Skip to content

fix(control_flow): Honor scopes in cond and scan - #2443

Open
aswanth-07 wants to merge 2 commits into
pyro-ppl:masterfrom
aswanth-07:fix/scoped-control-flow
Open

aswanth-07 wants to merge 2 commits into
pyro-ppl:masterfrom
aswanth-07:fix/scoped-control-flow

Conversation

@aswanth-07

@aswanth-07 aswanth-07 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2432.

When scope wraps a cond or a scan, traces show the scoped names, but handlers inside the control-flow body receive the original names. A substituted value for outer/level can therefore be ignored or replaced by the unrelated value for level. Scan replay can also resample a guide site.

I pass scopes through the control-flow handler stack in their original order, following the proposal from Juan Ignacio Torduz in #2432. Handlers outside a scope see the prefixed names while the body runs. The local trace records the original names so the outer stack applies each scope once when re-emitting the sites. cond, scan and the scan_enum path that scan takes under the funsor enum handler all build the body this way.

Behavior change: on master, substitute(scope(model, prefix="a"), data={"x": v}) with the unscoped key "x" set a site inside a cond or scan body. With this change the body sees "a/x", as sites outside control flow already do, so the unscoped key no longer matches and a seeded model samples that site from its prior without an error. Models that passed unscoped keys to work around #2432 need the scoped name.

The regression tests check nested scopes with different separators, a same-name site outside the scopes, the expected Normal joint log density under substitution and conditioning, a deterministic value that depends on replayed scan samples, a cond nested in a scoped scan, and the funsor joint log density of a scoped scan beside an enumerated discrete site. All seven cases fail on master. The enumerated case also failed on this PR's first head. A separate NUTS run with a fixed seed produced identical draws for the scoped and unscoped models for cond, scan and the enumerated scan.

  • python -m pytest test/contrib/test_control_flow.py test/test_handlers.py test/contrib/test_funsor.py test/contrib/test_infer_discrete.py test/contrib/test_module.py -q gave 160 passed and 4 expected failures on Windows, Python 3.11 and JAX 0.10.2. The same files from master give 153 passed and 4 expected failures; the extra seven are this PR's tests. In both runs the 36 Flax and Equinox tests in test_module.py fail at import because those packages are not installed locally.
  • Ruff formatting and lint, the license-header check and ty check pass.

Enumerated sites inside a scoped scan, such as an HMM state, still need a separate change to their _PREV_ naming. That case raises KeyError on master and with this change. I ran the focused suite above on CPU.

AI assistance disclosure: AI-assisted development tools were used during investigation and implementation. The reported tests were run against the final diff.

@github-actions github-actions Bot added the awaiting review Awaiting review from maintainers label Nov 19, 2026
@aswanth-07
aswanth-07 marked this pull request as ready for review November 19, 2026 12:08
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Benchmark report

this PR fix/scoped-control-flow at b21c2e38 vs baseline master at fc7691c7

- run time:     1 slower, 0 faster
  compile time: unchanged across 32 benchmarks

Significant changes (1)

                              ─────── run time ───────     ───── compile time ─────
  benchmark                   baseline  this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────
- truncated_normal_log_prob     1.0 ms   1.1 ms  +8.6%      71.8 ms  72.0 ms  +0.3%

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.8 ms   3.7 ms  -1.4%     184.2 ms  207.9 ms  +12.9%
  categorical_log_prob             2.1 ms   2.0 ms  -3.0%      62.8 ms   64.4 ms   +2.7%
  dirichlet_log_prob               576 µs   581 µs  +0.9%     993.6 ms  944.7 ms   -4.9%
  dirichlet_sample                95.8 ms  94.3 ms  -1.6%       2.43 s    2.39 s   -1.7%
  gamma_log_prob                   1.5 ms   1.5 ms  -1.1%       5.49 s    5.46 s   -0.6%
  gamma_sample                    30.8 ms  31.0 ms  +0.5%       2.26 s    2.28 s   +0.9%
  lkj_cholesky_sample              3.5 ms   3.5 ms  +0.6%       2.46 s    2.46 s   -0.0%
  mixture_same_family_log_prob     817 µs   834 µs  +2.1%      69.6 ms   72.0 ms   +3.4%
  multivariate_normal_log_prob     670 µs   698 µs  +4.2%     449.6 ms  460.3 ms   +2.4%
  normal_log_prob                  1.0 ms   1.0 ms  -0.4%      68.7 ms   60.8 ms  -11.5%
  normal_sample                   56.0 ms  55.6 ms  -0.8%     683.2 ms  688.5 ms   +0.8%
  stick_breaking_transform         5.3 ms   5.4 ms  +2.2%     178.3 ms  180.9 ms   +1.4%
  student_t_log_prob               1.8 ms   1.8 ms  +0.7%      73.9 ms   75.0 ms   +1.5%
