Skip to content

Keep scaled continuation means finite near float max - #628

Merged
hmgaudecker merged 1621 commits into
mainfrom
codex/514-continuation-overflow
Nov 8, 2026
Merged

hmgaudecker merged 1621 commits into
mainfrom
codex/514-continuation-overflow

Conversation

@hmgaudecker

@hmgaudecker hmgaudecker commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Scaled continuation expectations can overflow before normalization when values are near the floating-point limit. Small coefficients and small values can also underflow before their finite normalized mean is formed. This change normalizes coefficient mantissas and tracks binary scales so these intermediate operations preserve the represented contributions.

The derivative rule forms normalized finite slopes and transports the centered residual separately. This preserves finite coefficient derivatives when the rounded mean equals a neighboring value, while retaining zero-weight and nonfinite-input conventions. The implementation uses existing JAX binary scaling; it adds no runtime accuracy certificate or exact-arithmetic fallback.

Validation covers float32 and float64 eager, JIT, mapped, forward- and reverse-mode paths with exact-rational references, public continuation/policy examples, and existing CE controls. Tests also check equivalent coefficient/shift representations and the physical scale returned by the shared helper.

The added arithmetic has a measured cost. Relative to the prior revision, the bounded CPU kernel is about 1.5–1.8 times slower for primal evaluation and 1.17–1.20 times slower for coefficient gradients. A matched bounded Eichenbaum A100 solve showed no measurable slowdown: warm solves were 6.16 seconds, within the repeated baseline's 0.44% spread, with unchanged device peak memory and bitwise-identical values and sampled policies. This covers the tested profile; whole-model differentiation and larger calibration grids remain unmeasured. CPU kernel and differentiation cost acceptance remains open.

Process-edge continuation now uses one shared corner program. The loop keeps the certainty equivalent inside each joint corner and retains the original corner order. This removes exponential copies of the continuation graph without changing the economic rule. A regression test limits program construction to two continuation programs.

The additional checks cover 202 native mathematical cases and 1,106 source mutations. On the benchmark runner's V100, the selected ACA simulation program built in 2.13 seconds; both old-code arms exceeded 82 seconds in that phase before the 120-second process cap. The repaired replay matched the captured outputs and layouts exactly, rejected output mutations, and ran three warm calls in 2.412–2.414 seconds. Baseline warm time and a full-model speedup remain unmeasured.

The normal ACA benchmark class completed on the V100 with a fresh JAX cache and configured FP64: cold automatic solve and simulation took 1,803.34 seconds, the following warm call took 250.28 seconds, and the measured CPU-memory peak was 11.14 GiB. Total benchmark-cache setup took 36 minutes 44 seconds. These are one cold and one warm observation on eight CPU cores; a source-only certificate used separate cores during part of the run. There is no controlled full-baseline or A/A comparison. The earlier graph-construction hang is repaired; the remaining full-model cost needs review. This direct invocation used the original benchmark class and measurement subprocess; it does not establish a successful GitHub ASV CLI run.

@read-the-docs-community

read-the-docs-community Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

hmgaudecker and others added 28 commits October 30, 2026 00:47
The lookup lane moved canonical-Q evaluation into the compiled reader,
which reaches `_evaluate_canonical_Q_at_actions` through the regime's
`Q_and_F` slot; the stub test patched the old outer seam and its stub
regime lacked the slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
The shape template and the compiled program each traced the whole
native Case-R and Case-U body. The demand-free numerical stages now sit
behind one inlined jit on an object both callables hold, so the compile
reuses the template's trace: compile waves -2.2 to -2.5 s on the Case-R
toy and -3.5 to -4.5 s on the NNBEGM-U toy, cache off, panels unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
The host looped over source chunks, dispatching every query program and
syncing its status per chunk; one EKL period at query chunk 1 paid
~3 ms per chunk on the host. A `_chunks` core now runs one fori_loop
over the period's chunks, carrying the bank, per-query status and
landing totals, so a period is three dispatches and one status read:
4096 chunks 12.6 s -> 2.1 ms on the probe, bit-identical. Workspace
narrowing recomputes only when that lowers the declared answer peak and
otherwise halves the chunk on the first pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
… not merged)

