Skip to content

fix(infer): reject scanned sample sites in TraceEnum_ELBO - #2440

Open
rpinho wants to merge 2 commits into
pyro-ppl:masterfrom
rpinho:fix-traceenum-scan
Open

rpinho wants to merge 2 commits into
pyro-ppl:masterfrom
rpinho:fix-traceenum-scan

Conversation

@rpinho

@rpinho rpinho commented Nov 18, 2026 •

Copy link
Copy Markdown

TraceEnum_ELBO can omit a time step when a model samples inside scan. Evaluate the loss for a model that observes four Normal draws inside scan. The patch raises NotImplementedError when the dependency trace encounters a sample from scan. The tests cover the model and guide and check a scan that only computes values.

Fixes #2433.

🤖 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
Comment thread numpyro/infer/elbo.py Outdated
)


class _RejectScannedSamples(Messenger):

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.

we use this just one... I think we can put this condition directly where its used withous needed the class

@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 picking this up. Checking for scanned sample sites in the non-enum dependency pass works better than the _PREV_ prefix check I suggested in #2433. It also catches history=0 and length=1, which crash on master with TypeError / KeyError, and it still accepts scans with only deterministic sites (loss 5.558609, same as Trace_ELBO). There is one gap, and the tests don't cover it.

Replayed latent sites skip the guard

_RejectScannedSamples looks for _scan_current_index in msg["infer"], but handlers.replay replaces msg["infer"] with the guide site's copy (handlers.py:253), which drops the key. This happens twice: in the replay branch of scan_wrapper inside the body, and again in the outer replay used by _get_latents / get_importance_trace. Observed sites are not replayed, which is why all the tests in this PR pass.

Repro on this branch:

import jax
import jax.numpy as jnp

import numpyro
from numpyro.contrib.control_flow import scan
import numpyro.distributions as dist
from numpyro.infer import Trace_ELBO, TraceEnum_ELBO


def model(ys):
    def transition(carry, _):
        x = numpyro.sample("x", dist.Normal(carry, 1.0))
        return x, x

    _, xs = scan(transition, 0.0, None, length=ys.shape[0])
    with numpyro.plate("t", ys.shape[0]):
        numpyro.sample("y", dist.Normal(xs, 1.0), obs=ys)


def guide(ys):
    with numpyro.plate("t", ys.shape[0]):
        numpyro.sample("x", dist.Delta(ys))


ys = jnp.array([1.0, 2.0])
print(Trace_ELBO().loss(jax.random.key(0), {}, model, guide, ys))
for seed in range(3):
    print(TraceEnum_ELBO().loss(jax.random.key(seed), {}, model, guide, ys))

Trace_ELBO gives 4.676. TraceEnum_ELBO gives 10.337, 12.977 and 18.632 for keys 0, 1 and 2, with no error. With 3 or 4 time steps it fails with ValueError: Incompatible shapes for broadcasting instead of NotImplementedError.

A possible fix is to check the scan's own trace in postprocess_message of the control_flow message, before any site is replayed:

class _RejectScannedSamples(Messenger):
    def postprocess_message(self, msg: Message) -> None:
        from numpyro.contrib.control_flow.scan import scan_wrapper

        if msg["type"] == "control_flow" and msg["fn"] is scan_wrapper:
            _, (pytree_trace, _) = msg["value"]
            if any(site["type"] == "sample" for site in pytree_trace.trace.values()):
                raise NotImplementedError(...)

I tried it by monkeypatching it into this branch. The model above then raises for 2 and 4 time steps, and so do example 1 from the issue and a scan that is only in the guide. Scans with only deterministic sites, or with no sites, still give the same loss as Trace_ELBO.

Tests

I swapped the guard for a few broken versions to see what the tests catch:

Guard Failing cases (of 10)
none (master) 8, all of rejects_scan
checks observed sites only 0
rejects every scan 1, accepts_pure_scan
  • test_trace_enum_elbo_rejects_scan: the history and length parameters don't change the code path. The check runs in get_nonreparam_deps, which traces without enum, so scan_wrapper never reaches scan_enum (if enum and history > 0). Every case uses an observed site, so none of them covers the gap above, and a real guide wouldn't have an observed site. Two cases with a latent site would be enough:

    @pytest.mark.parametrize("scan_in_guide", [False, True])
    def test_trace_enum_elbo_rejects_scan(scan_in_guide):
        def scanned(data):
            def transition(carry, y):
                pyro.sample("x", dist.Normal())
                return carry, None
    
            scan(transition, None, data)
    
        def plated(data):
            with pyro.plate("t", len(data)):
                pyro.sample("x", dist.Normal())
    
        model, guide = (plated, scanned) if scan_in_guide else (scanned, plated)
        with pytest.raises(NotImplementedError, match="TraceEnum_ELBO.*scan"):
            infer.TraceEnum_ELBO().loss(random.key(0), {}, model, guide, jnp.arange(4.0))

    On this branch the model-side case fails with ValueError and the guide-side case passes.

  • test_trace_enum_elbo_accepts_prev_site_name: I'd drop it. It guards against the _PREV_ prefix check from the issue, which was never merged, and none of the variants above make it fail.

  • test_trace_enum_elbo_accepts_pure_scan: worth keeping. It's the only test that fails if every scan is rejected. A numpyro.deterministic inside the body would make it stronger.

