Skip to content

fix(control_flow): replay sample sites inside cond - #2423

Open
sohailshk wants to merge 2 commits into
pyro-ppl:masterfrom
sohailshk:fix/cond-replay
Open

sohailshk wants to merge 2 commits into
pyro-ppl:masterfrom
sohailshk:fix/cond-replay

Conversation

@sohailshk

@sohailshk sohailshk commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Sample sites inside the branches of cond ignore replay. The ELBOs (Trace_ELBO, TraceMeanField_ELBO, TraceGraph_ELBO, RenyiELBO) run the model under replay(model, guide_trace), so for a latent site inside cond the model draws its own value from the prior instead of using the guide's value. The trace still records the guide's value, but cond returns the fresh draw, and everything computed from it (here the observations) is scored against that draw. MCMC and Predictive use substitute, which cond already handles, so they are not affected.

Example: a latent switch picks the prior of level, and the data depend on level:

def model(y):
    switch = numpyro.sample("switch", dist.Normal(0.0, 1.0))
    level = cond(
        switch > 0,
        lambda _: numpyro.sample("level", dist.Normal(10.0, 2.0)),
        lambda _: numpyro.sample("level", dist.Normal(0.0, 2.0)),
        None,
    )
    with numpyro.plate("data", y.shape[0]):
        numpyro.sample("y", dist.Normal(level, 1.0), obs=y)


y = 8.5 + jax.random.normal(jax.random.key(3), (20,))  # mean(y) = 8.39
master this PR
SVI(model, AutoNormal(model), Adam(0.05), Trace_ELBO()), 3000 steps level = 4.98, final loss 452.35 level = 8.35, final loss 35.66
MCMC(NUTS(model), 500, 2000) posterior mean of level 8.40 same

Writing the same model without cond (dist.Normal(jnp.where(switch > 0, 10.0, 0.0), 2.0)) gives level = 8.35 and loss 35.66 on master as well.

