Repository navigation
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N
| ) | ||
|
|
||
|
|
||
| class _RejectScannedSamples(Messenger): |
There was a problem hiding this comment.
we use this just one... I think we can put this condition directly where its used withous needed the class
juanitorduz
left a comment
There was a problem hiding this comment.
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: thehistoryandlengthparameters don't change the code path. The check runs inget_nonreparam_deps, which traces withoutenum, soscan_wrappernever reachesscan_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
ValueErrorand 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. Anumpyro.deterministicinside 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.
Assisted-by: OpenAI Codex
|
Makes sense. I changed those. |
Benchmark reportthis PR + run time: 1 faster
compile time: unchanged across 32 benchmarksSignificant 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
|
| 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.
TraceEnum_ELBOcan omit a time step when a model samples insidescan. Evaluate the loss for a model that observes four Normal draws insidescan. The patch raisesNotImplementedErrorwhen the dependency trace encounters a sample fromscan. 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