Smaller things

  • "Fixes #2433" will close the issue, but this PR raises an error instead of fixing the three bugs listed there. "Refs #2433" would keep it open for full support.
  • The error message and the docstring warning could point to the workaround: unroll the loop with numpyro.contrib.funsor.markov, which gives the right value (7.73777) for the HMM in the issue.
  • In the PR description, "Evaluate the loss for a model that observes four Normal draws inside scan." reads like an instruction. The before and after numbers (7.383 on master, 8.307 expected) would say more.

Checked locally: ruff check, ruff format --check and ty check pass on the changed files, the new tests pass, and test_enum_elbo, test_gradient, test_sdvi, test_pickle and test_control_flow give 149 passed, 2 xfailed, 4 xpassed.

@rpinho

rpinho commented Nov 19, 2026

Copy link
Copy Markdown
Author

Makes sense. I changed those.

@github-actions

Copy link
Copy Markdown

Benchmark report

this PR fix-traceenum-scan at 8499027a vs baseline master at fc7691c7

+ run time:     1 faster
  compile time: unchanged across 32 benchmarks

Significant changes (1)

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
+ svi_automultivariatenormal_eight_schools   894.9 ms  843.3 ms  -5.8%       4.92 s   4.47 s  -9.1%

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            4.1 ms   4.2 ms    +1.4%     309.6 ms  343.0 ms  +10.8%
  categorical_log_prob             2.5 ms   2.5 ms    -2.7%      65.3 ms   64.4 ms   -1.3%
  dirichlet_log_prob               647 µs   652 µs    +0.8%     819.9 ms  843.1 ms   +2.8%
  dirichlet_sample                60.4 ms  60.5 ms    +0.2%       3.21 s    3.22 s   +0.3%
  gamma_log_prob                   2.0 ms   2.0 ms    -0.0%       3.81 s    3.67 s   -3.6%
  gamma_sample                    21.9 ms  22.3 ms    +1.8%       3.08 s    2.88 s   -6.6%
  lkj_cholesky_sample              3.4 ms   3.5 ms    +2.2%       3.00 s    3.15 s   +4.8%
  mixture_same_family_log_prob     1.0 ms   1.0 ms    -1.8%      75.0 ms   72.2 ms   -3.7%
  multivariate_normal_log_prob     414 µs   388 µs  (-6.3%)     485.1 ms  456.8 ms   -5.8%
  normal_log_prob                  728 µs   687 µs  (-5.7%)      55.3 ms   53.4 ms   -3.4%
  normal_sample                   48.4 ms  47.9 ms    -1.1%     780.6 ms  791.0 ms   +1.3%
  stick_breaking_transform         5.9 ms   6.0 ms    +1.8%     208.9 ms  200.4 ms   -4.1%
  student_t_log_prob               2.4 ms   2.4 ms    +0.6%      78.4 ms   76.7 ms   -2.3%
  truncated_normal_log_prob        844 µs   844 µs    -0.0%      74.9 ms   67.1 ms  -10.4%

handlers

                                  ───────── run time ────────     ────── compile time ──────
  benchmark                       baseline  this PR         Δ     baseline   this PR       Δ
────────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    51.6 ms  53.0 ms     +2.6%       3.51 s    3.59 s   +2.3%
  log_density_hierarchical          4.3 ms   4.4 ms     +0.8%       1.00 s    1.05 s   +4.9%
  nested_handler_stack              1.6 ms   1.7 ms     +2.5%       1.1 ms    850 µs  -23.8%
  potential_energy_and_grad          28 µs    22 µs  (-21.4%)      87.9 ms   91.1 ms   +3.6%
  predictive_forward_sampling       1.06 s   1.03 s     -2.2%     230.6 ms  255.6 ms  +10.8%
  trace_seeded_model                946 µs   995 µs   (+5.1%)     706.6 ms  703.3 ms   -0.5%

mcmc

                             ─────── run time ───────     ───── compile time ─────
  benchmark                  baseline  this PR      Δ     baseline  this PR      Δ
──────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression      1.43 s   1.42 s  -0.7%       3.00 s   2.96 s  -1.2%
  nuts_dense_mass_funnel       1.69 s   1.67 s  -1.2%       2.66 s   2.67 s  +0.2%
  nuts_eight_schools           2.38 s   2.31 s  -3.0%       2.67 s   2.76 s  +3.4%
  nuts_hierarchical_glm        3.37 s   3.35 s  -0.4%       4.37 s   4.28 s  -2.2%
  nuts_logistic_regression     2.20 s   2.18 s  -1.1%       3.01 s   3.04 s  +1.2%
  nuts_vectorized_chains       4.71 s   4.57 s  -2.9%       3.58 s   3.70 s  +3.3%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 453.6 ms  441.9 ms  -2.6%       3.17 s   3.10 s  -2.4%
  svi_autodiagonalnormal_hierarchical          1.03 s    1.03 s  +0.3%       5.00 s   4.70 s  -5.9%
+ svi_automultivariatenormal_eight_schools   894.9 ms  843.3 ms  -5.8%       4.92 s   4.47 s  -9.1%
  svi_autonormal_logistic                      1.41 s    1.42 s  +0.9%       3.46 s   3.39 s  -2.0%
  svi_multi_particle_elbo                      1.86 s    1.82 s  -2.4%       3.48 s   3.57 s  +2.7%
  svi_trace_mean_field_elbo                    1.52 s    1.51 s  -0.4%       5.42 s   5.28 s  -2.5%
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-traceenum-scan
commit fc7691c7 8499027a
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-1019-azure-x86_64-with-glibc2.43, 4 CPUs.

Produced by this benchmark run.

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.

TraceEnum_ELBO returns wrong losses for models that use scan: drops the first step, skips the Markov contraction, ignores replay

2 participants