Below the first arrival level, rebuilt action problems read a stored
arrival-adjusted surface A_{R->U} instead of recursing to the horizon.
Grid-point values unchanged; off-grid period-0 values move (see
tests/data/arrival_pricing_depth). Persistence of surfaces for loaded
solutions not yet implemented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Save writes each stored arrival surface like V; load verifies and
materialises them so a loaded solution replays arrivals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Price arrivals one level deep with stored, persisted continuation
surfaces; per-period cost no longer grows with remaining arrival dates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Budgeted chunk admission refused every policy route except finite
NNBEGM, so DC-EGM simulate under device_memory_bytes failed after the
policy-first switch. The read now runs as a profiled, admitted producer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
The combination is refused at Model build; the message says why and
names NBEGM, GridSearch or a nested NNBEGM parent as alternatives, or
states the current-IID limit when the child draws current shocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
egmtrace keeps a numerically identical publisher across rebinds, so its
point is not the function's point; the shape guard walked into the
stale point's context and hit host node arrays. The guard now rechecks
the retained publisher and captures the function's own point. The
NBEGM-U point test moves replay children onto the point's device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Gate predicates may only read states. A predicate argument naming V_target,
V_target_<s> or D_target now raises GateReadsValueError at Regime build and
points to exits=/Exit and ArrivalDecision/ArrivalRead. Gate(references=...)
is gone, together with the dissolution-flag replay artifact, its persistence
and the simulation flag channels. The kernel-internal D output stays; tests
observe it through tests/collective_fixtures.recorded_dissolution_flags().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
The per-query programs and the recomputation schedule were compiled and
sized but never dispatched; the chunk loop is the only executed program.
Memory admission now sizes the common chunk from the fori_loop program,
and narrowing halves that chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Simulation now reads the published DC-EGM policy when a regime carries
continuous stochastic-process states whose nodes are fixed at build time
and whose law is not state-conditioned. A subject off a node reads a linear
blend of the two bracketing node rows, using the node-coordinate rule of
the transition weights. Runtime-param and state-conditioned laws keep the
grid argmax, as does any read that leaves its row support.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
Regime(post_choice_shocks=(name, ...)) names Model shock groups drawn after
the choice. Only transitions read them, as next_<name>; any other function
reading one is refused at Model build. Each shock lowers to a fixed node set
feeding the transition-local lottery in the solve and per-subject draws in
simulation. This replaces the transition-only fold inference; fold=True on a
state read only as next_<name> now points to post_choice_shocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
A shock group read by a DCEGM, NBEGM, NEGM or NNBEGM regime is rewritten at
Model build into legacy IID node states in every regime that reads it; the
solve publishes values integrated over the node axis, and archives store the
published values. Groups read only by GridSearch regimes stay on the
current-IID route. Draws use the same addressed stream as the native route,
and BaseInnovations/PhysicalValues overrides apply with the same rules.
Groups an EGM regime cannot express on a fixed node axis (signed weights,
correlation, joint non-product rules, MonteCarlo/QMC, Discrete laws, runtime
or state-conditioned parameters) are refused at Model build. The native
route stays reachable through LCM_NATIVE_CURRENT_IID until it is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K77bhreFhbLuuKA6zCbv8t
…codex/cascade-pr625-20261103

# Conflicts:
#	tests/candidate_certificate/direct_flow.py
#	tests/candidate_certificate/sources.json
…20261103

# Conflicts:
#	tests/candidate_certificate/direct_flow.py
#	tests/candidate_certificate/sources.json
#	tests/ci/ci-workloads.json
…20261103