- truncated_normal_log_prob        1.0 ms   1.1 ms  +8.6%      71.8 ms   72.0 ms   +0.3%

handlers

                                  ───────── run time ────────     ────── compile time ─────
  benchmark                       baseline   this PR        Δ     baseline   this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    43.6 ms   44.4 ms    +1.8%       3.41 s    3.53 s  +3.7%
  log_density_hierarchical          3.3 ms    3.3 ms    +1.9%       1.04 s    1.06 s  +1.4%
  nested_handler_stack              1.4 ms    1.4 ms    -0.5%       653 µs    675 µs  +3.3%
  potential_energy_and_grad          25 µs     27 µs  (+5.5%)      80.6 ms   84.8 ms  +5.2%
  predictive_forward_sampling     836.0 ms  836.4 ms    +0.1%     312.1 ms  329.5 ms  +5.6%
  trace_seeded_model                726 µs    776 µs  (+6.9%)     679.1 ms  687.8 ms  +1.3%

mcmc

                             ─────── run time ───────     ───── compile time ─────
  benchmark                  baseline  this PR      Δ     baseline  this PR      Δ
──────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression      1.28 s   1.26 s  -1.4%       2.96 s   2.87 s  -2.9%
  nuts_dense_mass_funnel       1.49 s   1.51 s  +0.9%       2.64 s   2.52 s  -4.7%
  nuts_eight_schools           2.10 s   2.09 s  -0.2%       2.68 s   2.53 s  -5.7%
  nuts_hierarchical_glm        2.83 s   2.79 s  -1.3%       4.25 s   4.27 s  +0.3%
  nuts_logistic_regression     1.99 s   1.95 s  -1.9%       2.99 s   2.93 s  -1.9%
  nuts_vectorized_chains       4.20 s   4.14 s  -1.4%       3.29 s   3.24 s  -1.5%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 401.7 ms  400.7 ms  -0.2%       3.04 s   2.93 s  -3.6%
  svi_autodiagonalnormal_hierarchical        861.6 ms  865.8 ms  +0.5%       4.70 s   4.50 s  -4.4%
  svi_automultivariatenormal_eight_schools   763.7 ms  753.6 ms  -1.3%       4.58 s   4.34 s  -5.3%
  svi_autonormal_logistic                      1.30 s    1.31 s  +0.7%       3.29 s   3.41 s  +3.4%
  svi_multi_particle_elbo                      1.59 s    1.57 s  -1.6%       3.39 s   3.37 s  -0.6%
  svi_trace_mean_field_elbo                    1.24 s    1.25 s  +0.8%       5.27 s   5.22 s  -0.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/scoped-control-flow
commit fc7691c7 b21c2e38
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-1020-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 picking this up. The handler ordering looks right to me for cond and the non-enumerated scan, and the tests cover the collision case from #2432. I'm requesting changes for one remaining gap (scan_enum, item 1); the other items are smaller.

What I checked

I ran the PR head (b9abdce4) against master (fc7691c7) with JAX 0.10.2, and with JAX 0.12.1 on Python 3.14 to match CI:

  • The 5 new tests fail on master and pass here.
  • test_control_flow.py, test_handlers.py, test_funsor.py, test_infer_discrete.py, test_module.py, hsgp/test_approximation.py: 255 passed, 4 xfailed.
  • The script from #2432 prints the expected output on both JAX versions.

I also tried some harder cases, each compared with the unscoped model:

