Repository navigation
fix(control_flow): Honor scopes in cond and scan - #2443
aswanth-07 wants to merge 2 commits into
Conversation
Benchmark reportthis PR - run time: 1 slower, 0 faster
compile time: unchanged across 32 benchmarksSignificant 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
|
| 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
left a comment
There was a problem hiding this comment.
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
-
scan_enumstill ignores the scope entry. Under the funsorenumhandler everyscangoes toscan_enum, whose loop only handlesconditionandsubstitute. So any scoped model with an enumerated discrete site still has the bug from #2432. Example:z ~ Bernoulli(0.5)withinfer={"enumerate": "parallel"}outside the scan, a continuouslvlinside it, wrapped inscope(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 oflvl[0.288 1.337 2.136] AssertionError[0.288 1.337 2.136] The prototype in #2432 handled
scan_enumas well. What needs a separate change is the_PREV_naming for enumerated sites inside the scan (an HMM); that case raisesKeyErroron master, here, and with the change below, so the change doesn't make it worse. Adding the same branch toscan_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.pyandtest_infer_discrete.py. Please add a test comparing scoped and unscopedcontrib.funsor.log_densityfor a model like the one above. -
Add a nested test. Nested control flow works only because the scopes wrapped into the outer body push themselves onto the inner
control_flowmessage again;_ControlFlowUnscopepasses nothing down. The nested cases in the table pass, but nothing tests them. One test with acondinside ascanunderscope, compared with the unscopedlog_density, would cover it. -
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 acond/scanbody (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_historyfails for T = 10–13 with history 2 and 3. I get the same 7 failures on masterfc7691c7with 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_samplingcompile time (+40.7%) is noise: that benchmark runshierarchical_glm, which uses noscan,condorscope.
| elif subs_type == "scope": | ||
| seeded_fn = subs_map._wrap(seeded_fn) | ||
| scopes.append(subs_map) | ||
|
|
||
| if scopes: | ||
| seeded_fn = handlers._ControlFlowUnscope(seeded_fn, scopes) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| elif subs_type == "scope": | ||
| seeded_fn = subs_map._wrap(seeded_fn) | ||
| scopes.append(subs_map) |
There was a problem hiding this comment.
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.
| def process_message(self, msg: Message) -> None: | ||
| for handler in reversed(self.scopes): | ||
| handler._rename(msg, inverse=True) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Updated in b21c2e3.
A scoped HMM still raises
|
Fixes #2432.
When
scopewraps acondor ascan, traces show the scoped names, but handlers inside the control-flow body receive the original names. A substituted value forouter/levelcan therefore be ignored or replaced by the unrelated value forlevel. 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,scanand thescan_enumpath thatscantakes under the funsorenumhandler 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 acondorscanbody. 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
condnested in a scopedscan, and the funsor joint log density of a scopedscanbeside 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 forcond,scanand the enumeratedscan.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 -qgave 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 intest_module.pyfail at import because those packages are not installed locally.ty checkpass.Enumerated sites inside a scoped
scan, such as an HMM state, still need a separate change to their_PREV_naming. That case raisesKeyErroron 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.