# Conflicts:
#	tests/candidate_certificate/direct_flow.py
#	tests/candidate_certificate/sources.json
Publish original current shocks separately from the final actor realization, including participation fallback observations. Keep simulation inputs and draws unchanged, retain discrete report codes, and report the stored coordinates for missing values.
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Benchmark comparison (main → HEAD)

Comparing 0fb55673 (main) → 382ef23d (HEAD)

Benchmark Statistic before after Ratio Alert
ACA (reduced) warm solve + simulate (reuses compiled code) 105.722 s 73.609 s 0.70
cold solve + simulate (first run, includes compilation) 808.56 s 1226.77 s 1.52 ❌
peak CPU mem 6.16 GB 9.94 GB 1.61 ❌
Mahler-Yum warm solve + simulate (reuses compiled code) 6.054 s 7.389 s 1.22 ❌
cold solve + simulate (first run, includes compilation) 19.02 s 26.68 s 1.40 ❌
peak CPU mem 1.66 GB 1.76 GB 1.06
peak GPU mem: automatic solve + simulate 1.61 GB 714 MB 0.44
peak GPU mem: load saved solution + simulate 1.89 GB 837 MB 0.44
peak GPU mem: solve + save all persistable artifacts 571 MB 714 MB 1.25 ❌
Precautionary Savings - Solve execution time 84.0 ms 74.7 ms 0.89
first call (including compilation) 1.29 s 1.62 s 1.26 ❌
peak CPU mem 1.44 GB 1.45 GB 1.01
Precautionary Savings - Simulate execution time 901.9 ms 944.9 ms 1.05
peak GPU mem 324 MB 590 MB 1.82 ❌
first call (including compilation) 3.40 s 3.54 s 1.04
peak CPU mem 1.57 GB 1.58 GB 1.00
Precautionary Savings - Solve & Simulate execution time 661.7 ms 713.7 ms 1.08
peak GPU mem 1.51 GB 3.34 GB 2.22 ❌
first call (including compilation) 4.28 s 4.72 s 1.10 ❌
peak CPU mem 1.53 GB 1.54 GB 1.01
Precautionary Savings - Solve & Simulate (irreg) execution time 802.4 ms 842.4 ms 1.05
peak GPU mem 2.21 GB 3.34 GB 1.51 ❌
first call (including compilation) 4.45 s 4.96 s 1.12 ❌
peak CPU mem 1.53 GB 1.54 GB 1.01
Iskhakov et al. (2017) - GridSearch Solve execution time 195.2 ms 168.3 ms 0.86
peak GPU mem 120 MB 120 MB 1.00
first call (including compilation) 2.43 s 2.43 s 1.00
peak CPU mem 1.63 GB 1.63 GB 1.00
Iskhakov et al. (2017) - DC-EGM Solve execution time 826.2 ms 759.2 ms 0.92
first call (including compilation) 6.87 s 6.86 s 1.00
peak CPU mem 1.99 GB 1.97 GB 0.99
Iskhakov et al. (2017) - GridSearch Simulate execution time 918.0 ms 935.1 ms 1.02
peak GPU mem 891 MB 891 MB 1.00
first call (including compilation) 7.02 s 6.75 s 0.96
peak CPU mem 1.76 GB 1.77 GB 1.00
Iskhakov et al. (2017) - DC-EGM Simulate execution time 1.281 s 1.279 s 1.00
peak GPU mem 891 MB 891 MB 1.00
first call (including compilation) 9.25 s 9.00 s 0.97
peak CPU mem 2.03 GB 2.05 GB 1.01
Collective Household - Construct execution time 1.547 s 1.532 s 0.99
peak CPU mem 1.43 GB 1.43 GB 1.00
Collective Household - Solve execution time 5.453 s 4.935 s 0.91
first call (including compilation) 55.91 s 37.74 s 0.67
peak CPU mem 4.60 GB 2.56 GB 0.56
Collective Household - Simulate (1000) execution time 32.017 s 32.239 s 1.01
first call (including compilation) 505.24 s 534.46 s 1.06
peak CPU mem 25.19 GB 26.76 GB 1.06
Collective Household - Simulate (100000) execution time nan µs nan µs nan
peak GPU mem nan MB nan MB nan
first call (including compilation) nan s nan s nan
peak CPU mem nan MB nan MB nan
Reference Chain - Solve (1) execution time 39.8 ms 30.3 ms 0.76
first call (including compilation) 1.48 s 1.64 s 1.11 ❌
peak CPU mem 1.16 GB 1.16 GB 1.00
Reference Chain - Solve (8) execution time 253.5 ms 202.3 ms 0.80
first call (including compilation) 5.35 s 5.76 s 1.08
peak CPU mem 1.29 GB 1.29 GB 1.00
SimulationDispatch ('dissolution', 'off') warm simulation time per period and regime (ms) 78.72 ms 75.91 ms 0.96
backend compile requests on second simulation call 0
SimulationDispatch ('dissolution', 'progress') warm simulation time per period and regime (ms) 83.99 ms 77.59 ms 0.92
backend compile requests on second simulation call 0
SimulationDispatch ('multi_regime', 'off') warm simulation time per period and regime (ms) 56.41 ms 52.02 ms 0.92
backend compile requests on second simulation call 0
SimulationDispatch ('multi_regime', 'progress') warm simulation time per period and regime (ms) 50.58 ms 49.82 ms 0.99
backend compile requests on second simulation call 0