Case master this PR
cond in scan, scan in cond, user scope inside the body plus an outer scope (log_density) AssertionError (prior draw without a key) ✗ matches ✓
scope(..., hide_types=["plate"]) with a plate in the body, substitute on a/x ignored ✗ applied ✓
Predictive(posterior_samples={"a/lvl": 50.0}), mean of a/y −0.23 ✗ 50.00 ✓
SVI + AutoNormal on a scoped scan, final loss 71.11 vs 15.04 ✗ 15.04 = 15.04 ✓
replay in scan with an unscoped lvl next to the scoped one uses the unscoped site's value (−102.44) ✗ uses the guide's a/lvl ✓
get_model_relations on a scoped scan no edges ✗ same edges as unscoped ✓

Why I think the ordering is right: substitute_stack is filled innermost handler first and the body wraps in the same order, so handlers outside a scope see the scoped name and handlers inside it see the local one. The unscope runs after all of them and before the body's trace, so the outer scope renames each re-emitted site exactly once. plate raises on control_flow messages, so the early return in scope.process_message never skips plate frames.

Requested changes

  1. scan_enum still ignores the scope entry. Under the funsor enum handler every scan goes to scan_enum, whose loop only handles condition and substitute. So any scoped model with an enumerated discrete site still has the bug from #2432. Example: z ~ Bernoulli(0.5) with infer={"enumerate": "parallel"} outside the scan, a continuous lvl inside it, wrapped in scope(model, prefix="a"):

    unscoped scoped, this PR scoped, with the change below
    contrib.funsor.log_density, seeded −6.0864 −14.7184 (no error) −6.0864
    contrib.funsor.log_density, unseeded −6.0864 AssertionError −6.0864
    NUTS, mean of lvl [0.288 1.337 2.136] AssertionError [0.288 1.337 2.136]

    The prototype in #2432 handled scan_enum as well. What needs a separate change is the _PREV_ naming for enumerated sites inside the scan (an HMM); that case raises KeyError on master, here, and with the change below, so the change doesn't make it worse. Adding the same branch to scan_enum.body_fn:

    scopes = []
    for subs_type, subs_map in substitute_stack:
        subs_fn = partial(_subs_wrapper, subs_map, i, length)
        if subs_type == "condition":
            seeded_fn = handlers.condition(seeded_fn, condition_fn=subs_fn)
        elif subs_type == "substitute":
            seeded_fn = handlers.substitute(seeded_fn, substitute_fn=subs_fn)
        elif subs_type == "scope":
            seeded_fn = subs_map._wrap(seeded_fn)
            scopes.append(subs_map)
    if scopes:
        seeded_fn = handlers._ControlFlowUnscope(seeded_fn, scopes)

    gives 76 passed, 3 xfailed on test_control_flow.py, test_funsor.py and test_infer_discrete.py. Please add a test comparing scoped and unscoped contrib.funsor.log_density for a model like the one above.

  2. Add a nested test. Nested control flow works only because the scopes wrapped into the outer body push themselves onto the inner control_flow message again; _ControlFlowUnscope passes nothing down. The nested cases in the table pass, but nothing tests them. One test with a cond inside a scan under scope, compared with the unscoped log_density, would cover it.

  3. Mention the behavior change in the description. On master, substitute(scope(model, prefix="a"), data={"x": v}) with the unscoped key set the site inside a cond/scan body (a/x = [3.0, 4.0]). With this PR the key is ignored and the site is drawn from the prior, without an error. The new behavior is correct, but anyone who used unscoped keys to work around the bug loses those values silently, so it's worth a line in the description and release notes.

Coordination with #2423

#2423 (approved) ends the same if/elif chains in cond.wrap_fn and scan_wrapper with else: raise NotImplementedError(...). Whichever PR lands second needs the "scope" branch before that else (inline comment on cond.py). Once both are in, a test for scoped cond under replay (the SVI path) would cover a case neither PR tests.

CI

