Repository navigation
Conversation
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.
Benchmark reportthis PR run time: unchanged across 32 benchmarks
compile time: unchanged across 32 benchmarksNo significant changesEvery 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
|
| 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
left a comment
There was a problem hiding this comment.
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 4test_cond_replaycases fail on master and pass here, also withJAX_ENABLE_X64=1.ruff check/ruff format --checkpass 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_stackvisits the innermost handler first, so it adds itssubstitute_stackentry first, andwrap_fnwraps in the same order.seed → replay → substituteinside the branch therefore matches the outer stack, sosubstitute(replay(...), params)(elbo.py,infer/util.py,svi.py) behaves the same inside and outsidecond. - Passing the trace unsliced is correct for
cond, since it has no time axis. Inside ascanbody,condgets the per-step trace thatscanalready sliced with_replay_wrapper, which is why the nested case works without extra code. - No new branch-structure mismatch.
replaycopies the guide'sinferdict onto the site, andPytreeTracetreatsinferas static data thatlax.condcompares 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 tracecould already be raised on master when the outerreplayprocessed the branch's sites aftercond; now it is just raised earlier.
Requested changes
-
Add a test for the
scanclaim. The description says acondnested inscanis fixed by the same change. That's true (first row above), but nothing tests it, so a later change to howscanpasses the replay trace down could break it silently. Please add a test with acondinside ascanbody and a scanned guide, checking that the loss equals thejnp.whereversion. -
The first assertion in
test_cond_replayalready passes on master.assert_allclose(model_trace["level"]["value"], guide_trace["level"]["value"])doesn't catch the bug, because the outerreplayhandler 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 aftercond. -
Don't repeat the trace checks for every ELBO. The
replay/traceassertions don't depend onelbobut run four times. Please move them into a separate unparametrized test and keep only the loss comparison parametrized over the ELBOs.
Optional
-
Fail loudly on unknown
substitute_stackentries. This bug went unnoticed becausecond.wrap_fnsilently skips entry types it doesn't handle. Ending theif/elifchain in bothcond.wrap_fnandscan.scan_wrapperwithelse: 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.
-
SteinVI is also affected.
contrib/einstein/stein_loss.pycallsreplay(guide, tri)andreplay(seed(model, ...), tri), so guides or models withcondnow 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.
|
Thanks for the review and for running the extra cases. Updated in 1602339:
With master's |
|
@fehiepsi wdyt? |
Sample sites inside the branches of
condignorereplay. The ELBOs (Trace_ELBO,TraceMeanField_ELBO,TraceGraph_ELBO,RenyiELBO) run the model underreplay(model, guide_trace), so for a latent site insidecondthe model draws its own value from the prior instead of using the guide's value. The trace still records the guide's value, butcondreturns the fresh draw, and everything computed from it (here the observations) is scored against that draw. MCMC andPredictiveusesubstitute, whichcondalready handles, so they are not affected.Example: a latent
switchpicks the prior oflevel, and the data depend onlevel:SVI(model, AutoNormal(model), Adam(0.05), Trace_ELBO()), 3000 stepslevel = 4.98, final loss 452.35level = 8.35, final loss 35.66MCMC(NUTS(model), 500, 2000)level8.40Writing the same model without
cond(dist.Normal(jnp.where(switch > 0, 10.0, 0.0), 2.0)) giveslevel = 8.35and loss 35.66 on master as well.replayadds a("replay", trace)entry to thesubstitute_stackof control-flow messages (handlers.py#L254-L255).scanapplies it inside its body (scan.py#L328-L331, from #1693), butcondonly handlesconditionandsubstituteentries and skips it (cond.py#L36-L41). This PR applieshandlers.replaywith that trace inside the branches. Acondnested inscanis fixed by the same change, sincescanpasses its per-step replay trace down to thecondin its body.cond.wrap_fnandscan.scan_wrappernow raiseNotImplementedErrorfor an unknownsubstitute_stackentry instead of skipping it, so a new entry type cannot be ignored silently again (handlers.pyonly pushesreplay,conditionandsubstitute).In review, @juanitorduz found that the change also fixes, each compared with the same model written with
jnp.where: theTraceGraph_ELBOgradient for a non-reparameterized site (e.g. Poisson) insidecond; a subsampledplateinside a branch, which drew its own indices instead of the guide's; andSVI.runwithAutoNormal,AutoDiagonalNormal,AutoMultivariateNormalandAutoDelta. SteinVI is affected the same way, sincecontrib/einstein/stein_loss.pyruns the guide and model underreplay.Tests:
test/contrib/test_control_flow.py:test_cond_replaychecks that the value used aftercondis the guide's value underreplay;test_cond_replay_elbo(forTrace_ELBO,TraceMeanField_ELBO,TraceGraph_ELBOandRenyiELBO) checks that the loss equals the loss of the same density written withjnp.where;test_cond_in_scan_replay_elbodoes the same for acondinside ascanbody 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.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 lintpasses.No dependency changes.