Base automatically changed from codex/on-nodes-transition-rules to main November 5, 2026 07:33
Cache each target regime expectation for its own process-row combinations. Preserve the ordered corner sum, nonlinear readers, validity checks and exceptional-value behavior. Add reader-count regressions and refresh the source certificate pins.
LogNormalIIDProcess already publishes exp(z). Add that income once in the
wealth law and resource constraint, and seed level income at one in both
single- and cross-regime simulations and the panel generation recipe.

Pin equivalence with the normal log-income representation. Retain the
0.01% independent Bellman value check with explicit finite-grid backward
induction. Adopt the regenerated process panels and their historical
source provenance from df375f5. Production extrapolation is unchanged.

Use --as-is in the hash-seed subprocess check so it cannot refresh the
editable install and generated version metadata during a test run.
Reuse the existing lowering keys while preserving per-call admission. Import the EGM and policy-query modules before model construction so beartype annotation tracebacks cannot pin compiled executables through the model.

@mj023 mj023 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.

Looks fine overall, ignoring the large slowdown for now. given that we want to make all of this opt-in anyways. I still found some other correctness problems. The first two items are largely trade-offs that come from the new implementation, they were better under the old implementation but are probably never relevant in real models. The rest is mostly cleanup work.

  1. The custom JVP gives wrong weight derivatives when values cancel. Take equal weights on +B, −B and a small b. Measured against an exact Fraction reference, d(mean)/d(w₃) is off by a third in float32 at ±2²⁰ next to 2⁻¹⁰, and in float64 at ±2⁴⁰ next to 2⁻²⁰; main is exact on the same inputs. The residual correction in _scaled_mean_jvp is the cause. For the ±B nodes, vᵢ − m rounds to ±B, so the correction comes out as about (2/9)·b when it should be about 0. Please drop the correction when the centered gaps cancel, or show an input where it beats the plain slope.

  2. The mean flushes to 0 under wide cancellation. With ±2¹⁰⁰⁰ and 2⁻¹⁰⁰ in f64, or ±2¹⁰⁰ and 2⁻¹⁰⁰ in f32, the PR returns 0 where the exact mean (and main) is 2.6e-31. Scaling every term to the largest one before summing underflows the small term. The docstring admits this case, but it is a regression against main.

  3. Whether the Rouwenhorst refusal fires depends on how σ is declared. The test case: income carried from work (σ = 0.3) to retired (σ = 0.2).

    • With σ fixed at build time, the model is now refused.
    • With σ supplied at solve time, it is accepted without comment and gives the edge-row answer: 1.2903 instead of the 1.4438 the extension rule gives.
    • has_same_law_as treats two sigma=None declarations as the same law, so neither the refusal nor the solve-time extension fires.

    Please check the actual nodes once runtime parameters are known, or drop the refusal. The error message also contradicts the between-node blending that the same function implements.

  4. The off_grid docstring is out of date (processes/base.py:160). It still says that under "extrapolate", transition rows extend linearly beyond the outer nodes. Tauchen now reads the law row there, and Rouwenhorst reads the edge row and extends the continuation instead.

  5. Some code is now dead.

    • scaled_weighted_terms and relative_scales (_lcm/zero_safe.py) have no production callers, but test_wide_exponent_spread_lottery.py still tests scaled_weighted_terms.
    • binades_to_fit_product has no callers at all.

    Remove them, or point those tests at the code path that now runs.

  6. Minor:

    • regime_building/zero_safe.py imports three private helpers from certainty_equivalent. Moving the scaled-mean kernel into _lcm/zero_safe.py would fix that.
    • The phase is inferred from continuation_functions is not None (Q_and_F.py:683, :2029); it should be passed explicitly.