The failures don't come from this PR:

  • test-inference (3.14): test_funsor.py::test_scan_history fails for T = 10–13 with history 2 and 3. I get the same 7 failures on master fc7691c7 with JAX 0.12.1, which came out after the last green master run.
  • test-modeling: apt failed to download graphviz.
  • test-inference (3.11) was cancelled, not failed.
  • The predictive_forward_sampling compile time (+40.7%) is noise: that benchmark runs hierarchical_glm, which uses no scan, cond or scope.

Comment on lines +333 to +338
elif subs_type == "scope":
seeded_fn = subs_map._wrap(seeded_fn)
scopes.append(subs_map)

if scopes:
seeded_fn = handlers._ControlFlowUnscope(seeded_fn, scopes)

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.

scan_enum needs this branch and the unscope wrapper too. It currently skips "scope" entries, so a scoped model under the funsor enum handler still looks up local names inside the body. Numbers and the suggested change are in item 1 of the review.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in b21c2e3. scan_enum.body_fn now applies the scope entries and _ControlFlowUnscope exactly as scan_wrapper does. test_scoped_scan_enum_matches_unscoped fails on the previous head and passes now.

Comment on lines +43 to +45
elif subs_type == "scope":
seeded_fn = subs_map._wrap(seeded_fn)
scopes.append(subs_map)

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.

If #2423 lands first, this branch has to come before its new else: raise NotImplementedError(...) (here and in scan_wrapper). Otherwise every scoped model that uses cond/scan raises.

Comment thread numpyro/handlers.py
Comment on lines +829 to +831
def process_message(self, msg: Message) -> None:
for handler in reversed(self.scopes):
handler._rename(msg, inverse=True)

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.

Nit: this relies on removeprefix exactly undoing each scope's rename. That holds because the only handlers between the scope wrappers and this one (condition, substitute, replay) don't rename sites. Could the comment above say so? A future substitute_stack entry that renames sites would break this without any error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in b21c2e3. The comment above _ControlFlowUnscope now says that removeprefix relies on condition, substitute and replay never renaming sites, and that a renaming substitute_stack entry would break it.

Under the funsor enum handler, scan runs through scan_enum, whose body
applied condition and substitute entries but skipped scope entries. A
scoped model with an enumerated discrete site therefore looked up local
names inside the body, so substituted values were ignored.

Apply scope entries and the unscope wrapper in scan_enum as scan_wrapper
does. Add a funsor log-density test for a scoped scan beside an enumerated
site, a test for cond nested in a scoped scan, and document why the
unscope wrapper can reverse each prefix.
@aswanth-07

Copy link
Copy Markdown
Contributor Author

Updated in b21c2e3.

  1. scan_enum now wraps its body with each scope entry and _ControlFlowUnscope, the same way scan_wrapper does. test_scoped_scan_enum_matches_unscoped in test_funsor.py compares the scoped and unscoped contrib.funsor.log_density for your model shape: a parallel-enumerated Bernoulli outside the scan and a continuous site inside it. The test fails on master and on the previous head, where the first unrolled level value comes from the prior and differs by 0.083, and passes now. NUTS on that model gives identical draws for the scoped and unscoped versions; master and the previous head raise AssertionError.
  2. test_scoped_cond_in_scan_matches_unscoped runs a cond inside a scoped scan against the unscoped log_density. It fails on master and passes on both heads, as you found.
  3. The description now has a behavior-change paragraph for unscoped keys inside cond and scan bodies.

A scoped HMM still raises KeyError: 'x' on master and here, so the _PREV_ naming stays for a separate change. #2423 adds its else only to cond.wrap_fn and scan_wrapper; whichever PR lands second needs the scope branch ahead of it in those two chains.

test_control_flow.py, test_handlers.py, test_funsor.py, test_infer_discrete.py and test_module.py give 160 passed and 4 xfailed on this head and 153 passed and 4 xfailed on master with JAX 0.10.2; the extra seven are this PR's tests. In both runs the 36 Flax and Equinox tests in test_module.py fail at import because those packages are not installed locally, and I skipped hsgp/test_approximation.py because scikit-learn is not installed. Ruff, the license-header check and ty check pass.

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.

Sites inside cond/scan ignore an enclosing scope, so substitute, condition and replay miss them (silently wrong MCMC posteriors)

2 participants