replay adds a ("replay", trace) entry to the substitute_stack of control-flow messages (handlers.py#L254-L255). scan applies it inside its body (scan.py#L328-L331, from #1693), but cond only handles condition and substitute entries and skips it (cond.py#L36-L41). This PR applies handlers.replay with that trace inside the branches. A cond nested in scan is fixed by the same change, since scan passes its per-step replay trace down to the cond in its body. cond.wrap_fn and scan.scan_wrapper now raise NotImplementedError for an unknown substitute_stack entry instead of skipping it, so a new entry type cannot be ignored silently again (handlers.py only pushes replay, condition and substitute).

In review, @juanitorduz found that the change also fixes, each compared with the same model written with jnp.where: the TraceGraph_ELBO gradient for a non-reparameterized site (e.g. Poisson) inside cond; a subsampled plate inside a branch, which drew its own indices instead of the guide's; and SVI.run with AutoNormal, AutoDiagonalNormal, AutoMultivariateNormal and AutoDelta. SteinVI is affected the same way, since contrib/einstein/stein_loss.py runs the guide and model under replay.

Tests:

  • New in test/contrib/test_control_flow.py: test_cond_replay checks that the value used after cond is the guide's value under replay; test_cond_replay_elbo (for Trace_ELBO, TraceMeanField_ELBO, TraceGraph_ELBO and RenyiELBO) checks that the loss equals the loss of the same density written with jnp.where; test_cond_in_scan_replay_elbo does the same for a cond inside a scan body with a scanned guide (Trace_ELBO, TraceGraph_ELBO). All 7 cases fail on master and pass here.
  • pytest test/contrib/test_control_flow.py test/contrib/test_funsor.py: 54 passed, 1 xfailed.
  • Before the test changes: pytest test/contrib/test_control_flow.py test/contrib/test_funsor.py test/contrib/test_infer_discrete.py test/infer/test_infer_util.py test/infer/test_svi.py test/test_handlers.py test/infer/test_gradient.py: 318 passed, 4 skipped, 4 xfailed.
  • make lint passes.

No dependency changes.

Under replay (used by Trace_ELBO, TraceMeanField_ELBO, TraceGraph_ELBO
and RenyiELBO to run the model against the guide trace), the sample
sites inside the branches of cond drew fresh values instead of taking
the guide's values. The trace recorded the guide values afterwards, but
the value returned by cond, and everything computed from it, used the
fresh draws. Apply the replay entries of the substitute stack inside the
branches, as scan already does.
@github-actions github-actions Bot added the awaiting review Awaiting review from maintainers label Nov 10, 2026
@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Benchmark report

this PR fix/cond-replay at 16023397 vs baseline master at 0f987499

  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            3.1 ms   3.1 ms     -0.6%     167.1 ms  167.7 ms  +0.4%
  categorical_log_prob             1.3 ms   1.4 ms     +1.5%      47.6 ms   47.1 ms  -1.0%
  dirichlet_log_prob               398 µs   412 µs     +3.4%     842.3 ms  837.3 ms  -0.6%
  dirichlet_sample                75.3 ms  75.7 ms     +0.5%     666.9 ms  660.4 ms  -1.0%
  gamma_log_prob                   1.3 ms   1.3 ms     +0.7%       3.56 s    3.59 s  +0.7%
  gamma_sample                    28.1 ms  28.3 ms     +0.8%     602.7 ms  598.1 ms  -0.8%
  lkj_cholesky_sample              4.3 ms   4.3 ms     +0.3%     826.5 ms  842.8 ms  +2.0%
  mixture_same_family_log_prob     560 µs   563 µs     +0.6%      56.4 ms   57.9 ms  +2.6%
  multivariate_normal_log_prob     445 µs   504 µs  (+13.2%)     370.0 ms  379.0 ms  +2.4%
  normal_log_prob                  405 µs   435 µs   (+7.4%)      46.7 ms   43.0 ms  -8.0%
  normal_sample                   36.7 ms  36.6 ms     -0.3%     133.8 ms  139.7 ms  +4.4%
  stick_breaking_transform         4.5 ms   4.6 ms     +0.3%     156.9 ms  155.7 ms  -0.7%
  student_t_log_prob               2.5 ms   2.5 ms     -0.2%     119.5 ms  109.7 ms  -8.2%
  truncated_normal_log_prob        432 µs   467 µs   (+8.0%)      45.4 ms   42.9 ms  -5.6%

handlers

                                  ──────── run time ───────     ────── compile time ──────
  benchmark                       baseline   this PR      Δ     baseline   this PR       Δ
──────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    31.3 ms   31.7 ms  +1.3%       2.55 s    2.56 s   +0.3%
  log_density_hierarchical          2.5 ms    2.4 ms  -1.5%     879.6 ms  862.3 ms   -2.0%
  nested_handler_stack              1.0 ms    1.0 ms  +0.3%       594 µs    679 µs  +14.2%
  potential_energy_and_grad          21 µs     21 µs  -1.4%      76.7 ms   67.4 ms  -12.1%
  predictive_forward_sampling     383.3 ms  395.3 ms  +3.1%     135.3 ms  120.4 ms  -11.0%
  trace_seeded_model                532 µs    536 µs  +0.8%     349.0 ms  354.2 ms   +1.5%

mcmc

                             ──────── run time ───────     ───── compile time ─────
  benchmark                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression    497.5 ms  499.6 ms  +0.4%       2.00 s   1.99 s  -0.2%
  nuts_dense_mass_funnel     734.9 ms  741.5 ms  +0.9%       1.67 s   1.71 s  +2.3%
  nuts_eight_schools         855.2 ms  854.5 ms  -0.1%       1.75 s   1.77 s  +0.8%
  nuts_hierarchical_glm        2.17 s    2.18 s  +0.2%       2.99 s   3.05 s  +2.0%
  nuts_logistic_regression   863.6 ms  860.9 ms  -0.3%       2.04 s   2.09 s  +2.4%
  nuts_vectorized_chains       1.60 s    1.58 s  -1.3%       1.91 s   1.88 s  -1.3%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 210.1 ms  208.6 ms  -0.7%       2.07 s   2.10 s  +1.3%
  svi_autodiagonalnormal_hierarchical        676.0 ms  665.9 ms  -1.5%       3.38 s   3.33 s  -1.4%
  svi_automultivariatenormal_eight_schools   504.2 ms  506.7 ms  +0.5%       3.46 s   3.31 s  -4.4%
  svi_autonormal_logistic                    577.3 ms  582.2 ms  +0.8%       2.36 s   2.40 s  +1.7%
  svi_multi_particle_elbo                    832.3 ms  815.2 ms  -2.1%       2.35 s   2.57 s  +9.0%
  svi_trace_mean_field_elbo                  773.2 ms  766.8 ms  -0.8%       3.70 s   3.88 s  +4.8%
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/cond-replay
commit 0f987499 16023397
numpyro 0.22.0 0.22.0
jax 0.12.0.1 0.12.0.1
backend cpu cpu
python 3.14.4 3.14.4

Runner: Linux-7.0.0-1019-azure-x86_64-with-glibc2.43, 4 CPUs.

Produced by this benchmark run.

@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 for the fix and the clear write-up. The change to cond.py looks correct to me and matches how scan already applies replay. The requested changes are all about the tests; the fix itself is fine.

What I checked

I ran the PR head (4ceb911d) locally with JAX 0.10.2:

  • test/contrib/test_control_flow.py: 12 passed, 1 xfailed. The 4 test_cond_replay cases fail on master and pass here, also with JAX_ENABLE_X64=1.
  • ruff check / ruff format --check pass on both files.

I also tried some harder cases, each comparing a cond model against the same density written with jnp.where:

Case master this PR
cond nested in scan, scanned guide, Trace_ELBO / TraceGraph_ELBO loss 24.195 vs 15.001 ✗ 15.001 = 15.001 ✓
SVI.run with AutoNormal, AutoDiagonalNormal, AutoMultivariateNormal, AutoDelta final loss ~376–447 vs ~35 ✗ match ✓
Poisson latent inside cond (not reparameterizable), TraceGraph_ELBO gradient w.r.t. guide rate −0.566 vs −0.865 ✗ −0.865 = −0.865 ✓
Subsampled plate inside both branches, under replay model subsample indices [5 7 9] ≠ guide [7 8 2] ✗ indices and z match the guide ✓

So the PR fixes more than the description says: on master, TraceGraph_ELBO gave a wrong gradient for a non-reparameterized site inside cond, and a subsampled plate inside a branch drew its own indices instead of the guide's. Might be worth adding those to the description.

Why I think the change is right:

  • Handler order. apply_stack visits the innermost handler first, so it adds its substitute_stack entry first, and wrap_fn wraps in the same order. seed → replay → substitute inside the branch therefore matches the outer stack, so substitute(replay(...), params) (elbo.py, infer/util.py, svi.py) behaves the same inside and outside cond.
  • Passing the trace unsliced is correct for cond, since it has no time axis. Inside a scan body, cond gets the per-step trace that scan already sliced with _replay_wrapper, which is why the nested case works without extra code.
  • No new branch-structure mismatch. replay copies the guide's infer dict onto the site, and PytreeTrace treats infer as static data that lax.cond compares across branches. Both branches replay the same site name from the same guide entry, so it always matches.
  • No new errors. Site … must be sampled in trace could already be raised on master when the outer replay processed the branch's sites after cond; now it is just raised earlier.

Requested changes

  1. Add a test for the scan claim. The description says a cond nested in scan is fixed by the same change. That's true (first row above), but nothing tests it, so a later change to how scan passes the replay trace down could break it silently. Please add a test with a cond inside a scan body and a scanned guide, checking that the loss equals the jnp.where version.

  2. The first assertion in test_cond_replay already passes on master. assert_allclose(model_trace["level"]["value"], guide_trace["level"]["value"]) doesn't catch the bug, because the outer replay handler already wrote the guide value into the trace. On master the test fails at the second assertion (fn.mean: actual −1.578, desired 7.623). Please drop it or add a comment that it only checks the recorded trace, not the value used after cond.

  3. Don't repeat the trace checks for every ELBO. The replay/trace assertions don't depend on elbo but run four times. Please move them into a separate unparametrized test and keep only the loss comparison parametrized over the ELBOs.

Optional

  1. Fail loudly on unknown substitute_stack entries. This bug went unnoticed because cond.wrap_fn silently skips entry types it doesn't handle. Ending the if/elif chain in both cond.wrap_fn and scan.scan_wrapper with

    else:
        raise NotImplementedError(f"Unsupported substitute_stack entry: {subs_type}")

    would make a future handler that adds a new entry type fail instead of being ignored.

  2. SteinVI is also affected. contrib/einstein/stein_loss.py calls replay(guide, tri) and replay(seed(model, ...), tri), so guides or models with cond now replay particle values inside branches too. It's the same kind of fix, but worth a line in the description since nothing tests it.

Related bug, not for this PR

replay.process_message doesn't skip sites that cond has already processed (_control_flow_done), while substitute and condition do. With substitute(replay(model, guide_tr), data={"k": 42.}):

  • without cond, the model returns 42 and the trace records 42;
  • with cond, on both master and this PR, the model returns 42 but the trace records the guide's value.

The outer replay writes the guide value back into the trace after cond, while substitute skips that step. No current ELBO path hits this, since params only contains param sites, so it's better as a separate issue.

Also, I don't think the benchmark report is related to this change: no benchmark uses cond, and the predictive_forward_sampling compile-time change (+43.6%) is a single measurement in a range the report says moves about 20% between identical runs.

…BO checks

Raise NotImplementedError for unknown substitute_stack entries in
cond.wrap_fn and scan.scan_wrapper.
@sohailshk

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for running the extra cases. Updated in 1602339:

  1. Added test_cond_in_scan_replay_elbo: a cond inside a scan body with a scanned guide, loss compared with the jnp.where version for Trace_ELBO and TraceGraph_ELBO. Fails on master, passes here.
  2. Dropped the first assertion of test_cond_replay, since it already passes on master.
  3. test_cond_replay is now unparametrized and only checks the value used after cond; the loss comparison is in test_cond_replay_elbo, parametrized over the four ELBOs.
  4. Took the optional suggestion: cond.wrap_fn and scan.scan_wrapper now raise NotImplementedError for an unknown substitute_stack entry. handlers.py only pushes replay, condition and substitute. I left scan_enum alone: its loop handles only condition and substitute and skips replay, so an else there would raise for replay under enum().
  5. The description now lists the extra cases you found (credited to you) and the SteinVI note.

With master's cond.py, 7 of the new cases fail; with this branch test_control_flow.py and test_funsor.py give 54 passed, 1 xfailed. I'll leave the replay / _control_flow_done trace issue for a separate issue.

@juanitorduz

Copy link
Copy Markdown
Collaborator

@fehiepsi wdyt?

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