Probe the compiler that actually builds the native CPU payload. Exercise
cold module attribution with a fresh model and require warm solves to
reuse their traces.

Compare resolved Rouwenhorst nodes across solve regimes, including when
the process parameters arrive at solve time. Pass the phase explicitly to
the Bellman builders and describe off-grid process reads.

Move shared scaled-lottery arithmetic and remove unused helpers. Document
the remaining cancellation limits. The centered derivative correction
preserves adjacent-value slopes, and the tested wider reductions increase
CPU forward-kernel time.
@hmgaudecker

Copy link
Copy Markdown
Member Author

@mj023 Addressed in 382ef23. All 74 checks passed, including CPU, both GPU precisions, and benchmark-pr.

  1. I kept the JVP correction after testing the alternative. For equal weights on [1, nextafter(1, +inf)], write the spacing as δ. The exact weight derivatives are [-δ/4, +δ/4]. The correction returns these slopes. Subtracting the rounded mean alone returns [0, δ/2]. Your signed-cancellation example also reproduces. The limitation is explicit in the code.
  2. The wide-cancellation example reproduces at both precisions. A wider scale and separate sums for large and small terms repaired both examples, but the two tested lowerings increased CPU forward-kernel time by 15–96% on arrays of shape 8192×7 and 2048×64. An A100 fp64 kernel probe measured changes from −1.5% to +2.9% across three shapes. I kept the default arithmetic and documented the limit. These are kernel measurements, not whole-model estimates.
  3. The solver now compares the resolved Rouwenhorst nodes across regimes after runtime parameters are available. Unequal nodes are refused. Tests cover both the refusal and matching runtime nodes at fp32 and fp64. The error text states the solve requirement.
  4. Updated off_grid to describe Tauchen law-row evaluation and Rouwenhorst continuation extension.
  5. Removed the three unused helpers and the obsolete helper-only tests. The live mean path retains its overflow, rare-node, and zero-weight coverage.
  6. Moved the shared scaled-mean helpers into _lcm/zero_safe.py and passed the phase explicitly through both Bellman builders.

The cache also required two CI test corrections. Warm calls now issue zero trace requests, and compile-time attribution must be checked with a fresh model. Windows build fingerprints now probe the MSVC compiler used by the build.

The latest whole-model benchmark measured ACA warm solve and simulate at 73.609 s versus 105.722 s on main. Cold time remains 1226.77 s versus 808.56 s, and peak host memory is 9.94 GB versus 6.16 GB. These remaining costs are still visible in the benchmark report.

@hmgaudecker
hmgaudecker merged commit 5016fbb into main Nov 8, 2026
74 checks passed
@hmgaudecker
hmgaudecker deleted the codex/514-continuation-overflow branch November 8, 2026 06:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regime-weighted continuation overflows to inf near float max in eager mode

2 participants