diff --git a/hatch_build.py b/hatch_build.py index d9f1f9198..73a7f5885 100644 --- a/hatch_build.py +++ b/hatch_build.py @@ -94,9 +94,12 @@ def _tool_version(executable: str | None) -> str | None: """Return one compiler's version report for the installed-build manifest.""" if executable is None: return None + command = [executable] + if Path(executable).stem.lower() != "cl": + command.append("--version") try: result = subprocess.run( # noqa: S603 - [executable, "--version"], + command, capture_output=True, text=True, check=False, @@ -110,9 +113,17 @@ def _tool_version(executable: str | None) -> str | None: return f"exit={result.returncode}\n{report}" +def _find_cpu_compiler() -> str | None: + """Find the compiler used to build the CPU payload on this platform.""" + override = os.environ.get("CXX") + if sys.platform == "win32": + return override or shutil.which("cl") + return override or shutil.which("c++") or shutil.which("g++") + + def native_build_inputs(*, root: Path) -> dict[str, object]: """Return all inputs that decide whether an installed payload is reusable.""" - compiler = os.environ.get("CXX") or shutil.which("c++") or shutil.which("g++") + compiler = _find_cpu_compiler() nvcc = shutil.which("nvcc") try: from importlib.metadata import version # noqa: PLC0415 @@ -486,9 +497,9 @@ def build_exact_affine( source_dir = root / PACKAGE_DIR output_dir = output_dir or root / ".pylcm-native-build" include_dir = jax_include_dir or _find_jax_include_dir() + compiler = _find_cpu_compiler() if sys.platform == "win32": - compiler = os.environ.get("CXX") or shutil.which("cl") if compiler is not None and not _accepts_msvc_flags(compiler): msg = ( f"CXX is set to {compiler!r}, which does not take MSVC flags. The " @@ -532,7 +543,6 @@ def build_exact_affine( ) ] - compiler = os.environ.get("CXX") or shutil.which("c++") or shutil.which("g++") if compiler is None: msg = ( "No C++ compiler found. pylcm's certified upper envelope needs one to " diff --git a/src/_lcm/certainty_equivalent.py b/src/_lcm/certainty_equivalent.py index e1676a604..9c5e8c15b 100644 --- a/src/_lcm/certainty_equivalent.py +++ b/src/_lcm/certainty_equivalent.py @@ -21,16 +21,13 @@ weighted_power_mean, ) from _lcm.probability import ( - binades_above_smallest_normal, - binades_to_fit_product, is_live, is_negative, is_represented_zero, rescaled_lottery_weights, - scaled_down_by_power_of_two, ) from _lcm.utils.functools import get_union_of_args -from _lcm.zero_safe import zero_safe_weighted_term +from _lcm.zero_safe import scaled_lottery_mean, zero_safe_weighted_term from lcm.exceptions import ( RegimeInitializationError, ScaledLotteryDifferentiationError, @@ -233,12 +230,10 @@ def aggregate_scaled( The expectation, reduced over the last axis. """ - value_terms, weight_terms = _scaled_lottery_terms( + mean, _ = scaled_lottery_mean( values=values, coefficients=coefficients, shifts=shifts ) - return _states_no_derivative( - jnp.sum(value_terms, axis=-1) / jnp.sum(weight_terms, axis=-1) - ) + return _states_no_derivative(mean) @beartype(conf=REGIME_CONF) @@ -413,14 +408,11 @@ def aggregate_scaled( transformed = self.transform( value=safe_values, **_args_for(func=self.transform, params=params) ) - value_terms, weight_terms = _scaled_lottery_terms( + mean, _ = scaled_lottery_mean( values=transformed, coefficients=coefficients, shifts=shifts ) return _states_no_derivative( - self.inverse( - value=jnp.sum(value_terms, axis=-1) / jnp.sum(weight_terms, axis=-1), - **_args_for(func=self.inverse, params=params), - ) + self.inverse(value=mean, **_args_for(func=self.inverse, params=params)) ) @@ -647,106 +639,3 @@ def aggregates_nonlinearly(certainty_equivalent: CertaintyEquivalent | None) -> return certainty_equivalent is not None and not isinstance( certainty_equivalent, LinearExpectation ) - - -def _scaled_lottery_terms( - *, values: FloatND, coefficients: FloatND, shifts: IntND -) -> tuple[FloatND, FloatND]: - """Return a lottery's value terms and weight terms on one shared scale. - - A node's contribution to a mean is `c * 2**-s * v`, and the order those - three are combined in decides whether the node survives. Two orders each - lose it at one end of the range: - - - forming the weight `c * 2**-s` first loses a rare node, because the - weight of a node many binades below the likeliest one is not - representable and becomes zero, taking its value with it — although the - *product* it was heading for may be an ordinary number, which is - precisely the case where the node changes the answer; - - forming `c * v` first loses a node whose coefficient has been normalized - above one and whose value sits near the top of the range, because that - intermediate overflows to infinity before any scale is applied to bring - it back. - - Splitting the scale covers both. The coefficient absorbs as much of the - downward shift as it can while staying normal, the product absorbs the - remainder. Neither an unrepresentable weight nor an overflowing product is - ever materialized, and a rare node earns its place in the mean exactly when - its value is large enough to offset its probability. - - Both returned terms carry the same shift, so the scale cancels in their - ratio and the caller divides them directly. The shift is the smallest the - row carries, per lottery rather than per batch, so the likeliest node's - weight lands at its own magnitude and no unrelated lottery beside it can - move it. A dead node takes no part in that choice: an unreachable node - carrying a large shift would otherwise push every live weight down with it. - - The row's own weight total joins that shift, scaled against the largest - value the row carries, so that the weighted sum cannot reach infinity while - the mean it states is an ordinary number. Two equally likely nodes near the - top of the range are the case: their mean is comfortably representable, but - the numerator alone is not. That correction is the smallest one that fits, - because every binade spent at the top is one the rarest term of the same - sum loses at the bottom. - - A coefficient that is not a probability at all — negative, infinite, or - NaN — is not a dead node and is not silently dropped. It poisons its whole - row, so a malformed lottery is visible in the result rather than reduced to - a plausible number. - - Args: - values: Continuation values of the lottery along the last axis. - coefficients: The weights' significands, over the same axis. - shifts: Each weight's own base-two scale, broadcast against them. - - Returns: - Tuple of the value terms and the weight terms, both over the last axis - and both carrying the row's shared scale. - - """ - coefficients = jnp.asarray(coefficients) - values = jnp.asarray(values) - shifts = jnp.broadcast_to(jnp.asarray(shifts), jnp.shape(coefficients)) - - live = is_live(coefficients) & jnp.isfinite(coefficients) - invalid = is_negative(coefficients) | ( - ~jnp.isfinite(coefficients) & ~is_represented_zero(coefficients) - ) - unusable = jnp.max(shifts, axis=-1, keepdims=True) - common = jnp.min(jnp.where(live, shifts, unusable), axis=-1, keepdims=True) - scale = (common - shifts).astype(jnp.int32) - - on_common_scale = jnp.where( - live, - scaled_down_by_power_of_two(values=coefficients, shift=scale), - jnp.zeros_like(coefficients), - ) - total = jnp.sum(on_common_scale, axis=-1, keepdims=True) - largest = jnp.max( - jnp.where(live, jnp.abs(values), jnp.zeros_like(values)), - axis=-1, - keepdims=True, - ) - full = scale - binades_to_fit_product(left=total, right=largest) - - room = binades_above_smallest_normal(coefficients) - on_weight = jnp.maximum(full, -room) - scaled_coefficients = scaled_down_by_power_of_two( - values=coefficients, shift=on_weight - ) - products = zero_safe_weighted_term( - weight=scaled_coefficients, - value=values, - subnormal_is_accounted_for=False, - ) - value_terms = scaled_down_by_power_of_two(values=products, shift=full - on_weight) - weight_terms = scaled_down_by_power_of_two(values=coefficients, shift=full) - - value_terms = jnp.where(live, value_terms, jnp.zeros_like(value_terms)) - weight_terms = jnp.where(live, weight_terms, jnp.zeros_like(weight_terms)) - invalid_row = jnp.any(invalid, axis=-1, keepdims=True) - nan = jnp.asarray(jnp.nan, dtype=coefficients.dtype) - return ( - jnp.where(invalid_row, nan, value_terms), - jnp.where(invalid_row, nan, weight_terms), - ) diff --git a/src/_lcm/probability.py b/src/_lcm/probability.py index 522af7e3b..24c7f8aef 100644 --- a/src/_lcm/probability.py +++ b/src/_lcm/probability.py @@ -1025,39 +1025,6 @@ def binades_above_smallest_normal(values: FloatND) -> _BitsND: ) -def binades_to_fit_product(*, left: FloatND, right: FloatND) -> _BitsND: - """Halvings of `left` that bring `left * right` inside the format's range. - - A caller reducing a weighted mean uses this to scale a row's weight total - against its largest value, so the weighted sum cannot reach infinity while - the mean it states is an ordinary number. The shift is a power of two - applied to both sides of the ratio, so it is exact and leaves the mean - unchanged. - - It is the *smallest* such shift, which matters at the other end of the - range: every binade spent here is one the smallest term of the same sum - loses, and one binade too many turns a representable contribution into a - subnormal a backend may flush. A product that already fits needs none. - - Args: - left: The factor to be scaled down — the weight total. - right: The factor it will meet — the largest value in the row. - - Returns: - The non-negative number of halvings of `left` that make the product - representable. - - """ - arr = jnp.asarray(left) - largest_exponent = jnp.finfo(arr.dtype).maxexp - 2 - excess = ( - _unbiased_exponent(arr) - + _unbiased_exponent(jnp.asarray(right)) - - largest_exponent - ) - return jnp.maximum(excess, 0).astype(jnp.int32) - - def _unbiased_exponent(values: FloatND) -> _BitsND: """Return each entry's base-two exponent, subnormals included.""" arr = jnp.asarray(values) diff --git a/src/_lcm/processes/ar1.py b/src/_lcm/processes/ar1.py index 6e33de0ac..5f1a574b6 100644 --- a/src/_lcm/processes/ar1.py +++ b/src/_lcm/processes/ar1.py @@ -239,6 +239,23 @@ def compute_transition_probs(self, **kwargs: ScalarFloat | ScalarInt) -> FloatND [first_col, jnp.diff(cdf_vals, axis=1), last_col], axis=1 ) + def transition_row_at( + self, *, from_value: ScalarFloat, **kwargs: ScalarFloat | ScalarInt + ) -> Float1D: + """Return the law's transition row from any current value, on the nodes. + + The row bins the conditional law at the nodes' midpoints, exactly as + `compute_transition_probs` does at each node, so it is a probability + distribution wherever the current value lies. + """ + return tauchen_row( + nodes=self.compute_gridpoints(**kwargs), + rho=kwargs["rho"], + sigma=kwargs["sigma"], + from_value=from_value, + mu=kwargs["mu"], + ) + def draw_shock( self, *, @@ -323,6 +340,14 @@ def compute_transition_probs(self, **kwargs: ScalarFloat | ScalarInt) -> FloatND """Evaluate the selected transition row at each supplied source node.""" return jax.vmap(partial(self.compute_transition_row, **kwargs))(self.to_jax()) + def transition_row_at( + self, *, from_value: ScalarFloat, **kwargs: ScalarFloat | ScalarInt + ) -> Float1D: + """Return the selected rule's row from any current value.""" + return self.compute_transition_row( + from_value, rho=kwargs["rho"], sigma=kwargs["sigma"], mu=kwargs["mu"] + ) + # keyword-only-exempt: library-callback=jax.vmap def compute_transition_row( self, @@ -1054,6 +1079,23 @@ def compute_transition_probs(self, **kwargs: ScalarFloat | ScalarInt) -> FloatND P = P.at[:, 0].set(upper[:, 0]) return P.at[:, -1].set(1 - lower[:, -1]) + def transition_row_at( + self, *, from_value: ScalarFloat, **kwargs: ScalarFloat | ScalarInt + ) -> Float1D: + """Return the law's transition row from any current value, on the nodes. + + Each node's bin reaches half a step to either side, the first and last + bins open, as in `compute_transition_probs`. + """ + x = self.compute_gridpoints(**kwargs) + mixture = {name: kwargs[name] for name in ("p1", "mu1", "sigma1", "mu2")} + half_step = 0.5 * (x[-1] - x[0]) / (self.n_points - 1) + z = x - kwargs["mu"] - kwargs["rho"] * from_value + upper = _mixture_cdf(x=z + half_step, sigma2=kwargs["sigma2"], **mixture) + lower = _mixture_cdf(x=z - half_step, sigma2=kwargs["sigma2"], **mixture) + row = (upper - lower).at[0].set(upper[0]) + return row.at[-1].set(1 - lower[-1]) + def draw_shock( self, *, diff --git a/src/_lcm/processes/base.py b/src/_lcm/processes/base.py index 6a08c12c8..f13808c67 100644 --- a/src/_lcm/processes/base.py +++ b/src/_lcm/processes/base.py @@ -157,16 +157,18 @@ def __new__( ) """How a value beyond the outer nodes is read, as on a continuous grid. - - `"extrapolate"`: transition rows, continuations and policies extend - linearly along the edge segment. + - `"extrapolate"`: Tauchen evaluates its transition law at the off-grid + value. Rouwenhorst uses the edge node's transition row and extends the + continuation along the edge segment. Interpolated policies also extend + along the edge segment. - `"clip_lookup"`: those reads use the nearest edge node; the state keeps its value. - `"clip_state"`: a simulated value is additionally clipped to the outer nodes. - `"raise"`: a simulated value beyond the outer nodes is refused. - A `simulated_draws="nodes"` draw samples the nearest edge node's row under - every rule, since an extrapolated row can carry negative weights. + A `simulated_draws="nodes"` draw beyond the nodes samples the nearest edge + node's transition row when the off-grid rule permits the state. """ state_conditioned: StateConditioned | None = field(init=False, default=None) diff --git a/src/_lcm/regime_building/Q_and_F.py b/src/_lcm/regime_building/Q_and_F.py index 91728e729..d99c3ac04 100644 --- a/src/_lcm/regime_building/Q_and_F.py +++ b/src/_lcm/regime_building/Q_and_F.py @@ -11,12 +11,13 @@ """ import dataclasses +import functools import inspect import operator from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field from types import FunctionType, MappingProxyType -from typing import NamedTuple, cast, no_type_check +from typing import Literal, NamedTuple, cast, no_type_check import jax import jax.numpy as jnp @@ -40,6 +41,7 @@ regime_mass_is_a_distribution, ) from _lcm.processes import _ContinuousStochasticProcess +from _lcm.reachability import PhaseName from _lcm.regime_building.next_state import ( get_next_state_function_for_solution, get_next_stochastic_weights_function, @@ -103,6 +105,7 @@ FunctionName, Int1D, IntND, + LoopIndex, ReferenceName, UserFunction, ) @@ -118,6 +121,8 @@ # the feasibility mask (a Python `bool` for a regime without constraints). type UtilitiesAndF = tuple[FloatND | IntND | BoolND | int | float | bool, ...] +_PROCESS_EDGE_CORNER = "_lcm_process_edge__corner" + class EvaluatedUtilitiesAndF(NamedTuple): """Actual utility/feasibility values with separate declaration-integrity flags.""" @@ -553,6 +558,7 @@ def _normalized_regime_mixture( def get_Q_and_F( *, + phase_name: PhaseName = "solution", flat_param_names: frozenset[QualifiedName], functions: EconFunctionsMapping, constraints: ConstraintFunctionsMapping, @@ -675,6 +681,7 @@ def get_Q_and_F( co_map_state_names=co_map_state_names, gated_continuations=gated_continuations, count_raise_landings=count_raise_landings, + extend_process_edges=phase_name, ) _build_W_kwargs = _get_build_W_kwargs( functions=functions, koopmans_aggregator=koopmans_aggregator @@ -1026,6 +1033,7 @@ def get_compute_intermediates( certainty_equivalent=certainty_equivalent, co_map_state_names=co_map_state_names, gated_continuations=gated_continuations, + extend_process_edges="solution", ) _build_W_kwargs = _get_build_W_kwargs( functions=functions, koopmans_aggregator=koopmans_aggregator @@ -1854,6 +1862,7 @@ def _lookup_reference_params( def get_Q_and_F_collective( *, + phase_name: PhaseName, flat_param_names: frozenset[QualifiedName], functions: EconFunctionsMapping, constraints: ConstraintFunctionsMapping, @@ -2017,6 +2026,7 @@ def get_Q_and_F_collective( n_stakeholders=n_stakeholders, gated_continuations=gated_continuations, count_raise_landings=count_raise_landings, + extend_process_edges=phase_name, ) _build_W_kwargs = _get_build_W_kwargs( @@ -2932,6 +2942,7 @@ def _get_compute_CE( ), flat_param_names: frozenset[QualifiedName] | None = None, count_raise_landings: bool = False, + extend_process_edges: Literal["solution", "simulation"] | None = None, ) -> tuple[ Callable[..., ContinuationAggregate], tuple[Callable[..., ArrayTree], ...], @@ -2993,6 +3004,12 @@ def _get_compute_CE( `off_grid="raise"` grid the continuation reads. A landing counts where its target regime and its lottery node are live and, through a gated edge, where the gate routes to the grid it is read on. + extend_process_edges: The phase whose process values beyond the outer + nodes extend the continuation linearly along the edge segment, as the + blend of the continuations under the edge node's row and its + neighbour's (`EdgeRows`), or `None` for no extension. A simulation + extends every process carrying `EdgeRows`; a solve only those whose + current values can leave the target's nodes. Returns: Tuple of the closure returning `(CE, active_regime_probs)` — followed by @@ -3002,6 +3019,26 @@ def _get_compute_CE( weights formed inside the node axes. """ + if extend_process_edges is not None: + return _get_compute_CE_with_process_edges( + functions=functions, + period_targets=period_targets, + phase=extend_process_edges, + build=functools.partial( + _get_compute_CE, + scalar_targets=scalar_targets, + transitions=transitions, + transition_plans=transition_plans, + compute_regime_transition_probs=compute_regime_transition_probs, + regime_to_v_interpolation_info=regime_to_v_interpolation_info, + certainty_equivalent=certainty_equivalent, + co_map_state_names=co_map_state_names, + n_stakeholders=n_stakeholders, + gated_continuations=gated_continuations, + flat_param_names=flat_param_names, + count_raise_landings=count_raise_landings, + ), + ) # The plain expectation reduces each target on its own; every other # certainty equivalent needs the whole joint lottery in one piece, because # its transform has to be applied before any expectation is taken. @@ -3126,6 +3163,424 @@ def _get_compute_CE( return compute_CE, deps, continuation_arg_names +@dataclass(frozen=True, kw_only=True, eq=False) +class EdgeRows: + """The reads that extend a process's continuation beyond its outer nodes. + + The process's weights read the nearest edge node's row there, a genuine + lottery. The extension along the edge segment is the blend + `(1 + distance) * CE_edge - distance * CE_neighbour` of the continuations under + that row and under its inward neighbour's, each a genuine lottery too. It is + linear in the continuation: under a nonlinear certainty equivalent it + extrapolates the certainty equivalents of the two node rows. + """ + + neighbour: Callable[..., FloatND] + """The inward neighbour's row beyond the nodes; the weights' row elsewhere.""" + distance: Callable[..., FloatND] + """Edge segments the value lies beyond the outer nodes; zero between them.""" + in_solve: bool + """Whether a solve can read the process beyond the target's nodes.""" + + +@dataclass(frozen=True, kw_only=True, eq=False) +class _ProcessEdgeExtension: + """Extend a continuation linearly beyond its processes' outer nodes.""" + + distances: tuple[Callable[..., FloatND], ...] + """One `EdgeRows.distance` per extended process weight.""" + corner: _ComputeCE + """One continuation program selecting each process row by a corner index.""" + + def read_corner( + self, + *, + index: LoopIndex, + next_regime_to_V_arr: MappingProxyType[RegimeName, FloatND], + zero: FloatND, + states_actions_params: QAndFKwargs, + ) -> ContinuationAggregate: + """Read one joint corner without changing its lottery or CE aggregation.""" + return self.corner( + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=MappingProxyType( + {**states_actions_params, _PROCESS_EDGE_CORNER: index} + ), + ) + + @no_type_check + def extend( + self, + *, + edge: _ComputeCE, + next_regime_to_V_arr: MappingProxyType[RegimeName, FloatND], + zero: FloatND, + states_actions_params: QAndFKwargs, + ) -> ContinuationAggregate: + """Return `edge`'s aggregate with `CE` extended along the edge segments. + + Each corner's expectation is weighted by the product over processes of + `1 + distance` (edge row) or `-distance` (neighbour row). Between the + nodes every distance is zero and `edge`'s `CE` is returned untouched. + """ + aggregate, valid = _continuation_evaluation( + edge( + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=states_actions_params, + ) + ) + + def read_corner(*, index: LoopIndex) -> FloatND: + corner, _ = _continuation_evaluation( + self.read_corner( + index=index, + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=states_actions_params, + ) + ) + return corner[0] + + return self._extend_aggregate( + aggregate=aggregate, + valid=valid, + read_corner=read_corner, + states_actions_params=states_actions_params, + ) + + @no_type_check + def _extend_aggregate( + self, + *, + aggregate: _PlainContinuationAggregate, + valid: BoolND | None, + read_corner: Callable[..., FloatND], + states_actions_params: QAndFKwargs, + ) -> ContinuationAggregate: + """Fold corner values in their original coefficient and addition order.""" + distances = [ + distance( + **{ + name: states_actions_params[name] + for name in inspect.signature(distance).parameters + } + ) + for distance in self.distances + ] + initial = zero_safe_weighted_term( + weight=functools.reduce( + operator.mul, (1.0 + distance for distance in distances) + ), + value=aggregate[0], + subnormal_is_accounted_for=True, + ) + + # keyword-only-exempt: library-callback=jax.lax.fori_loop + def add_corner(index: LoopIndex, total: FloatND) -> FloatND: + corner = read_corner(index=index) + weight = functools.reduce( + operator.mul, + ( + jnp.where( + ((index >> (len(distances) - axis - 1)) & 1) != 0, + -distance, + 1.0 + distance, + ) + for axis, distance in enumerate(distances) + ), + ) + return total + zero_safe_weighted_term( + weight=weight, value=corner, subnormal_is_accounted_for=True + ) + + # A loop retains Cartesian corner order without copying the CE graph. + extended = jax.lax.fori_loop(1, 1 << len(distances), add_corner, initial) + on_nodes = functools.reduce( + operator.and_, (distance == 0 for distance in distances) + ) + aggregate = (jnp.where(on_nodes, aggregate[0], extended), *aggregate[1:]) + if valid is None: + return aggregate + return CheckedContinuationEvaluation(aggregate=aggregate, valid=valid) + + +@dataclass(frozen=True, kw_only=True, eq=False) +class _LinearProcessEdgeExtension(_ProcessEdgeExtension): + """Reuse each target's local expectations in the ordered corner mixture.""" + + target_shifts: tuple[tuple[RegimeName, tuple[int, ...]], ...] + """Global corner-bit positions belonging to each target.""" + + @no_type_check + def extend( + self, + *, + edge: _ComputeCE, + next_regime_to_V_arr: MappingProxyType[RegimeName, FloatND], + zero: FloatND, + states_actions_params: QAndFKwargs, + ) -> ContinuationAggregate: + """Cache local target reads, preserving the original global scalar fold.""" + base = edge.evaluate( + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=states_actions_params, + ) + aggregate, valid = _continuation_evaluation(base.aggregate) + base_terms = { + name: (probability, value) + for name, probability, value in base.mixture_terms + } + cached: dict[RegimeName, FloatND] = {} + for target_name, shifts in self.target_shifts: + if not shifts: + continue + value = base_terms[target_name][1] + values = jnp.broadcast_to(value, (1 << len(shifts), *value.shape)) + + # keyword-only-exempt: library-callback=jax.lax.fori_loop + def cache_corner( + index: LoopIndex, + values: FloatND, + *, + shifts: tuple[int, ...] = shifts, + target_name: RegimeName = target_name, + ) -> FloatND: + global_index = jnp.asarray(0, dtype=jnp.int32) + for axis, shift in enumerate(shifts): + global_index = global_index | ( + ((index >> (len(shifts) - axis - 1)) & 1) << shift + ) + params = MappingProxyType( + {**states_actions_params, _PROCESS_EDGE_CORNER: global_index} + ) + target = self.corner.continuations[target_name] + marginals = target.lottery_weights(**params) + weights, scales = target.joint_lottery_weights( + **{ + name: weight + for name, weight in marginals.items() + if name not in target.integrated_weight_names + } + ) + read = target.read( + next_values=next_regime_to_V_arr[target_name], + states_actions_params=params, + marginals=marginals, + weights=weights, + shifts=scales, + probability=base_terms[target_name][0], + co_map_next_names=edge.co_map_next_names, + n_stakeholders=edge.n_stakeholders, + reduces_per_target=True, + ) + return jax.lax.dynamic_update_index_in_dim( + values, read.values, index, axis=0 + ) + + cached[target_name] = jax.lax.fori_loop( + 1, 1 << len(shifts), cache_corner, values + ) + shifts_by_target = dict(self.target_shifts) + + def read_corner(*, index: LoopIndex) -> FloatND: + terms: list[tuple[RegimeName, FloatND, FloatND]] = [] + for name, probability, value in base.mixture_terms: + selected_value = value + if name in cached: + local_index = jnp.asarray(0, dtype=jnp.int32) + for shift in shifts_by_target[name]: + local_index = (local_index << 1) | ((index >> shift) & 1) + selected_value = jax.lax.dynamic_index_in_dim( + cached[name], local_index, axis=0, keepdims=False + ) + terms.append((name, probability, selected_value)) + mixture = _sum_regime_mixture( + mixture_terms=terms, + like=_value_shaped_zero(zero=zero, n_stakeholders=edge.n_stakeholders), + ) + return _normalized_regime_mixture( + mixture=mixture, + probability_mass=base.probability_mass, + has_negative_probability=base.has_negative_probability, + ) + + return self._extend_aggregate( + aggregate=aggregate, + valid=valid, + read_corner=read_corner, + states_actions_params=states_actions_params, + ) + + +def _can_reuse_linear_process_expectations( + *, + functions: EconFunctionsMapping, + edges: Mapping[FunctionName, EdgeRows], + compute: _ComputeCE, +) -> bool: + """Admit only built-in linear readers with no selected-row dependencies.""" + if ( + not compute.reduces_per_target + or compute.has_participation_queries + or compute.gated_scalar_readers + ): + return False + if any(target.gated_read for target in compute.continuations.values()): + return False + local_reads = sum( + 1 << sum(name.startswith(f"weight_{target}__") for name in edges) + for target in compute.period_targets + ) + if local_reads >= (1 << len(edges)) * len(compute.period_targets): + return False + producers = [ + *functions.values(), + *(row.neighbour for row in edges.values()), + *(row.distance for row in edges.values()), + ] + try: + return not bool(get_union_of_args(producers) & set(edges)) + except TypeError, ValueError: + return False + + +def _get_process_corner_row( + *, + edge: Callable[..., FloatND], + neighbour: Callable[..., FloatND], + shift: int, +) -> Callable[..., FloatND]: + """Select an edge or neighbour row using one bit of the joint corner index.""" + edge_annotations = { + name: annotation + for name, annotation in get_annotations(edge).items() + if name != "return" + } + neighbour_annotations = { + name: annotation + for name, annotation in get_annotations(neighbour).items() + if name != "return" + } + + def selected(**kwargs: PytreeValue) -> FloatND: + index = cast("LoopIndex", kwargs[_PROCESS_EDGE_CORNER]) + return jnp.where( + ((index >> shift) & 1) != 0, + neighbour(**{name: kwargs[name] for name in neighbour_annotations}), + edge(**{name: kwargs[name] for name in edge_annotations}), + ) + + return with_signature( + selected, + args=edge_annotations + | neighbour_annotations + | {_PROCESS_EDGE_CORNER: "LoopIndex"}, + return_annotation=FloatND, + enforce=False, + ) + + +def _get_compute_CE_with_process_edges( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[ + ..., + tuple[ + Callable[..., ContinuationAggregate], + tuple[Callable[..., ArrayTree], ...], + frozenset[str], + ], + ], +) -> tuple[ + Callable[..., ContinuationAggregate], + tuple[Callable[..., ArrayTree], ...], + frozenset[str], +]: + """Build `_get_compute_CE`'s closure, extended beyond its processes' nodes. + + `build` is `_get_compute_CE` with every argument but these two bound. Every + process weight of a reachable target that carries `EdgeRows` is extended in + `phase`, a solve only where `EdgeRows.in_solve`; with none, the closure is the + plain one. + """ + prefixes = tuple(f"weight_{target}__" for target in period_targets) + edges = { + name: rows + for name, func in functions.items() + if name.startswith(prefixes) + and isinstance(rows := getattr(func, "edge_rows", None), EdgeRows) + and (phase == "simulation" or rows.in_solve) + } + compute_CE, deps, arg_names = build( + functions=functions, period_targets=period_targets + ) + if not edges: + return compute_CE, deps, arg_names + corner = build( + functions=MappingProxyType( + dict(functions) + | { + name: _get_process_corner_row( + edge=functions[name], + neighbour=rows.neighbour, + shift=len(edges) - axis - 1, + ) + for axis, (name, rows) in enumerate(edges.items()) + } + ), + period_targets=period_targets, + )[0] + extension = _ProcessEdgeExtension( + distances=tuple(rows.distance for rows in edges.values()), + corner=cast("_ComputeCE", corner), + ) + if isinstance(compute_CE, _ComputeCE) and _can_reuse_linear_process_expectations( + functions=functions, edges=edges, compute=compute_CE + ): + extension = _LinearProcessEdgeExtension( + distances=extension.distances, + corner=extension.corner, + target_shifts=tuple( + ( + target, + tuple( + len(edges) - axis - 1 + for axis, name in enumerate(edges) + if name.startswith(f"weight_{target}__") + ), + ) + for target in period_targets + ), + ) + return ( + dataclasses.replace(cast("_ComputeCE", compute_CE), edge_extension=extension), + deps, + arg_names, + ) + + +class _TargetValue(NamedTuple): + """One target's node value with its landing counts and integrity.""" + + values: FloatND + landing_counts: tuple[IntND, ...] + valid: BoolND + + +class _ContinuationValues(NamedTuple): + """An aggregate and the original linear-mixture inputs that produced it.""" + + aggregate: ContinuationAggregate + mixture_terms: tuple[tuple[RegimeName, FloatND, FloatND], ...] + probability_mass: FloatND + has_negative_probability: BoolND + + @dataclass(frozen=True, kw_only=True, eq=False) class _ComputeCE: """Aggregate the continuation lottery into `CE` at one state-action point.""" @@ -3174,6 +3629,10 @@ class _ComputeCE: default_factory=lambda: MappingProxyType({}), metadata={"fingerprint_omit_if_default": True}, ) + edge_extension: _ProcessEdgeExtension | None = field( + default=None, metadata={"fingerprint_omit_if_default": True} + ) + """Continuations under neighbour rows that extend this one beyond the nodes.""" @property def has_participation_queries(self) -> bool: @@ -3203,7 +3662,7 @@ def landing_checks(self) -> tuple[LandingCheck, ...]: ) @no_type_check - def __call__( # noqa: C901 - preserve original dense arithmetic beside the projected read + def __call__( self, *, next_regime_to_V_arr: MappingProxyType[RegimeName, FloatND], @@ -3232,6 +3691,28 @@ def __call__( # noqa: C901 - preserve original dense arithmetic beside the proj of `landing_checks` when there are any. """ + if self.edge_extension is not None: + return self.edge_extension.extend( + edge=dataclasses.replace(self, edge_extension=None), + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=states_actions_params, + ) + return self.evaluate( + next_regime_to_V_arr=next_regime_to_V_arr, + zero=zero, + states_actions_params=states_actions_params, + ).aggregate + + @no_type_check + def evaluate( + self, + *, + next_regime_to_V_arr: MappingProxyType[RegimeName, FloatND], + zero: FloatND, + states_actions_params: QAndFKwargs, + ) -> _ContinuationValues: + """Evaluate the aggregate and retain its unmultiplied linear terms.""" regime_transition_probs: MappingProxyType[RegimeName, FloatND] = ( self.compute_regime_transition_probs(**states_actions_params) ) @@ -3318,98 +3799,23 @@ def __call__( # noqa: C901 - preserve original dense arithmetic beside the proj ) for target_regime_name in self.period_targets: continuation = self.continuations[target_regime_name] - next_states = continuation.next_states(**states_actions_params) joint_next_stochastic_states_weights = target_node_weights[ target_regime_name ] - - # As we productmap'd the value function over the stochastic variables, the - # resulting next value function gets a new dimension for each stochastic - # variable. - extra_kw = { - k: states_actions_params[k] for k in continuation.extra_param_names - } - # A co-mapped state's axis is sliced off the value array, so the - # interpolation places no coordinate on it. A gated edge's projected - # references are read at the landing instead, and a projection may map - # such a state onto the referenced regime's grid — it needs the state's - # value, not an index — so a coordinate the continuation still names is - # passed rather than dropped with the axis. - # Restore the full original slot sequence before any interpolation - # arithmetic. Repeating restricted integer coordinates preserves - # each node's local state/law meaning without reading another fixed - # group. Copying floating-point results after interpolation can - # change its fusion/vectorization relative to the original model. - if continuation.original_node_axes: - next_states = dict(next_states) - for axis, indices in continuation.original_node_axes: - name = continuation.lottery_axis_names[axis] - nodes = next_states[name] - next_states[name] = jax.lax.concatenate( - tuple( - jax.lax.slice_in_dim(nodes, index, index + 1, axis=0) - for index in indices - ), - dimension=0, - ) - next_values = next_regime_to_V_arr[target_regime_name] - fixed_slice_names = frozenset( - name for _, name in continuation.fixed_value_axes - ) - # Fixed components select one value surface, not one value per - # lottery node. Slice them before mapping the nodes so the reader - # sees the same rest-axis lookup as the original categorical grid. - # Axes already removed by the caller's device co-map are absent. - for axis, name in reversed(continuation.fixed_value_axes): - next_values = read_at_codes( - array=next_values, - positions=(*(slice(None),) * axis, next_states[name]), - ) - interpolator_coordinates = { - name: val - for name, val in next_states.items() - if name not in self.co_map_next_names | fixed_slice_names - or name in continuation.co_mapped_landing_names - } - if continuation.next_V is None: - raise TypeError("Ordinary continuation lost its dense value reader.") - next_V_at_stochastic_states_arr = continuation.next_V( - **interpolator_coordinates, - next_V_arr=next_values, - **extra_kw, - **{ - name: target_marginals[target_regime_name][name] - for name in continuation.integrated_weight_names - }, - ) - - if continuation.landing_checks: - next_V_at_stochastic_states_arr, node_counts = ( - next_V_at_stochastic_states_arr - ) - - landing_counts.append( - _live_landing_counts( - node_counts=node_counts.reshape((-1, node_counts.shape[-1])) - if continuation.participation_query - else node_counts, - target_probability=active_regime_probs[target_regime_name], - node_weights=(joint_next_stochastic_states_weights.reshape(-1),) - if continuation.participation_query - else continuation.node_weights_at( - marginals=target_marginals[target_regime_name], - next_states=next_states, - ), - ) - ) - - next_V_at_stochastic_states_arr, valid = _participation_value_and_integrity( - continuation=continuation, - result=next_V_at_stochastic_states_arr, - probability=active_regime_probs[target_regime_name], + read = continuation.read( + next_values=next_regime_to_V_arr[target_regime_name], + states_actions_params=states_actions_params, + marginals=target_marginals[target_regime_name], weights=joint_next_stochastic_states_weights, + shifts=target_node_shifts[target_regime_name], + probability=active_regime_probs[target_regime_name], + co_map_next_names=self.co_map_next_names, + n_stakeholders=self.n_stakeholders, + reduces_per_target=self.reduces_per_target, ) - participation_valid &= valid + landing_counts.extend(read.landing_counts) + participation_valid &= read.valid + next_V_at_stochastic_states_arr = read.values # A node the target's own lottery gives zero probability is never # realized, so whatever a law names there -- a value off the target's # support, and so a NaN out of the interpolator -- is not part of the @@ -3432,29 +3838,7 @@ def __call__( # noqa: C901 - preserve original dense arithmetic beside the proj ) if self.reduces_per_target: - # A pure lookup has no floating-point interpolation arithmetic. - # Restore its original slots here with static slices rather than - # an indexed gather that can scalarize the ordinary reduction. - for axis, indices in continuation.original_value_axes: - next_V_at_stochastic_states_arr = jax.lax.concatenate( - tuple( - jax.lax.slice_in_dim( - next_V_at_stochastic_states_arr, - index, - index + 1, - axis=axis, - ) - for index in indices - ), - dimension=axis, - ) - next_V_expected_arr = _expected_continuation_over_nodes( - values=next_V_at_stochastic_states_arr, - weights=joint_next_stochastic_states_weights, - shifts=target_node_shifts[target_regime_name], - has_lottery_axes=continuation.has_lottery_axes, - n_stakeholders=self.n_stakeholders, - ) + next_V_expected_arr = read.values # Collect the UNMULTIPLIED `(prob, expected V)`; the mixture is # reduced ONCE by `_sum_regime_mixture`: form each target's # zero-safe contribution on its native cell shape, put the @@ -3546,9 +3930,14 @@ def __call__( # noqa: C901 - preserve original dense arithmetic beside the proj jnp.nan, ) - return self._checked_result( - aggregate=(CE, active_regime_probs, *_concatenated(landing_counts)), - valid=participation_valid, + return _ContinuationValues( + aggregate=self._checked_result( + aggregate=(CE, active_regime_probs, *_concatenated(landing_counts)), + valid=participation_valid, + ), + mixture_terms=tuple(mixture_terms), + probability_mass=probability_mass, + has_negative_probability=has_negative_probability, ) def _checked_result( @@ -3732,6 +4121,137 @@ class _TargetContinuation: ) """The mapped reader returns value plus mandatory participation integrity.""" + gated_read: bool = field( + default=False, metadata={"fingerprint_omit_if_default": True} + ) + """The value reader projects a gated continuation's channels.""" + + @no_type_check + def read( + self, + *, + next_values: FloatND, + states_actions_params: QAndFKwargs, + marginals: Mapping[str, FloatND | IntND], + weights: FloatND, + shifts: IntND, + probability: FloatND, + co_map_next_names: frozenset[str], + n_stakeholders: int | None, + reduces_per_target: bool, + ) -> _TargetValue: + """Read this target's nodes, counts and integrity, reducing a linear mean.""" + landing_counts: list[IntND] = [] + next_states = self.next_states(**states_actions_params) + + # As we productmap'd the value function over the stochastic variables, the + # resulting next value function gets a new dimension for each stochastic + # variable. + extra_kw = {k: states_actions_params[k] for k in self.extra_param_names} + # A co-mapped state's axis is sliced off the value array, so the + # interpolation places no coordinate on it. A gated edge's projected + # references are read at the landing instead, and a projection may map + # such a state onto the referenced regime's grid — it needs the state's + # value, not an index — so a coordinate the continuation still names is + # passed rather than dropped with the axis. + # Restore the full original slot sequence before any interpolation + # arithmetic. Repeating restricted integer coordinates preserves + # each node's local state/law meaning without reading another fixed + # group. Copying floating-point results after interpolation can + # change its fusion/vectorization relative to the original model. + if self.original_node_axes: + next_states = dict(next_states) + for axis, indices in self.original_node_axes: + name = self.lottery_axis_names[axis] + nodes = next_states[name] + next_states[name] = jax.lax.concatenate( + tuple( + jax.lax.slice_in_dim(nodes, index, index + 1, axis=0) + for index in indices + ), + dimension=0, + ) + fixed_slice_names = frozenset(name for _, name in self.fixed_value_axes) + # Fixed components select one value surface, not one value per + # lottery node. Slice them before mapping the nodes so the reader + # sees the same rest-axis lookup as the original categorical grid. + # Axes already removed by the caller's device co-map are absent. + for axis, name in reversed(self.fixed_value_axes): + next_values = read_at_codes( + array=next_values, + positions=(*(slice(None),) * axis, next_states[name]), + ) + interpolator_coordinates = { + name: val + for name, val in next_states.items() + if name not in co_map_next_names | fixed_slice_names + or name in self.co_mapped_landing_names + } + if self.next_V is None: + raise TypeError("Ordinary continuation lost its dense value reader.") + next_V_at_stochastic_states_arr = self.next_V( + **interpolator_coordinates, + next_V_arr=next_values, + **extra_kw, + **{name: marginals[name] for name in self.integrated_weight_names}, + ) + + if self.landing_checks: + next_V_at_stochastic_states_arr, node_counts = ( + next_V_at_stochastic_states_arr + ) + + landing_counts.append( + _live_landing_counts( + node_counts=node_counts.reshape((-1, node_counts.shape[-1])) + if self.participation_query + else node_counts, + target_probability=probability, + node_weights=(weights.reshape(-1),) + if self.participation_query + else self.node_weights_at( + marginals=marginals, + next_states=next_states, + ), + ) + ) + + next_V_at_stochastic_states_arr, valid = _participation_value_and_integrity( + continuation=self, + result=next_V_at_stochastic_states_arr, + probability=probability, + weights=weights, + ) + if reduces_per_target: + # A pure lookup has no floating-point interpolation arithmetic. + # Restore its original slots here with static slices rather than + # an indexed gather that can scalarize the ordinary reduction. + for axis, indices in self.original_value_axes: + next_V_at_stochastic_states_arr = jax.lax.concatenate( + tuple( + jax.lax.slice_in_dim( + next_V_at_stochastic_states_arr, + index, + index + 1, + axis=axis, + ) + for index in indices + ), + dimension=axis, + ) + next_V_at_stochastic_states_arr = _expected_continuation_over_nodes( + values=next_V_at_stochastic_states_arr, + weights=weights, + shifts=shifts, + has_lottery_axes=self.has_lottery_axes, + n_stakeholders=n_stakeholders, + ) + return _TargetValue( + values=next_V_at_stochastic_states_arr, + landing_counts=tuple(landing_counts), + valid=valid, + ) + def node_weights_at( self, *, @@ -4461,6 +4981,7 @@ def _build_target_continuation( landing_checks=landing_counting.checks, node_weight_names=landing_counting.node_weight_names, participation_query=participation_reader is not None, + gated_read=gated_continuation is not None, ) diff --git a/src/_lcm/regime_building/processing.py b/src/_lcm/regime_building/processing.py index f160643d7..7a68cd746 100644 --- a/src/_lcm/regime_building/processing.py +++ b/src/_lcm/regime_building/processing.py @@ -59,6 +59,9 @@ _get_passive_state_names, ) from _lcm.egm.scalar_query import ScalarEGMQueryModel + +# Load the solver before model construction so import frames cannot retain a model. +from _lcm.egm.step import compute_egm_carry_length from _lcm.egm.terminal import ( N_STATELESS_CARRY_ROWS, get_brute_child_carry_producer, @@ -116,7 +119,11 @@ ) from _lcm.post_decision_bound import PostDecisionBoundSpec from _lcm.processes import _ContinuousStochasticProcess, _IIDProcess -from _lcm.processes.ar1 import TauchenAR1Process, _TauchenOnNodesProcess +from _lcm.processes.ar1 import ( + RouwenhorstAR1Process, + TauchenAR1Process, + _TauchenOnNodesProcess, +) from _lcm.processes.iid import NormalIIDProcess from _lcm.processes.state_conditioned import ( Family, @@ -225,6 +232,7 @@ from _lcm.gated_edge import GatedEdge from _lcm.regime_building.Q_and_F import ( EDGE_REF_V_ARG, + EdgeRows, GatedContinuationSchedule, GatedContinuationSpec, ResolvedProjectedRegimeValue, @@ -339,7 +347,12 @@ Solver, UniformObservedFixedCost, ) -from lcm.transition import JointTransition, StochasticTransition, Transition +from lcm.transition import ( + AgeSpecializedGrid, + JointTransition, + StochasticTransition, + Transition, +) from lcm.typing import ( ActionName, BoolND, @@ -1885,7 +1898,6 @@ def _prepare_dcegm_query_models( FiniteOuterQuerySpec, build_query_model_authority, ) - from _lcm.egm.step import compute_egm_carry_length # noqa: PLC0415 from _lcm.solution.dcegm import ( # noqa: PLC0415 ExactEnvelope, _BoundDCEGM, @@ -4066,6 +4078,15 @@ def _state_handoff_errors( target=target, state_name=state_name, target_grid=target_grid, + ) or _rouwenhorst_node_mismatch_error( + phase_name=phase_name, + source=source, + target=target, + state_name=state_name, + source_grid=specs[source].solution.grid_states.get( + state_name + ), + target_grid=target_grid, ) if entry_error is not None: error_messages.append(entry_error) @@ -4176,6 +4197,43 @@ def _fail_if_a_law_reads_a_draw_the_edge_lacks( raise ModelInitializationError(format_messages(errors)) +def _rouwenhorst_node_mismatch_error( + *, + phase_name: PhaseName, + source: RegimeName, + target: RegimeName, + state_name: StateName, + source_grid: Grid | AgeSpecializedGrid | None, + target_grid: _ContinuousStochasticProcess, +) -> str | None: + """Return an error if a carried Rouwenhorst state changes its nodes. + + This check uses the fixed solve supports. The solve checks the completed + supports when both regimes carry the same runtime-parameterized law. + """ + if not ( + phase_name == "solution" + and isinstance(target_grid, RouwenhorstAR1Process) + and isinstance(source_grid, _ContinuousStochasticProcess) + and target_grid.is_fully_specified + and source_grid.is_fully_specified + ): + return None + source_nodes = np.asarray(source_grid.get_gridpoints()) + target_nodes = np.asarray(target_grid.get_gridpoints()) + if source_nodes.shape == target_nodes.shape and np.array_equal( + source_nodes, target_nodes + ): + return None + return ( + f"{phase_name} phase: the Rouwenhorst process '{state_name}' is carried " + f"from '{source}' to '{target}', but the two regimes place its nodes " + f"differently ({source_nodes.tolist()} vs {target_nodes.tolist()}). A " + "carried Rouwenhorst process requires identical solve nodes. Declare the same " + "process in both regimes, or use a Tauchen-family process if the law changes." + ) + + def _solve_laws_agree( *, specs: Mapping[RegimeName, PhasedRegimeSpec], @@ -5049,6 +5107,7 @@ def _prepare_numerical_solution_phase( # noqa: PLR0915 - native route admission ) decision_Q_and_F = functools.partial( _build_Q_and_F_per_period, + phase_name="solution", bound_specs=tuple( bound for bound in post_decision_bounds if bound.kind == "dag" ), @@ -6425,6 +6484,7 @@ def _build_simulation_phase( # noqa: C901, PLR0912, PLR0915 ) decision_Q_and_F = functools.partial( _build_Q_and_F_per_period, + phase_name="simulation", bound_specs=tuple( bound for bound in post_decision_bounds if bound.kind == "dag" ), @@ -7377,6 +7437,7 @@ def _process_regime_core( grids=all_grids[user_regime], clip_coordinate=phase_name == "simulation" and grid.simulated_draws == "nodes", + source_grid=all_grids[source_regime_name].get(process), ) for (user_regime, process), grid in carried_process_grids.items() } @@ -8889,8 +8950,9 @@ def _get_weights_func_for_process( grid: _ContinuousStochasticProcess, grids: Mapping[StateOrActionName, Grid] = MappingProxyType({}), clip_coordinate: bool = False, + source_grid: Grid | None = None, ) -> Callable[..., FloatND]: - """Get function that uses linear interpolation to calculate the process weights. + """Get the function returning a process's transition row at its current value. For processes whose params are supplied at runtime, the grid points and transition probabilities are computed inside JIT from those runtime params. For a @@ -8898,16 +8960,33 @@ def _get_weights_func_for_process( (`_get_conditioned_weights_func`), and `grids` is that regime's grid mapping, from which the conditioning state is resolved. - A value beyond the nodes takes its nearest edge node's row when the process - declares `off_grid="clip_lookup"` or `"clip_state"`, or with `clip_coordinate`. - A node draw needs the latter whatever the process declares: rows extrapolated - along the edge segment can carry negative weights, which are no probabilities - to sample with. + The row is a probability distribution at every current value: + + - **Tauchen family.** The law's own row at the current value, on the target's + nodes; at a node, exactly that node's tabulated row. + - **Rouwenhorst.** Its rows exist at its nodes only. Between nodes the row is + the convex blend of the two neighbouring rows; beyond the outer nodes, the + edge node's row. Under `off_grid="extrapolate"` the function carries + `EdgeRows`, from which the continuation extends linearly beyond the nodes. + A solve needs that only where the source declares a different law, whose + nodes can lie beyond the target's. + + A value beyond the nodes is first clipped to them when the process declares + `off_grid="clip_lookup"` or `"clip_state"`, or with `clip_coordinate`, which a + node draw needs whatever the process declares. An unconditioned IID process has one row repeated, so its weights are that row and read no current value: the continuation is then constant along the process's axis rather than recomputed at each of its nodes. + Args: + name: The process state's name. + grid: The target's process declaration, whose nodes the row is on. + grids: The target regime's grids, resolving a conditioning state. + clip_coordinate: Whether to clip the current value to the outer nodes. + source_grid: The source regime's declaration of the state, whose nodes the + current value takes in a solve. + """ sc = grid.state_conditioned if sc is not None: @@ -8917,62 +8996,106 @@ def _get_weights_func_for_process( if isinstance(grid, _IIDProcess): return _get_entry_weights_for_process(name=name, grid=grid) - clip_coordinate = clip_coordinate or grid.off_grid in ("clip_lookup", "clip_state") - if grid.params_to_pass_at_runtime: - n_points = grid.n_points - fixed_params = dict(grid.params) - runtime_param_names = { - qname_from_tree_path((name, p)): p for p in grid.params_to_pass_at_runtime - } - args = { - name: "ContinuousState", - **dict.fromkeys(runtime_param_names, "FloatND"), - } + clip = clip_coordinate or grid.off_grid in ("clip_lookup", "clip_state") + if not isinstance(grid, RouwenhorstAR1Process): + return _get_process_row_func(name=name, grid=grid, read="law", clip=clip) + weights_func = _get_process_row_func(name=name, grid=grid, read="edge", clip=clip) + if not clip and grid.off_grid == "extrapolate" and grid.n_points > 1: + weights_func.edge_rows = EdgeRows( # ty: ignore[unresolved-attribute] + neighbour=_get_process_row_func( + name=name, grid=grid, read="neighbour", clip=clip + ), + distance=_get_process_row_func( + name=name, grid=grid, read="distance", clip=clip + ), + in_solve=not ( + isinstance(source_grid, _ContinuousStochasticProcess) + and grid.has_same_law_as(source_grid) + ), + ) + return weights_func - @with_signature(args=args, return_annotation="FloatND", enforce=False) - def weights_func_runtime(*a: FloatND, **kwargs: FloatND) -> Float1D: # noqa: ARG001 - # `grid.params` is canonical (0-d JAX scalars) from its own - # boundary cast; `kwargs` arrive as JAX tracers from JIT. - process_kw: dict[str, FloatND | IntND] = { - **fixed_params, - **{raw: kwargs[qn] for qn, raw in runtime_param_names.items()}, - } + +def _get_process_row_func( + *, + name: str, + grid: _ContinuousStochasticProcess, + read: Literal["law", "edge", "neighbour", "distance"], + clip: bool, +) -> Callable[..., FloatND]: + """Get one read of a process's transition rows at a current value. + + - `"law"`: the law's row at the value (`transition_row_at`), or the node's + tabulated row where the value is a node. + - `"edge"`: the tabulated rows blended linearly in the value's coordinate, + clipped to the nodes, so beyond them the nearest edge node's row. + - `"neighbour"`: beyond the outer nodes, the row of the node next to the + nearest edge node; elsewhere the `"edge"` row. + - `"distance"`: how many edge segments the value lies beyond the outer nodes, + zero between them. + + With `clip`, the value is clipped to the outer nodes before it is read. + """ + n_points = grid.n_points + fixed_params = dict(grid.params) + runtime_param_names = { + qname_from_tree_path((name, p)): p for p in grid.params_to_pass_at_runtime + } + fixed_law = ( + None + if runtime_param_names + else (grid.get_gridpoints(), grid.get_transition_probs()) + ) + args = {name: "ContinuousState", **dict.fromkeys(runtime_param_names, "FloatND")} + + @with_signature(args=args, return_annotation="FloatND", enforce=False) + def row_func(*a: FloatND, **kwargs: FloatND) -> Float1D: # noqa: ARG001 + # `grid.params` is canonical (0-d JAX scalars) from its own + # boundary cast; `kwargs` arrive as JAX tracers from JIT. + process_kw: dict[str, FloatND | IntND] = { + **fixed_params, + **{raw: kwargs[qn] for qn, raw in runtime_param_names.items()}, + } + if fixed_law is None: gridpoints = grid.compute_gridpoints(**process_kw) transition_probs = grid.compute_transition_probs(**process_kw) - coord = get_irreg_coordinate(value=kwargs[name], points=gridpoints) - if clip_coordinate: - coord = jnp.clip(coord, 0, n_points - 1) - return map_coordinates( - input=transition_probs, - coordinates=[ - jnp.full(n_points, fill_value=coord), - jnp.arange(n_points, dtype=jnp.int32), - ], + else: + gridpoints, transition_probs = fixed_law + value = kwargs[name] + if clip: + value = jnp.clip(value, gridpoints[0], gridpoints[-1]) + if read == "law": + node = jnp.clip( + jnp.searchsorted(gridpoints, value, side="left"), 0, n_points - 1 + ) + return jnp.where( + gridpoints[node] == value, + transition_probs[node], + cast("TauchenAR1Process", grid).transition_row_at( + from_value=value, **process_kw + ), + ) + coordinate = get_irreg_coordinate(value=value, points=gridpoints) + if read == "distance": + return jnp.maximum( + jnp.maximum(coordinate - (n_points - 1), -coordinate), 0.0 + ) + clipped = jnp.clip(coordinate, 0, n_points - 1) + if read == "neighbour": + clipped = jnp.where( + coordinate > n_points - 1, + n_points - 2, + jnp.where(coordinate < 0, 1, clipped), ) - - return weights_func_runtime - - gridpoints = grid.get_gridpoints() - transition_probs = grid.get_transition_probs() - - @with_signature( - args={f"{name}": "ContinuousState"}, - return_annotation="FloatND", - enforce=False, - ) - def weights_func(*args: FloatND, **kwargs: FloatND) -> Float1D: # noqa: ARG001 - coordinate = get_irreg_coordinate(value=kwargs[f"{name}"], points=gridpoints) - if clip_coordinate: - coordinate = jnp.clip(coordinate, 0, grid.n_points - 1) return map_coordinates( input=transition_probs, coordinates=[ - jnp.full(grid.n_points, fill_value=coordinate), - jnp.arange(grid.n_points, dtype=jnp.int32), + jnp.full(n_points, fill_value=clipped), + jnp.arange(n_points, dtype=jnp.int32), ], ) - return weights_func + return row_func def _get_next_for_process(*, grid: Float1D) -> Callable[..., IntND]: @@ -10014,6 +10137,7 @@ class _GroupedQAndF: def _build_Q_and_F_per_period( *, + phase_name: PhaseName, active_periods: tuple[int, ...], bound_specs: tuple[PostDecisionBoundSpec, ...] = (), phase_reachability: PhaseReachability, @@ -10181,6 +10305,7 @@ def _build_Q_and_F_per_period( # singleton branch; with no age-specialized node the resolution is a # passthrough. built[key] = get_Q_and_F_collective( + phase_name=phase_name, bound_specs=bound_specs, flat_param_names=flat_param_names, koopmans_aggregator=koopmans_aggregator, @@ -10239,6 +10364,7 @@ def _build_Q_and_F_per_period( ) continue built[key] = get_Q_and_F( + phase_name=phase_name, bound_specs=bound_specs, flat_param_names=flat_param_names, functions=cast( diff --git a/src/_lcm/regime_building/zero_safe.py b/src/_lcm/regime_building/zero_safe.py index ca97915f6..9cd4aeeae 100644 --- a/src/_lcm/regime_building/zero_safe.py +++ b/src/_lcm/regime_building/zero_safe.py @@ -157,11 +157,20 @@ import jax import jax.numpy as jnp - -from _lcm.probability import scaled_down_by_power_of_two +from jax.custom_derivatives import SymbolicZero + +from _lcm.probability import ( + _IntegerTangent, + _unbiased_exponent, + is_live, + is_represented_zero, + scaled_by_power_of_two, + scaled_down_by_power_of_two, +) from _lcm.zero_safe import ( - relative_scales, - scaled_weighted_terms, + center_lottery_shifts, + scaled_lottery_mean, + scaled_lottery_terms_with_scale, zero_safe_weighted_term, ) from lcm.typing import FloatND, IntND @@ -204,22 +213,13 @@ def zero_safe_average( the latter replaced it; the two agree, as their bit-for-bit equality on non-positive shifts implies. - The two reductions treat the scale differently: - - - the **mass** lowers each weight onto the common scale before summing. A - live node too far below that scale to register contributes no share of a - total of order one, which is the right answer for a denominator; - - the **numerator** goes through `scaled_weighted_terms`, the engine's one - scaled contraction, which splits the relative scale between the - coefficient and the product. All of it on the coefficient would flush a - tiny probability before the value supplied its binades; all of it on the - product would overflow an ordinary coefficient meeting a value near the - top of the range, which no later scaling recovers. - - Both read the relative scale from `relative_scales`, so numerator and mass - are lowered onto the same one and their ratio is the mean. The common scale - is the smallest shift — the largest node — so every relative scale is a - power of two no greater than one and the lowering cannot overflow. + Scaled lotteries use `scaled_lottery_mean`. + It forms every weighted value from normal significands and places the + numerator and the mass on their own binary scales. A finite mean then + remains finite when its unnormalized numerator exceeds the format's range, + a rare node keeps its contribution against a large value, and a node near + the bottom of the normal range keeps its contribution against a small + coefficient. Unlike `jnp.average`, only `axis=None` or a single `int` `axis` is supported — every call site here reduces at most one axis at a time; pass @@ -263,19 +263,22 @@ def zero_safe_average( if shifts_arr is not None: shifts_arr = jnp.reshape(shifts_arr, new_shape) - if shifts_arr is None: - lowered_weights = weights_arr - else: - # `relative_scales` returns the SMALLEST shift's offset, so every entry - # is non-positive — which is exactly `scaled_down_by_power_of_two`'s - # precondition. It agrees with `jnp.ldexp` bit-for-bit on that domain and - # skips the general `frexp` graph, which here would run twice over the - # whole value surface. - lowered_weights = scaled_down_by_power_of_two( - values=weights_arr, shift=relative_scales(shifts=shifts_arr, axis=axis) + if shifts_arr is not None: + values, coefficients, scales = jnp.broadcast_arrays( + a_arr, weights_arr, shifts_arr ) + if axis is None: + values, coefficients, scales = ( + entry.reshape(-1) for entry in (values, coefficients, scales) + ) + else: + values, coefficients, scales = ( + jnp.moveaxis(entry, axis, -1) + for entry in (values, coefficients, scales) + ) + return _scaled_mean_with_tangent(values, coefficients, scales) - total_weight = jnp.sum(lowered_weights, axis=axis) + total_weight = jnp.sum(weights_arr, axis=axis) _raise_if_concretely_zero(total_weight=total_weight, context="zero_safe_average") # The masked numerator is used unconditionally -- see the module docstring's # PORTABILITY section. A whole-expression branch that keeps a RAW `sum(w*a)` @@ -291,25 +294,167 @@ def zero_safe_average( # extra reductions. NB the float64 bit-identity is a property of THIS single # vectorised reduction; the SEQUENTIAL regime-mixture fold in `Q_and_F` is a # different reduction order and is not made bit-portable by float64. - if shifts_arr is None: - # Weights on one scale already: whatever size the model supplied them - # at, and nothing upstream has accounted for a small one. - terms = zero_safe_weighted_term( - weight=weights_arr, value=a_arr, subnormal_is_accounted_for=False - ) - else: - # Scaled weights share their contraction with every other scaled - # weighted sum in the engine, which is what splits the downscale - # between the coefficient and the product so that neither a rare node - # against a large value nor an ordinary node against a near-max value - # leaves the format on the way. - terms = scaled_weighted_terms( - coefficients=weights_arr, shifts=shifts_arr, values=a_arr, axis=axis - ) + terms = zero_safe_weighted_term( + weight=weights_arr, value=a_arr, subnormal_is_accounted_for=False + ) numerator = jnp.sum(terms, axis=axis) return numerator / total_weight +# keyword-only-exempt: library-callback=jax.custom_jvp +def _scaled_mean_primal( + values: FloatND, coefficients: FloatND, shifts: IntND +) -> FloatND: + """Reduce one normalized lottery without exposing independent AD cotangents.""" + mean, total_weight = scaled_lottery_mean( + values=values, coefficients=coefficients, shifts=shifts + ) + _raise_if_concretely_zero(total_weight=total_weight, context="zero_safe_average") + return mean + + +# keyword-only-exempt: library-callback=jax.custom_jvp.defjvp +def _scaled_mean_jvp( + primals: tuple[FloatND, FloatND, IntND], + tangents: tuple[ + FloatND | SymbolicZero, + FloatND | SymbolicZero, + _IntegerTangent | SymbolicZero, + ], +) -> tuple[FloatND, FloatND]: + """Form normalized slopes before the linear, transposable tangent sum. + + An unperturbed channel contributes nothing, even if its partial derivative + is outside the dtype. Explicit directions through out-of-format partials + retain ordinary active-dtype tangent arithmetic, including zero times infinity. + """ + values, coefficients, shifts = primals + values_dot, coefficients_dot, _ = tangents + # A common exponent offset cancels in a normalized mean and its partials. + # Remove it before subtracting floating coefficient exponents. + shifts = center_lottery_shifts(coefficients=coefficients, shifts=shifts) + mean = _scaled_mean_with_tangent(values, coefficients, shifts) + + coefficient_exponent = _unbiased_exponent(coefficients) + live = is_live(coefficients) & jnp.isfinite(coefficients) + weight_exponent = coefficient_exponent - shifts + common = jnp.max( + jnp.where(live, weight_exponent, jnp.iinfo(jnp.int32).min // 2), + axis=-1, + keepdims=True, + ) + unit_coefficients = _rescale_mean_operand( + values=coefficients, shift=-coefficient_exponent + ) + mass = jnp.sum( + _rescale_mean_operand(values=unit_coefficients, shift=weight_exponent - common), + axis=-1, + keepdims=True, + ) + mass_exponent = _unbiased_exponent(mass) + unit_mass = _rescale_mean_operand(values=mass, shift=-mass_exponent) + + value_slopes = _rescale_mean_operand( + values=unit_coefficients / unit_mass, + shift=weight_exponent - common - mass_exponent, + ) + tangent = jnp.zeros_like(mean) + if not isinstance(coefficients_dot, SymbolicZero): + mean_column = mean[..., None] + finite_support = live & jnp.isfinite(values) + lower = jnp.min( + jnp.where(finite_support, values, jnp.inf), axis=-1, keepdims=True + ) + upper = jnp.max( + jnp.where(finite_support, values, -jnp.inf), axis=-1, keepdims=True + ) + # A finite mean's anchor stays inside its live support even when an + # intermediate underflow moved the published level outside that hull. + anchor = jnp.where( + jnp.isfinite(mean_column), jnp.clip(mean_column, lower, upper), mean_column + ) + safe_values = jnp.where( + is_represented_zero(coefficients) & ~jnp.isfinite(values), anchor, values + ) + value_exponent = _unbiased_exponent( + jnp.maximum(jnp.abs(safe_values), jnp.abs(anchor)) + ) + unit_gap = _rescale_mean_operand( + values=safe_values, shift=-value_exponent + ) - _rescale_mean_operand(values=anchor, shift=-value_exponent) + # Retain the mean's rounding residual on the centered value scale. A + # rounded level alone discards the sub-ULP difference needed by a slope. + # shortcut: opposing large gaps can round away the anchor. A wider + # accumulator is needed when these gaps cancel. + gap_exponent = _unbiased_exponent(unit_gap) + centered_values = _rescale_mean_operand(values=unit_gap, shift=-gap_exponent) + centered_exponent = value_exponent + gap_exponent + # Keep the centered sum on normal coefficient mantissas, including + # when every raw coefficient is close to the smallest normal value. + centered_shifts = shifts - coefficient_exponent - centered_exponent + # A zero gap contributes nothing and must not select a scale for the + # nonzero residual terms. The helper's mass terms are not used here. + unused_shift = jnp.max(centered_shifts, axis=-1, keepdims=True) + centered_shifts = jnp.where( + is_represented_zero(centered_values), unused_shift, centered_shifts + ) + residual_terms, _, residual_scale = scaled_lottery_terms_with_scale( + values=centered_values, + coefficients=unit_coefficients, + shifts=centered_shifts, + ) + residual = jnp.sum(residual_terms, axis=-1, keepdims=True) / unit_mass + residual_shift = -residual_scale - common - mass_exponent + # Subtract the two centered quantities on each entry's own scale; this + # also permits a residual too small to materialize before normalization. + absent_exponent = jnp.iinfo(jnp.int32).min // 2 + subtraction_exponent = jnp.maximum( + jnp.where( + is_represented_zero(unit_gap), absent_exponent, centered_exponent + ), + jnp.where( + is_represented_zero(residual), + absent_exponent, + _unbiased_exponent(residual) + residual_shift, + ), + ) + subtraction_exponent = jnp.where( + is_represented_zero(unit_gap) & is_represented_zero(residual), + 0, + subtraction_exponent, + ) + corrected_gap = _rescale_mean_operand( + values=unit_gap, shift=value_exponent - subtraction_exponent + ) - _rescale_mean_operand( + values=residual, shift=residual_shift - subtraction_exponent + ) + coefficient_slopes = _rescale_mean_operand( + values=corrected_gap / unit_mass, + shift=subtraction_exponent - shifts - common - mass_exponent, + ) + # A null event carrying a nonfinite value has no finite weight + # derivative; keep its zero stand-in convention after centering. + coefficient_slopes = jnp.where( + is_represented_zero(coefficients) & ~jnp.isfinite(values), + jnp.zeros_like(coefficient_slopes), + coefficient_slopes, + ) + tangent = tangent + jnp.sum(coefficient_slopes * coefficients_dot, axis=-1) + if not isinstance(values_dot, SymbolicZero): + tangent = tangent + jnp.sum(value_slopes * values_dot, axis=-1) + return mean, tangent + + +def _rescale_mean_operand(*, values: FloatND, shift: IntND) -> FloatND: + """Apply an integer power of two without a subnormal scaling operand.""" + lowered = scaled_down_by_power_of_two(values=values, shift=jnp.minimum(shift, 0)) + return scaled_by_power_of_two(values=lowered, shift=jnp.maximum(shift, 0)) + + +_scaled_mean_with_tangent = jax.custom_jvp(_scaled_mean_primal) +_scaled_mean_with_tangent.defjvp(_scaled_mean_jvp, symbolic_zeros=True) + + def _raise_if_concretely_zero(*, total_weight: FloatND, context: str) -> None: """Best-effort eager guard: raise if `total_weight` is a CONCRETE zero. diff --git a/src/_lcm/simulation/entry_allocations.py b/src/_lcm/simulation/entry_allocations.py index 84eef9390..2ff34b43a 100644 --- a/src/_lcm/simulation/entry_allocations.py +++ b/src/_lcm/simulation/entry_allocations.py @@ -28,6 +28,9 @@ from _lcm.grids import Grid from _lcm.grids.materialization import admitted_grid_extent, materialize_original_grid from _lcm.params.edges import EDGES, flat_namespaces + +# Load the query module before a simulation owns a model and its buffers. +from _lcm.policy_queries import query_parameter_namespaces from _lcm.processes.base import _ContinuousStochasticProcess from _lcm.simulation.entry_inputs import SimulationEntryInputs, SolutionResultBoundary from _lcm.simulation.host_operations import ProfiledSimulationOperations @@ -262,8 +265,6 @@ def _place_query_solve_parameters( self, *, flat_params: FlatParams, regimes: Mapping[RegimeName, Regime] ) -> None: """Admit only actual query consumers' copies, retaining every source.""" - from _lcm.policy_queries import query_parameter_namespaces # noqa: PLC0415 - views: dict[RegimeName, FlatParams] = {} self.solve_parameter_views = MappingProxyType(views) self._stages["query_solve_params"] = views diff --git a/src/_lcm/solution/backward_induction.py b/src/_lcm/solution/backward_induction.py index 990969595..4d9f1af1d 100644 --- a/src/_lcm/solution/backward_induction.py +++ b/src/_lcm/solution/backward_induction.py @@ -164,6 +164,7 @@ regime_kernel_params, ) from _lcm.participation_continuation import participation_surface_leaves +from _lcm.processes.ar1 import RouwenhorstAR1Process from _lcm.processes.grid_resolution import ProcessGridResolver from _lcm.regime_building.gated_edges import ( EDGE_PERIOD_CONTEXT_ARGS, @@ -287,6 +288,7 @@ ) from lcm.exceptions import ( ExecutionPlanningError, + InvalidParamsError, InvalidValueFunctionError, ModelInitializationError, ShockDeclarationError, @@ -2658,13 +2660,54 @@ def _build_base_state_action_spaces( runtime-grid completion (e.g. process gridpoint computation) runs once per regime instead of once per period-regime iteration. """ - return { + spaces = { regime_name: regime.solution.state_action_space( regime_params=regime_kernel_params(flat_params, regime_name=regime_name), process_grid_resolver=process_grid_resolver, ) for regime_name, regime in regimes.items() } + _fail_if_carried_rouwenhorst_nodes_differ(regimes=regimes, spaces=spaces) + return spaces + + +def _fail_if_carried_rouwenhorst_nodes_differ( + *, + regimes: Mapping[RegimeName, Regime], + spaces: Mapping[RegimeName, StateActionSpace], +) -> None: + """Check resolved nodes where both regimes carry one declared solve law.""" + for source_name, source in regimes.items(): + runtime_states = tuple( + state_name + for state_name, grid in source.solution.grids.items() + if isinstance(grid, RouwenhorstAR1Process) and not grid.is_fully_specified + ) + if not runtime_states: + continue + for target_name in source.solution.reachability.union_targets( + source=source_name + ): + if target_name == source_name: + continue + for state_name in runtime_states: + target_grid = regimes[target_name].solution.grids.get(state_name) + if not isinstance(target_grid, RouwenhorstAR1Process) or ( + target_grid.is_fully_specified + ): + continue + source_nodes = spaces[source_name].states.get(state_name) + target_nodes = spaces[target_name].states.get(state_name) + if source_nodes is None or target_nodes is None: + continue + left, right = jax.device_get((source_nodes, target_nodes)) + if not np.array_equal(left, right): + msg = ( + f"Rouwenhorst process '{state_name}' carried from " + f"'{source_name}' to '{target_name}' requires identical " + f"solve nodes. Got {left.tolist()} and {right.tolist()}." + ) + raise InvalidParamsError(msg) def _drain_V_arr_shards( diff --git a/src/_lcm/zero_safe.py b/src/_lcm/zero_safe.py index 5fdababba..89500ffd0 100644 --- a/src/_lcm/zero_safe.py +++ b/src/_lcm/zero_safe.py @@ -68,17 +68,21 @@ import jax.numpy as jnp from _lcm.probability import ( + _significand_in_unit_range, + _unbiased_exponent, balanced_product, binades_above_smallest_normal, exact_product, is_below_smallest_normal, + is_live, is_negative, is_represented_zero, nonzero_exact_product, + scaled_by_power_of_two, scaled_down_by_power_of_two, scaled_exact_product, ) -from lcm.typing import FloatND, IntND +from lcm.typing import BoolND, FloatND, IntND def factored_weighted_term(*, factors: FloatND, values: FloatND) -> FloatND: @@ -345,94 +349,260 @@ def sum_in_value_order(*, values: FloatND, axis: int = 0) -> FloatND: return jnp.sum(jnp.sort(arr, axis=axis), axis=axis) -def scaled_weighted_terms( - *, coefficients: FloatND, shifts: IntND, values: FloatND, axis: int | None = None -) -> FloatND: - """Return each node's contribution, formed before its scale is applied. - - A node's contribution to a weighted sum is `w 2**-s v`, and the order the - three are combined in decides whether the format can hold it. Lowering the - weight first asks the format for `w 2**-s` on its own, which for a node far - below the likeliest one is a subnormal — flushed to zero on a backend that - does not carry them — and the value never gets to supply the binades it was - holding. A rare node against a large value is then lost even though its - contribution is an ordinary number: a probability of `2**-128` against a - value of `2**126` contributes a quarter, not nothing. - - Applying all of it to the product instead fails from the other end: a - coefficient of order one meeting a value near the top of the range - overflows to infinity, and the downscale that would have brought the - contribution back into range never gets to run. Splitting the scale - between the two is what holds at both ends, and it costs nothing, because - every intermediate is a power of two away from one the format holds. - - The non-finite protection that a lowered weight needs is unnecessary here: - an infinity or a `NaN` at a live node survives the multiplication and no - power of two reaches it, so the term carries the answer on its own. What is - still dropped is a node whose contribution is genuinely below the sum's last - place, which is the declared approximation and is one-sided. +def center_lottery_shifts(*, coefficients: FloatND, shifts: IntND) -> IntND: + """Remove a common weight gauge before coefficient exponent arithmetic. + + Only live finite coefficients select the gauge. Relative shift spans and + subsequent exponent arithmetic must fit int32; private arbitrary endpoint + spans are not an admitted scaled-measure representation. + """ + coefficients = jnp.asarray(coefficients) + shifts = jnp.broadcast_to(jnp.asarray(shifts), coefficients.shape) + live = is_live(coefficients) & jnp.isfinite(coefficients) + fallback = jnp.max(shifts, axis=-1, keepdims=True) + reference = jnp.min(jnp.where(live, shifts, fallback), axis=-1, keepdims=True) + return shifts - reference + + +def scaled_lottery_mean( + *, values: FloatND, coefficients: FloatND, shifts: IntND +) -> tuple[FloatND, FloatND]: + """Return a scaled lottery's mean over the last axis, and its scaled mass. + + Every finite operand is held as a significand in `[1, 2)` and an integer + exponent. A node's weighted value is the product of two significands, + which is always a normal number, and its exponent is the sum + `coefficient - shift + value`. The numerator is placed so its largest + term sits in `[1, 4)`, and the mass so its likeliest node sits in + `[1, 2)`. Each term is lowered from there by its own distance to the + largest one. When no live finite nonzero value contributes, the numerator + uses the mass's anchor: a zero numerator then has zero relative exponent, + while live infinities and NaNs retain their original products. + + A term that leaves the format on the way down is therefore smaller than + the largest term by the whole normal range. Without cancellation it + cannot be material to the numerator, whatever the scale of the values, + the weights, or the mean. + + shortcut: cancellation can expose a small term that underflows on the + shared scale. Use a wider accumulator if the application needs that case. + + Neither sum can overflow, since every term is + below four. The two exponents meet once, in the final ratio. Their + difference is at most the largest finite value exponent when such a value + contributes, and zero otherwise, so the upward part is a normal power of + two. If rounding makes reconstruction overflow, + return the corresponding endpoint of the live support. A finite-support + mean lies between those endpoints; genuine live infinities remain infinite. + Finite estimates and NaNs pass through unchanged. + + A null event contributes nothing, even against an infinite value. A live + node with a nonfinite value carries that value into the mean. A + coefficient that is negative, infinite, or NaN poisons its whole row. + Relative shift spans and the derived exponent sums must fit int32. Args: - coefficients: The scaled weights' significands. - shifts: Each one's own base-two scale. - values: What each weight stands against. - axis: The axis the sum will be taken over, so that each reduced slice - is brought onto the scale its own largest node sets, or `None` - when the whole array is summed together. + values: Continuation values of the lottery along the last axis. + coefficients: The weights' significands, over the same axis. + shifts: Each weight's own base-two scale, broadcast against them. Returns: - Each node's contribution, on the one scale the sum is taken at. + Tuple of the mean and the mass on its own normalized scale. The mass + is zero only when the row has no live node. """ - arr = jnp.asarray(coefficients) - scale = relative_scales(shifts=shifts, axis=axis) - # Neither end of the scale is safe on its own: all of it on the weight - # underflows a rare node before the value can supply the binades it was - # holding, and all of it on the product overflows an ordinary weight - # meeting a value near the top of the range. So the weight takes as much - # as it has room for while staying normal, and the product takes the rest. - room = binades_above_smallest_normal(arr) - on_the_weight = jnp.maximum(scale, -room) - return scaled_down_by_power_of_two( - values=zero_safe_weighted_term( - weight=scaled_down_by_power_of_two(values=arr, shift=on_the_weight), - value=values, - subnormal_is_accounted_for=False, - ), - shift=scale - on_the_weight, - ) + coefficients = jnp.asarray(coefficients) + values = jnp.asarray(values) + shifts = center_lottery_shifts(coefficients=coefficients, shifts=shifts) + live = is_live(coefficients) & jnp.isfinite(coefficients) + invalid = is_negative(coefficients) | ( + ~jnp.isfinite(coefficients) & ~is_represented_zero(coefficients) + ) + weight_exponent = jnp.where(live, _unbiased_exponent(coefficients) - shifts, 0) + unit_coefficients = jnp.where( + live, _significand_in_unit_range(coefficients), jnp.zeros_like(coefficients) + ) -def relative_scales(*, shifts: IntND, axis: int | None = None) -> IntND: - """Return each node's base-two scale relative to the largest node beside it. + finite_value = jnp.isfinite(values) & ~is_represented_zero(values) + unit_values = jnp.where( + finite_value, + jnp.copysign(_significand_in_unit_range(values), values), + values, + ) + contributes = live & finite_value + term_exponent = weight_exponent + jnp.where( + finite_value, _unbiased_exponent(values), 0 + ) + mass_exponent = _largest_selected(selected=live, exponents=weight_exponent) + numerator_exponent = _largest_selected( + selected=contributes, exponents=term_exponent, fallback=mass_exponent + ) + products = zero_safe_weighted_term( + weight=unit_coefficients, value=unit_values, subnormal_is_accounted_for=True + ) + value_terms = scaled_down_by_power_of_two( + values=products, + shift=jnp.where(contributes, term_exponent - numerator_exponent, 0), + ) - A node's probability is `coefficient * 2**-shift`, so nodes held at - different shifts are not comparable as plain floats and a sum over them - needs one scale. That scale is the smallest shift — the largest node — - which makes every relative scale non-positive, so bringing a node onto it - is a downscale and cannot overflow. + weight_terms = scaled_down_by_power_of_two( + values=unit_coefficients, + shift=jnp.where(live, weight_exponent - mass_exponent, 0), + ) - A weighted mean is invariant to a common factor on its weights, so the - numerator and the mass have to be brought onto the *same* scale for the - ratio to be the mean. Both read it from here rather than each deriving it, - since a disagreement between the two would be a silent power of two in the - published value. + mass = jnp.sum(weight_terms, axis=-1) + ratio = jnp.sum(value_terms, axis=-1) / mass + exponent = (numerator_exponent - mass_exponent)[..., 0] + upward = scaled_by_power_of_two( + values=jnp.ones_like(ratio), shift=jnp.maximum(exponent, 0) + ) + mean = scaled_down_by_power_of_two( + values=ratio * upward, shift=jnp.minimum(exponent, 0) + ) + # A normalized nonnegative mean cannot exceed its live support. + lower = jnp.min(jnp.where(live, values, jnp.inf), axis=-1) + upper = jnp.max(jnp.where(live, values, -jnp.inf), axis=-1) + mean = jnp.where(jnp.isinf(mean), jnp.where(jnp.signbit(mean), lower, upper), mean) + nan = jnp.asarray(jnp.nan, dtype=coefficients.dtype) + invalid_row = jnp.any(invalid, axis=-1) + return jnp.where(invalid_row, nan, mean), jnp.where(invalid_row, nan, mass) + + +def _largest_selected( + *, selected: BoolND, exponents: IntND, fallback: IntND | None = None +) -> IntND: + """Return each row's largest selected exponent, using the fallback only if empty.""" + absent = jnp.iinfo(exponents.dtype).min + largest = jnp.max(jnp.where(selected, exponents, absent), axis=-1, keepdims=True) + has_selected = jnp.any(selected, axis=-1, keepdims=True) + return jnp.where(has_selected, largest, 0 if fallback is None else fallback) + + +def scaled_lottery_terms_with_scale( + *, values: FloatND, coefficients: FloatND, shifts: IntND +) -> tuple[FloatND, FloatND, IntND]: + """Return a lottery's value terms and weight terms on one shared scale. + + A node's contribution to a mean is `c * 2**-s * v`, and the order those + three are combined in decides whether the node survives. Two orders each + lose it at one end of the range: + + - forming the weight `c * 2**-s` first loses a rare node, because the + weight of a node many binades below the likeliest one is not + representable and becomes zero, taking its value with it — although the + *product* it was heading for may be an ordinary number, which is + precisely the case where the node changes the answer; + - forming `c * v` first loses a node whose coefficient has been normalized + above one and whose value sits near the top of the range, because that + intermediate overflows to infinity before any scale is applied to bring + it back. + + Splitting the scale covers both. The coefficient absorbs as much of the + downward shift as it can while staying normal, the product absorbs the + remainder. Neither an unrepresentable weight nor an overflowing product is + ever materialized, and a rare node earns its place in the mean exactly when + its value is large enough to offset its probability. + + Normalize each positive finite coefficient into a normal significand + before any product; its exact binary exponent moves into its shift. + Both returned terms carry the same shift, so their scale cancels in the + ratio. The common shift is selected from those normalized encodings, per + lottery rather than per batch. No unrelated lottery or dead node selects it. + + The values are not normalized, so a value near the bottom of the normal + range can lose its product. The caller is the scaled mean's centered + residual, whose values are normal significands; a mean reduces through + `scaled_lottery_mean` instead. + + This physical-scale helper requires all relative shift and derived exponent + arithmetic, including the returned exponent, to fit int32. Its caller uses + bounded IEEE-exponent-derived shifts. This is not an arbitrary private-int32 + endpoint-span interface, and no live exponent is silently saturated. + + Headroom bounds each actual scaled contribution, as well as the weight + total. An extremely rare large value must not force an unrelated normal + small contribution below the arithmetic range. A cardinality bound keeps + both sums below the top binade without materializing an overflowing product. + + A coefficient that is not a probability at all — negative, infinite, or + NaN — is not a dead node and is not silently dropped. It poisons its whole + row, so a malformed lottery is visible in the result rather than reduced to + a plausible number. Args: - shifts: Each node's own base-two scale. - axis: The axis the sum will be taken over, so that each reduced slice - is brought onto the scale its own largest node sets, or `None` - when the whole array is summed together. + values: Continuation values of the lottery along the last axis. + coefficients: The weights' significands, over the same axis. + shifts: Each weight's own base-two scale, broadcast against them. Returns: - The non-positive power of two carrying each node onto the common - scale, with the reduced axis kept so it broadcasts against the values. + Tuple of the value terms and the weight terms, both over the last axis + and both carrying the row's shared scale, followed by that binary exponent. This + exponent multiplies the unscaled terms; subtract it to recover their scale. """ - shifts_arr = jnp.asarray(shifts) - common = ( - jnp.min(shifts_arr) - if axis is None - else jnp.min(shifts_arr, axis=axis, keepdims=True) + coefficients = jnp.asarray(coefficients) + values = jnp.asarray(values) + shifts = jnp.broadcast_to(jnp.asarray(shifts), jnp.shape(coefficients)) + + live = is_live(coefficients) & jnp.isfinite(coefficients) + invalid = is_negative(coefficients) | ( + ~jnp.isfinite(coefficients) & ~is_represented_zero(coefficients) + ) + # Normalize each coefficient before multiplying by a small value. Its + # exact power of two moves into the accompanying shift, not into a float + # product that may underflow even when the normalized mean is normal. + coefficient_exponent = jnp.where(live, _unbiased_exponent(coefficients), 0) + normalization = -coefficient_exponent + coefficients = scaled_down_by_power_of_two( + values=coefficients, shift=jnp.minimum(normalization, 0) + ) + coefficients = scaled_by_power_of_two( + values=coefficients, shift=jnp.maximum(normalization, 0) + ) + shifts = shifts - coefficient_exponent + unusable = jnp.max(shifts, axis=-1, keepdims=True) + common = jnp.min(jnp.where(live, shifts, unusable), axis=-1, keepdims=True) + scale = (common - shifts).astype(jnp.int32) + + contribution_exponent = ( + _unbiased_exponent(coefficients) + + scale + + jnp.maximum(_unbiased_exponent(jnp.abs(values)), 0) + ) + largest_exponent = jnp.max( + jnp.where(live, contribution_exponent, jnp.iinfo(jnp.int32).min // 2), + axis=-1, + keepdims=True, + ) + # Each product's two significands are below two; n terms add ceil(log2(n)) + # binades. Keeping the bound below 2**(maxexp-1) leaves rounding headroom. + sum_binades = (values.shape[-1] - 1).bit_length() + headroom = jnp.maximum( + largest_exponent + 2 + sum_binades - (jnp.finfo(values.dtype).maxexp - 1), + 0, + ) + full = scale - headroom + + room = binades_above_smallest_normal(coefficients) + on_weight = jnp.maximum(full, -room) + scaled_coefficients = scaled_down_by_power_of_two( + values=coefficients, shift=on_weight + ) + products = zero_safe_weighted_term( + weight=scaled_coefficients, + value=values, + subnormal_is_accounted_for=False, + ) + value_terms = scaled_down_by_power_of_two(values=products, shift=full - on_weight) + weight_terms = scaled_down_by_power_of_two(values=coefficients, shift=full) + + # Zero coefficients already annihilate their values; masking the terms + # again would erase a finite node's derivative with respect to its weight. + invalid_row = jnp.any(invalid, axis=-1, keepdims=True) + nan = jnp.asarray(jnp.nan, dtype=coefficients.dtype) + return ( + jnp.where(invalid_row, nan, value_terms), + jnp.where(invalid_row, nan, weight_terms), + common - headroom, ) - return (common - shifts_arr).astype(jnp.int32) diff --git a/src/lcm/model.py b/src/lcm/model.py index e9d876989..07fbddce5 100644 --- a/src/lcm/model.py +++ b/src/lcm/model.py @@ -244,6 +244,7 @@ selected_persistable_artifact_refs, ) from _lcm.solution.backward_induction import ( + ExecutableCache, GatherChecks, _build_base_state_action_spaces, _reject_edge_fold_state_param_collisions, @@ -1440,6 +1441,8 @@ def _prepare_declarations( # noqa: PLR0915 # Fusion verdicts read off compiled solve programs; warm solves reuse the # executables, so they reuse the verdicts instead of re-reading the HLO. self._gather_checks: GatherChecks = {} + # Lowering keys contain specialization and layouts, never call operands. + self._solve_executable_cache = ExecutableCache() # Immutable structural blueprints of earlier solves, keyed by abstract # schema; a warm solve binds one instead of resolving every program. self._structural_blueprints: StructuralBlueprintCache = ( @@ -2256,6 +2259,7 @@ def __setstate__(self, state: _PickledModel) -> None: self._active_generation = None self._initial_generation_key = state.get("_initial_generation_key") self._gather_checks = {} + self._solve_executable_cache = ExecutableCache() self._structural_blueprints = StructuralBlueprintCache() self._validated_selection_params = set() self._solution_param_projection = solution_param_projection(self._regimes) @@ -3064,6 +3068,7 @@ def _solve_compiled( gather_checks=self._gather_checks, period_capture=period_capture, structural_blueprints=self._structural_blueprints, + executable_cache=self._solve_executable_cache, ) except InvalidValueFunctionError as exc: regime = self._user_regimes.get(exc.regime_name or "") diff --git a/tests/candidate_certificate/direct_flow.py b/tests/candidate_certificate/direct_flow.py index 9d1970d47..e1aed4816 100755 --- a/tests/candidate_certificate/direct_flow.py +++ b/tests/candidate_certificate/direct_flow.py @@ -613,7 +613,7 @@ S02__LCM_EGM_BUDGET_SOURCE: "1c8fb0cbc8f9156950bea34c71c9ccce2c58ac17ec6b9f1221f8c8966f1031d2", S02__LCM_EGM_CARRY_SOURCE: "17c85a9146e68a8b57487754bcb89b879e62bcd391699d82ac4116ec7e4c4691", S02__LCM_EGM_QUERY_DATA_SOURCE: "5ca53117248f9009d4d9b696fdb46a361fa47c5b082757ccc9beb6ccd967bde3", - S02__LCM_REGIME_BUILDING_Q_AND_F_SOURCE: "242811e5f010d1f72e29cf0768c845579261bb50b699e6dcd9972b77b9e3d1f1", + S02__LCM_REGIME_BUILDING_Q_AND_F_SOURCE: "2a275560230e4248b30b39393bb77f58fc3cbd098ac8d20f4b134b64217d6386", S02__LCM_SIMULATION_SUBJECT_PARALLEL_SOURCE: "66d70a81a7ec535d92933bc8841c6bbe7472e227509f88fc6d3bdd00b6c95e76", S02__LCM_SOLUTION_EGM_SOURCE: "c554d6e993da4b3b253ae8235a7fcac56c74a7bdc9c2537e84515d6c39af52bf", S02__LCM_SOLUTION_KERNEL_OUTPUT_SOURCE: "4b814b0aecacb22cc1f5b47d6bb9006f3f0f5eb08dc0eb18f1345fcd4becb770", @@ -661,7 +661,7 @@ COMBINED_STORES_SOURCE: "6c7be7157d70fab084f524f93fd182cff90b612a96dddacaf6e05ef7a1bf9bf7", SIMULATION_POLICY_PROGRAMS_SOURCE: "2be9ca13d372fede91e4adf0f54ae22f4105aad1f9e28d255eea0c63bc0cf734", PUBLISHED_POLICY_SOURCE: "6e0e77a3e47cec4690b9e3d917159c5a2503efd1a6e7239fcc72f74ae0146316", - SIMULATION_ENTRY_ALLOCATIONS_SOURCE: "c3a68cbf4c54a0f5ae15204e0d00070f9b991a2efae998f9f4e69c3dff97fa1c", + SIMULATION_ENTRY_ALLOCATIONS_SOURCE: "1989ff5ac2f0e59150ae806cfc31af7c731f792f2958bf6ee83045c6e2448918", NBEGM_SOURCE: "99dd2e916cb6d265c4bf7d12de55992a9ba925cddec40ca53a5777c234e6fe20", CONTINUATION_ARGUMENTS_SOURCE: "2bfffbd49e5a2e267fcfdefadd21cf4249dcc6979a6ff4889098c37a06dcc0e1", SIMULATION_TASTE_STREAM_SOURCE: "f6b629ed946bb3e211f890dc20f32741db6497c119ebb3b66adc578f7732352c", @@ -692,7 +692,7 @@ ARGMAX_SOURCE: "b508d4e10350de8b54707db238d01c7de6c73b4ca6b0176e0c6c12ec762952dc", COLLECTIVE_SOURCE: "4cc0683d493f597684f5801909d297145d8bade0aa752c3e35cf8af2cb55edd9", MAX_Q_SOURCE: "62e5010e5f535ed3731218a5549167d6f5ea332b145d2dcece88d492949fd78c", - PROCESSING_SOURCE: "8afa2618cb5b01f70a5907fd007e960990500b1ca7ccc0d25c814dc06a637383", + PROCESSING_SOURCE: "8d5e2e23ec8d84426bfc1c1c2664d1612409349c7d8507e3936fb1cf3fdd5d80", GRID_SEARCH_SOURCE: "691879f5e6e90a5a764fe247f6d15c8e8f74dc3a8e05dc0913ee1742c54a952f", CORE_PROGRAM_SOURCE: "7d8197a3d2607a3380be63408ae4cf2b8d8ebbe68b043cc3aff76bf1f5c6b78a", OUTPUT_LAYOUT_SOURCE: "c7da1256b36b3b6d89200bbae5267936d84e27746ff2c776dced4ea612ec3eb9", @@ -705,17 +705,17 @@ DISPATCHERS_SOURCE: "a78d5271fcfc7437b68bd755ce7c2b8b0b78d5f26ed00a3fb4424133725da8b2", FUNCTOOLS_SOURCE: "8dbb11ab2f7bac3cefe98c732a0ddb429d9e4189ea79517cff3f54d90d405cd5", CONTAINERS_SOURCE: "1b58c79878a182dd61929a15d4e3a2f3c249411d19d5df8853476bc57c2a87e1", - ZERO_SAFE_SOURCE: "8d54492b73e33461f750420eef45ba8c8281c467acd0c77ba2eb90281793c8d3", + ZERO_SAFE_SOURCE: "b8ca10a6190844e1b032f4af669d85b311e5aabcc73e6e67f5e53bc5841ae84e", LOGSUMEXP_ACTION_REDUCTION_SOURCE: "4799ad9bfbc02ae1e5d5270a18ed81fe682f1004d63ae6cf796ff48ac5699445", - PROBABILITY_SOURCE: "60ccd04b143c714360388fcce2730804a4ca729ea4db82e4a0100732e155e53f", + PROBABILITY_SOURCE: "6231a021bcf78740ea167995aa8cff0009de2f973c09347d244874a1d9d5cd77", ENGINE_SOURCE: "9723b0411730e6bea66d1812f9bdab63d720aadb2c3a2adf8b8ad7da19680640", STATE_ACTION_SPACE_SOURCE: "761150639f8756f1157abbcc425e39e5d0b8a949afc0ccaf6f29bdad964d7476", SIMULATION_SOURCE: "2620420127a1655e091ddadafa271ef3036705b448dc1fb6013c88cbcfe22055", SIMULATION_TRANSITIONS_SOURCE: "74d8ecfd0726c58d7a33457677079a18f5065b338d29ab14e506bc301456c365", SIMULATION_COMPILE_SOURCE: "2c54bd385d0205897bebd42c6b63d55eb0896a04e208786f4e0028b20e81074d", - MODEL_SOURCE: "c224a50b35e4b50e8403a8c8bf18968d16923c6ba6331f726e65bd29e24b4919", + MODEL_SOURCE: "bf00b963e6374ab94b5e46da0ff6ff2588e072ac0df05bc6b8d48c98ccea84fb", SOLVER_API_SOURCE: "65c8235466fdeda91e14b94863e8e8fa84eaa4fefc7b0e0fd30e5efcd514ffc5", - BACKWARD_INDUCTION_SOURCE: "6f57d51a0a40be63392c0d4e17fd1fe9c1d5bb96a83ef23ef859d17248e0689a", + BACKWARD_INDUCTION_SOURCE: "fdbe468b45f89a2e2436cbedd63705d9a0e26f08bfcbe85a2a91a15f2b6b5ea7", PERIOD_REPLAY_SOURCE: "d504ad8064dd8d7fc127ebd05510dc7ef1abc939627ab3f004b1ee75427e19ae", INITIAL_CONDITIONS_SOURCE: "6d1c779d539ec84a0edb13b1926782492fdb5d999da110fde354b9c6fceeb6b4", RESULT_SOURCE: "d2b09b95537cb65dff52e87a4b9b91a6fe99570e8b98c7ce33a95f5e9d7f5ef1", @@ -723,7 +723,7 @@ RESULT_METADATA_SOURCE: "ba9ec4f48e7df67b4a57a35cd3e781906d7ef64a35f3bc37238033c1c168df3e", ADDITIONAL_TARGETS_SOURCE: "3769b0eb0dad646767068fd4cf6e73a707115d2ede3ae5e3d9859b82b75d63fd", SIMULATION_RANDOM_SOURCE: "314164a170cf4eb3d4680dd575022c83943998f2c1ec78ba09d1085984d34a5e", - FOLD_ZERO_SAFE_SOURCE: "c1c748c17eabf1f3439bf4309a1cf79ed3a6dc85c8532a3a4b3dcb5559acf638", + FOLD_ZERO_SAFE_SOURCE: "f1f8a856013f15d09dbb2da93881b587634f0bb429876dda83e96b7af0e2dd83", SOLUTION_CONTRACT_SOURCE: "f649bf76181815bd7db3b1a6452849ba6d2922cc963b9dd1c180b30e06d00f15", GRIDS_INIT_SOURCE: "3c720bc2240dd1cfd45855ce501f03f8a05abda5de1142b9d00208e517b9ddce", GRID_BASE_SOURCE: "2d9c7f1a0827f3ca172417a2ee2bf60b15c9ccb3dcedf3a94fb502e2d57538de", @@ -732,9 +732,9 @@ CONTINUOUS_GRID_SOURCE: "37eeadb95ca49855248da90a99fd5b5424f2acc28c9bf1535d228bfcf0b112f5", PIECEWISE_GRID_SOURCE: "88dea9f6573e8b88db1a4f7a28f77b80eeb7a06bc29e70d4314be76237a1bc9f", PROCESSES_INIT_SOURCE: "fbce6ed4c889cf4c30f5242c142b4dcf2fa9e186b75cd17be1557f827abff00a", - PROCESS_BASE_SOURCE: "3e9c95ca2a4de89a90d954ec227ddbb20c8a12f57e7140c8056817ebf93dfcd8", + PROCESS_BASE_SOURCE: "c6b25978ef4fdbf16212b38e5f3f4cb4a776aa5792097419e0af0a39ef2460fe", PROCESS_IID_SOURCE: "0ac786980fdd6346363fbf6cd569d9766727c250c2695b06fae732d079ffe1d2", - PROCESS_AR1_SOURCE: "7f86f58de1364c68a1f512ae86f653d4abd2259b5dd0dc25553ba226a3f44ddf", + PROCESS_AR1_SOURCE: "a7f766eacf08a2f907942a0a7383950ec2e166e19007504a78e2133d6a0dbdb2", VARIABLES_SOURCE: "8445fd5d92144d013955027460ee204debfdcedf8bb5ef5d10092538cd18de8c", PARAMS_REGIME_TEMPLATE_SOURCE: "d1f9eca748b625c00c33351118682171b65ccd813ffdaf1abd52469be7f16a35", PARAMS_PROCESSING_SOURCE: "cd703789b7defbf24801e2450efc536600351b905d5b2a211c3a634bbc3cb4c9", @@ -952,7 +952,7 @@ }, ), "src/_lcm/zero_safe.py": ( - "32bf37e7db6997c36d0faa5a152ea883f4588c650174d5805c3f4c805682bffd", + "2da85a5039429957e694f84c17da63a56120d340f3eec8da823ee4bbf5872b6d", { "zero_safe_weighted_term": "1f9682a923d63877e5ec668bb404bf92911278ee806e99b5ef60c098a9c82dd1", }, @@ -1093,7 +1093,7 @@ }, ), SIMULATION_ENTRY_ALLOCATIONS_SOURCE: ( - "2038657753b59b873d9bc2357d4d40d5c758eeb5c534bb6b6bbd261460af3cfa", + "92104c8d24fc96e96ddc29fbbbc51c2d7b3ed4c82f0ba0f7b9c35e88f68210aa", { "SimulationEntryAllocations.snapshot": "a2b219011564236e6b8f863d59086d802a43ea49a2f0f73a01b99358c7faf49f", "SimulationEntryAllocations.solve_input_roots": "abbd1f8e3a3956b718cefcc7de938bbaea7cc909e6a898c1e95607cb60c345f3", @@ -1576,7 +1576,7 @@ }, ), MODEL_SOURCE: ( - "6e3f93b555e112885e174e074b69ab475f390ab5d7f8694bbf0717272b422010", + "59432296c64e1cc9993cd2ee35135005b375be110f9e9f2ec1e295cb0ea34afa", { "_validate_sharded_state_capability": "e60cbf29e61c167df80d03b822e100799d7f9be529a8013c6f014be6df0c7233", "_supports_continuous_sharding_vocabulary": "1ce9646ee043fb623720d6367b531c860ab0020969a58ec62682784814843387", @@ -1593,7 +1593,7 @@ "Model._model_fingerprint": "5b37a0b093cb5e1754d64158e087da1e29358fc09707654626b53a468f767829", "Model.solve": "0e4bf6d7525b6397eee7ac8286d91b21b40cbed9cd1aa2dda0b508cec56ced55", "Model._solve_from_flat_params": "915199bff9dd8805fbebb1eadf3afae8a2f58e5c4d34328b7e349abe8cf505db", - "Model._solve_compiled": "6f1e86c43468452d2f514058cc2fa6358f55e84bedfa2fe4bef41a2234e44ab4", + "Model._solve_compiled": "5d5a8fba19fe1c948be536494029819975b47e24e12388c8eec75b621aa77fd3", "Model._consume_owned_solution": "02316f361b19ad96872ceb25c224a147c1b585819d24ca65237f0ae9c9df4d6d", "Model._build_external_replay_readers": "62d5d2c5bd473f779ddb81644162279e0a3ca329105b42636220a862391dc771", "Model._runtime_regimes_for_shape": "f524f330e24be0042a19fdd3e877959c5361d2932003854910c23365f90d4902", @@ -1669,7 +1669,7 @@ }, ), BACKWARD_INDUCTION_SOURCE: ( - "9b6f193aadf588d500a3671e841c3b81841787d4cd53f30662df438ff81aa517", + "85d15437c19e8c65def723f3af8b77fa78eb9d47558fcee8f34c73f2fba889cf", { "_period_transfer_scratch_reservations": "e614b686048f4131f4b612386ca89ed8cec5f786fc64ac82f7ba87866e54fc76", "_continuous_value_replica_required": "4f22692255b3746899ee7b2849776ea8967090af80d68d46272cd0b9a5bc771b", @@ -1682,7 +1682,7 @@ "_prepare_abstract_program": "e5ce732766b8e62aeddd6e2047957c918876fb5d895bdc0190601e9566e6e34b", "_build_continuation_templates": "458ac8482471a3d565a61dba63830e30a1fe2271a8e40128fbb1e7da2b4cb46a", "_iter_edge_topologies": "ba1a385a7779fb841a865a76bbb185c30653f27a7f66c2d888e147dcddcd4725", - "_build_base_state_action_spaces": "7a0648369e6ca73456ba099ed2cde0bffd294728dfaf482a7ea07b477eea792d", + "_build_base_state_action_spaces": "7a2e4265ea06fd61755a3cdca996e35688d46229f691a5e4a49334c8abfa4ff5", "_resolve_output_layouts_and_lowering_keys": "9a7ca112027ab83e686d6bdb7c36305f3268b676dad01d5fc4cdc0caa365cd0e", "_build_structural_blueprint": "8b84ad84b9d93e2f7e846eb33fbe105de31d6a5d5c34dab94911e6453635f7d7", "_bind_structural_blueprint": "71990a1c2417e81464e44045b10cad6d6e61b5da2db5775aedcfcbbfec3cbee0", @@ -2453,7 +2453,7 @@ }, ), PROCESSING_SOURCE: ( - "98d18479682fefdf9ebdb63b47923b9805e25d3443e2b1422f6571a644cddbbe", + "7a6e7738d47fd579f2cdfdeffa21a82d0696862b9a872d66c9131852bdca7029", { "_build_per_subject_decisions_per_period": "b04fb50baadb61f7a5301b2ec1af99a6c53e10355574f1bddf3da94f606ac67a", "process_regimes": "288b4375dff6c1f924dc3e646f38e3c4471887ce440c6b99f9528bf26129c67f", @@ -2464,8 +2464,8 @@ "_prepare_scalar_egm_query_models": "14738d0d901df243cadefb2ce4b5f38570d719c23570785619050257a7aec0bb", "_fail_if_a_declaration_moved_more_than_the_kernels": "77f7d0d6adebd110f143c0156321536d67434715df60d1c7375fbfc3d0ac269e", "_fail_if_a_continuation_demand_is_unmet": "3aba143cb3f660bb0d07a6f8c524527a4e58bbe22a96aef28ca45f0f3317fba1", - "_process_regime_core": "d91fc301f7a359e6f99c42485551d5c71c85537002122c6b269f5d07926d3f4d", - "_prepare_dcegm_query_models": "9dbd436a6be2af9365412d2c594afbea4335103f3f2a8234c9f521605d5f85fe", + "_process_regime_core": "2087f8736fbe5864801cb9e26fdbb6780f4774d9e7cad17fa67765ef6734956e", + "_prepare_dcegm_query_models": "3340d19e12acf972ed363ce9ec1953dff6bd5a7752296b902ba9e0c796640f63", "_canonical_constraint_routing_inputs": "b014cb91c503eb021cd7aee8b6ead91fa54a86b0ffc1b8fde29e80978b53327e", "_prepare_nbegm_query_models": "1b73177b06799eed293c42985ef536c39282074a07075aa4dd8508f25c743ac4", "_nbegm_evaluated_query_predicates": "4a734bc9d0020b846a7ed8e56c318331ec1e414191354ee55194c39d0f5e6b98", @@ -2473,7 +2473,7 @@ "_nbegm_query_function_pools": "3d5549c36db6f139068d67a76c0234a3055f84989391576fe5615658ba39ce1b", "_nbegm_query_row_state_names": "f398c3a4c47b01a2fe7811f0c76f4ed01618129e38e7e86d703743fa24dea2ca", "_solver_with_query_authority": "0eb2703b05650da0b98779c17f9401b9d948debeed46d27068215ba1fe1a6385", - "_build_simulation_phase": "4cd45c51443dd57676b3946d51eb96e25558185ae5381f06774e863cb1301ca2", + "_build_simulation_phase": "1154866e5f8255eb830114c6bbefb7221d5eecf6a477fa329a69f0b725033cab", }, ), SIMULATION_PROGRAMS_SOURCE: ( @@ -2658,7 +2658,7 @@ }, ), "src/_lcm/regime_building/Q_and_F.py": ( - "96e32d2cf7bf6d1bd0ac2e901cb5b409bd6ed109317d8bffca4d5cff1f954f21", + "782e6dc485523c2378f0307fd118851ffed73590824105322c25dbcce50fdec2", { "runtime_bound_specs": "84f9e94e2f2fa9cf0f27f8900a244cf80b64681bf23b2973e5c08875c76155a0", "BoundedQAndF.__post_init__": "ba409022a0b51498849a82498a8c53e3cd74adbab150de8880eaebdb81b58d75", @@ -2892,7 +2892,7 @@ }, ), "src/_lcm/probability.py": ( - "bb125dcad684e572c3ffb7ea7fd5ca19b7225662cd5fdebe0c070a71cacdd0dd", + "4f241cf8154fe7252b6b7d482df2746dded00607c249e1f17dddd34f73b7bcb0", { "_encoded": "58d2dd01903a637adc4af5d18dcf3767eae9b16f685a0652e24c156164511bdd", "_exponent_bias": "c3a992302c901ac4ff4bb7c25cb2dc54965e8d08c9b8dd18fe98832431c469fe", diff --git a/tests/candidate_certificate/sources.json b/tests/candidate_certificate/sources.json index 63ae04726..ce528d29e 100644 --- a/tests/candidate_certificate/sources.json +++ b/tests/candidate_certificate/sources.json @@ -14,7 +14,7 @@ }, "generation_rule": "unique sorted literal _parse() call arguments in the certificate AST", "schema_version": "2", - "source_inventory_sha256": "0a068b7e93901f5b0d69a3c157bd11fa3ba46d4a3f7b25df6e02a9202c9812ef", + "source_inventory_sha256": "86abc5d22d2e13093b3f675baa4f9c0dc431e0228c5ccf0a215ae38ce67be48c", "sources": [ { "path": "src/_lcm/constraints/bounds.py", @@ -294,7 +294,7 @@ }, { "path": "src/_lcm/probability.py", - "sha256": "60ccd04b143c714360388fcce2730804a4ca729ea4db82e4a0100732e155e53f" + "sha256": "6231a021bcf78740ea167995aa8cff0009de2f973c09347d244874a1d9d5cd77" }, { "path": "src/_lcm/processes/__init__.py", @@ -302,11 +302,11 @@ }, { "path": "src/_lcm/processes/ar1.py", - "sha256": "7f86f58de1364c68a1f512ae86f653d4abd2259b5dd0dc25553ba226a3f44ddf" + "sha256": "a7f766eacf08a2f907942a0a7383950ec2e166e19007504a78e2133d6a0dbdb2" }, { "path": "src/_lcm/processes/base.py", - "sha256": "3e9c95ca2a4de89a90d954ec227ddbb20c8a12f57e7140c8056817ebf93dfcd8" + "sha256": "c6b25978ef4fdbf16212b38e5f3f4cb4a776aa5792097419e0af0a39ef2460fe" }, { "path": "src/_lcm/processes/grid_resolution.py", @@ -318,7 +318,7 @@ }, { "path": "src/_lcm/regime_building/Q_and_F.py", - "sha256": "242811e5f010d1f72e29cf0768c845579261bb50b699e6dcd9972b77b9e3d1f1" + "sha256": "2a275560230e4248b30b39393bb77f58fc3cbd098ac8d20f4b134b64217d6386" }, { "path": "src/_lcm/regime_building/age_normalization.py", @@ -342,11 +342,11 @@ }, { "path": "src/_lcm/regime_building/processing.py", - "sha256": "8afa2618cb5b01f70a5907fd007e960990500b1ca7ccc0d25c814dc06a637383" + "sha256": "8d5e2e23ec8d84426bfc1c1c2664d1612409349c7d8507e3936fb1cf3fdd5d80" }, { "path": "src/_lcm/regime_building/zero_safe.py", - "sha256": "c1c748c17eabf1f3439bf4309a1cf79ed3a6dc85c8532a3a4b3dcb5559acf638" + "sha256": "f1f8a856013f15d09dbb2da93881b587634f0bb429876dda83e96b7af0e2dd83" }, { "path": "src/_lcm/shock_overrides.py", @@ -414,7 +414,7 @@ }, { "path": "src/_lcm/simulation/entry_allocations.py", - "sha256": "c3a68cbf4c54a0f5ae15204e0d00070f9b991a2efae998f9f4e69c3dff97fa1c" + "sha256": "1989ff5ac2f0e59150ae806cfc31af7c731f792f2958bf6ee83045c6e2448918" }, { "path": "src/_lcm/simulation/entry_inputs.py", @@ -546,7 +546,7 @@ }, { "path": "src/_lcm/solution/backward_induction.py", - "sha256": "6f57d51a0a40be63392c0d4e17fd1fe9c1d5bb96a83ef23ef859d17248e0689a" + "sha256": "fdbe468b45f89a2e2436cbedd63705d9a0e26f08bfcbe85a2a91a15f2b6b5ea7" }, { "path": "src/_lcm/solution/collective_action_reduction.py", @@ -686,7 +686,7 @@ }, { "path": "src/_lcm/zero_safe.py", - "sha256": "8d54492b73e33461f750420eef45ba8c8281c467acd0c77ba2eb90281793c8d3" + "sha256": "b8ca10a6190844e1b032f4af669d85b311e5aabcc73e6e67f5e53bc5841ae84e" }, { "path": "src/lcm/_solver_api/authority.py", @@ -710,7 +710,7 @@ }, { "path": "src/lcm/model.py", - "sha256": "c224a50b35e4b50e8403a8c8bf18968d16923c6ba6331f726e65bd29e24b4919" + "sha256": "bf00b963e6374ab94b5e46da0ff6ff2588e072ac0df05bc6b8d48c98ccea84fb" }, { "path": "src/lcm/regime.py", diff --git a/tests/data/fingerprints_slice4_base.json b/tests/data/fingerprints_slice4_base.json index 5aa059d33..b8095c683 100644 --- a/tests/data/fingerprints_slice4_base.json +++ b/tests/data/fingerprints_slice4_base.json @@ -2,7 +2,7 @@ "32": { "dissolution": "ccd6ab99da888cca91936af61d6fc99fc10230c8da1bcfd5eb36841e44cea3ca", "ds_app2_housing": "5672de3aed2796231c44278d847d117cba4b521fa9422ec34f478734fc5718fb", - "multi_regime_normal": "ebf593d9dd3d6a5d60327ce63b1d38a1b07e6bdfe66e1c285e4f000d016a5153", + "multi_regime_normal": "a92f9b2941d1dee6bb995ec669bbdead634a495f3aa21c7ce6d2ae74e495acdf", "n_nbegm_toy": "cdc5d8d365d187ef51ee3222e04d714d226bd313d3b8946cbf0a5c638b086e6b", "nbegm_ride_along_toy": "1c675ab653dac292e1bdf4f2d6cd81a03eee6e01578390b0b45d73a20d8e0384", "nbegm_stochastic_node_toy": "eb68c835b116991850d8e9bd8e22d4864a08c8a60afb9cc18e397cabd7d235e9", @@ -11,7 +11,7 @@ "64": { "dissolution": "32865b8f39ef37bdaacc57cbd7ddb7fb6ed1e37677dfe097daef7838cdd09c1a", "ds_app2_housing": "8c335012f455ce6ee6bfae521f8f803fec158a6e63a69563e9152f7f8ba19c26", - "multi_regime_normal": "582f6488b1b4394787f5637e7cf92f191c54f0dae9cff167a33360c1c15baeeb", + "multi_regime_normal": "19bed4ca7644aa51a139538ee360b17a9e7fe225a682b108e4379b452a23097e", "n_nbegm_toy": "db16166d24bc36ed2881abbb646b8a064b746d1f38ef4254e9058c81a2ab9e0e", "nbegm_ride_along_toy": "9b061694bb1f0ab394fb6a5a2551164e6f33404687c51b159fe025b4d84329f9", "nbegm_stochastic_node_toy": "9ba90979230852c0c5b39ed986bf64bd414968c977562c83797d3f95158aac94", diff --git a/tests/data/processes/random-v1/provenance.json b/tests/data/processes/random-v1/provenance.json index ef8a1733e..7cb62e741 100644 --- a/tests/data/processes/random-v1/provenance.json +++ b/tests/data/processes/random-v1/provenance.json @@ -1,386 +1,424 @@ { "address_version": "pylcm.random.v1", - "source_commit": "afd67bc97885445aebc9ddb46bd3c35b04c29677", - "source_diff_sha256": "5301e83efc3240ea1c73f74abf955506bfd1564da6581665555492622cf425a6", + "source_commit": "6bb9f211ec2cef715c3f1422fb7090a887ecb078", + "source_diff_sha256": "568db2e52d90ab03dba3b9f546114d7a608cb08f03a548e233bfc4fb6b424190", "source_files": { "src/_lcm/__init__.py": "ebdeb479fe3bd233cdbc5d0246c0e7d5be9122fb96dad4bbc7f80b28cd025a44", "src/_lcm/additive_shock_transition.py": "d3a48403fe752458034241eb17af3802293e0e28fe4c4970a2aa67de0c9d49a0", "src/_lcm/ages.py": "a05d4e48724ff0c67758acfed318699a817610bb31d1fb63e94a0a9c438d2613", "src/_lcm/axis_boundaries.py": "7ed1270affe770e277a1586fc8001afc524904ac434990c03af21d61bcc82a88", - "src/_lcm/beartype_conf.py": "7fed7fe977ad944063c495e2e1236feef008db1a661ba79504659f5b5d502373", - "src/_lcm/certainty_equivalent.py": "191fa76ceea8b01fa5d6674b9b99a39729673e2837b97b2e13b3b6c5cc319eca", + "src/_lcm/beartype_conf.py": "54c7f354fca66ed26187b1221ed73530ed1ff3c732df37efdb46f428111d9435", + "src/_lcm/certainty_equivalent.py": "f30fba168a0588cb92d5b63daa123605e4c0b9d2c3f70870a20cccca99decac0", "src/_lcm/coarse_transition.py": "40ed66d5e590e55f278e2e48175d6ff278f82722856a71655742100f56a2024d", "src/_lcm/config.py": "d50c08f25a276fff560c84d22ab04d3e3a6a00008e2e7d1c3f18f4886d208865", "src/_lcm/constraints/__init__.py": "7dcd0c0a4ef93c8ced8ad1f4cfcf842322dcaf3a4b4fc0a74572fd0d02f0e6c2", "src/_lcm/constraints/bounds.py": "e2d2d2ae850a3c4c91f7b094a6f603dbd77aa9f6e202d17ec4ab0af512fd1c35", "src/_lcm/constraints/dispositions.py": "fc78ac9aeb47aa67fe0ac393938acbafd819e6fd03be8cf4dba7f84212635c86", - "src/_lcm/constraints/dynamic_bound.py": "44eab93412fd37fab34514cf6eae73c3c9479111b5a4ec57da474ab2055562fb", + "src/_lcm/constraints/dynamic_bound.py": "8f44c31d42f69d8316e78cadba7b19230a69893d7f6cb0bc2daa72f0a0d684f5", "src/_lcm/constraints/ir.py": "32c9d157999045a134c196e0e1e58ab2a7c4ad105bc182995ce86ab9c6621ed6", "src/_lcm/constraints/materialize.py": "70107d75e2f3a89ef3f4b5863657b464adae5b2f8884d9ae11dd45b2fb22776a", "src/_lcm/constraints/processed.py": "55f0e24bed63303ed9338798a876b6ad4a4b287b174d9513c2065fede183d495", "src/_lcm/constraints/routes.py": "9877997b89a6561361bb82ee0ffd652733be7ffd6478065bd3121ace032a19ed", - "src/_lcm/continuation.py": "20648e28199e759602ad1d4e82502947a2402a1050b633a76c05e238a6ff502d", + "src/_lcm/continuation.py": "b9793cbca0f776bebd5c0efbfd9a835fbae1a090e6ad0b12c9f27fa01c1f45a7", + "src/_lcm/current_iid.py": "e518ccdf975b2c1d82082157ce964b2d1a5ecf69360851cba9d86449b2d17507", + "src/_lcm/current_iid_node_adapter.py": "55ba10fde950d705e93eafc649ad14d8b7b9fb9f4de1a59908f7d8196abdfa23", "src/_lcm/docs/__init__.py": "4f5c682e09bfe1b759895dbd00538abec1ac8b63dc391a113be74026afad3e84", "src/_lcm/docs/render_solver_tables.py": "c0b55fd76b72e9f8509a88e1b5025c7d812c69f63098b35cafff3df424553e66", - "src/_lcm/dtypes.py": "1d38a54667166599fd692f8c58b37741f355753138d234b650c54384321bcbb2", + "src/_lcm/dtypes.py": "1be61ef17ecb00309aed5a9dec4d4e8d11b9a03cfef8d7e6a812691835e87ec6", "src/_lcm/egm/__init__.py": "392d15eead2ecfd0ade2dc83d48717dcc5346ac4e7b78ddbb955f42dd49ddbdc", "src/_lcm/egm/adaptive_nbegm_producer.py": "6e981492ef9f803816a1b6e579818e02c9754395b0dac2a19355c0361b115574", - "src/_lcm/egm/asset_row.py": "d7389b5048707dd9657638c790f9afbd8feb27893bcfd2bd6659da66199b069c", + "src/_lcm/egm/asset_row.py": "a1754248507153a646157269741645c745b956c916821d592d009e429d97c8fe", "src/_lcm/egm/branch_aggregation.py": "a3c5caef0f16bb9afb1f998048fc08295766f8857c9897db7c57f0f7e2a14b32", "src/_lcm/egm/budget.py": "1c8fb0cbc8f9156950bea34c71c9ccce2c58ac17ec6b9f1221f8c8966f1031d2", - "src/_lcm/egm/carry.py": "5245ca56a6cdf6ce53695ff6d3cb42ce0ac5d07dbf1ff65297cff2e324f96c34", + "src/_lcm/egm/carry.py": "17c85a9146e68a8b57487754bcb89b879e62bcd391699d82ac4116ec7e4c4691", "src/_lcm/egm/case_conditions.py": "78e2fc3a0467b5ecdd0aeeb3839bc929cae3cfef6863cb7edcdff74a92b5104d", + "src/_lcm/egm/ce_scaled_linear.py": "00afe3a76f15991e752c18a76878e34b4bc5d6799b353eeda6d2ee68a9ceaae7", "src/_lcm/egm/comparison_arithmetic.py": "a7e65eba79b64493fb4ecf363b6af6b4068ec1c2bd5d4a26009ba63eff7728e5", - "src/_lcm/egm/continuation.py": "5a25a1183c81ef4c3e8e3c4aaebc6e4797ce04c9c55b88edefa7de7fc7946f9f", + "src/_lcm/egm/continuation.py": "ecea4e3e177c92abd735e9365edf0578b2dd4795fadfdca5286147123595d5f0", "src/_lcm/egm/continuation_grids.py": "a6bf15509066713b08d6b5a10330c2d8a3be0d260a175d8d2a708b2d5c069ce7", + "src/_lcm/egm/current_iid_power_math.py": "6fbfc653b75708bb6735cacb7871223a8d61e837cda91509fb81059d412f9cde", + "src/_lcm/egm/current_iid_power_mean.py": "fa6242460d4b40eb7461116b23bd84d138b86ee196a7b652ae60a78a3437d341", "src/_lcm/egm/dcegm_query.py": "8d21916983c632df46ad96c57726cac6137322db985b2e0b9a9f7cb41b8ba9bb", "src/_lcm/egm/dcegm_query_model.py": "92788d75814f82e8acea2a9174a210997e04f68ec8253957836c8b327a03542a", "src/_lcm/egm/declared_law.py": "635329b1a16ebe7b80ae57acfcc3fa3fd2c1b65a7b6778d1f72dc985f47e0e69", "src/_lcm/egm/euler.py": "a5e95cde939adcefdf3d8310f6617df4f203ae3479bc318cd92ac51c020d0f55", "src/_lcm/egm/euler_errors.py": "d2155046225c16310592c2def6a4b40acad0601d18ea6e41eee525d6e4c30cea", - "src/_lcm/egm/ez_kernel.py": "568caa5183613de012ae4c7b433b5bf058d5594ef3d5263963c25f2b7302c269", - "src/_lcm/egm/finite_nbegm_query.py": "c9b62c4ab9c8f72f491c6afb3e5334731ab8b78b95ab4c48b606cdbc44dce665", - "src/_lcm/egm/finite_negm_query.py": "deb8afbaba19be4c6263b1183958e6b0cacd7857032d7d14b8139ef4f362fe84", + "src/_lcm/egm/ez_kernel.py": "aef102b6dbc73efae7e103e34597948e8e354f3195a33383973bfbd0da112a72", + "src/_lcm/egm/ez_power_mean.py": "6f108f1ad56b4cd119dce43b8e71700e357b3202f6a27826e629cf6506f40d4b", + "src/_lcm/egm/finite_nbegm_query.py": "923182a7957e7f29e579952ceca9f9fce9129d785f9ca17c4cb4a345b0681699", + "src/_lcm/egm/finite_negm_query.py": "7ce90cf75e272da35fbe28608c88b2cbd1a93201e5c1b785b480b75f1e311289", "src/_lcm/egm/framed_arithmetic.py": "f4b1fa68cc765fc1450222f7370256306d22b92a6488b40c3575e98f44e43877", - "src/_lcm/egm/interp.py": "4eee527815c5a2fdec690a349f5bf303a13c667b3142036f07dbda3e0ba92765", + "src/_lcm/egm/interp.py": "6dcb3eba26a508447e6f6c958dfc257dfd95be3aef1bd6dc03e2b279ffa22129", "src/_lcm/egm/kernel_scope.py": "6a4bc62b7b13b3e6411e93eb81d3c6cf15d86728965815008dfcc37febc5200c", "src/_lcm/egm/nbegm.py": "b8fa475eeb9d9e6ef6b85fabf9feddbdaeee99a3d30a68766727f6a4820bcad6", "src/_lcm/egm/nbegm_breakpoints.py": "6c0577b9aee4f102e2b5b21c0da8a5fc17c33cede069f1e9994831cbe2555bd1", "src/_lcm/egm/nbegm_constraint_boundaries.py": "c364c0ecd682a5be1cd52fd74efad6135f1fa04b709b1ea0087ec925e7f55c9d", "src/_lcm/egm/nbegm_crra.py": "d0636fe39ead7cd2cde5ccb1d5ba34ddf0f929871def311d50747104757be278", + "src/_lcm/egm/nbegm_probe_stages.py": "f6e3a7161e08da83153643d894292bfced6f3ce60f248dcfce3f3792052c3fd4", "src/_lcm/egm/nbegm_query.py": "594f8e44f7a3ba541dfa35fab59a6e9629e2dee31dd63dff57b2ee07afc32702", "src/_lcm/egm/nbegm_query_model.py": "d57f368e399523c823c3caa2082ae06cdec74a5c5b0da20d8a6a88abdf555ddd", + "src/_lcm/egm/nbegm_resources.py": "0636ee49e6ae58c58ae2f6b4d11f32d27a22b55b9b37b936e473f757401efe22", "src/_lcm/egm/nbegm_routes.py": "53baf390ad6999c4443848a8b2e96caa395ff9ec7d611c2a016f9aaa02666c43", "src/_lcm/egm/nbegm_segments.py": "658a74ca40e3da1c025c3d03e0f8bf695feb45953113521a4700f2c1d1890505", - "src/_lcm/egm/nbegm_step.py": "394096232ad23d1abad577da07dd2e839001a541a5683aeec0daa4cf1b52f76a", + "src/_lcm/egm/nbegm_step.py": "2282aa8fb0a07abcc7aac5c7a19ffc22df6bf72105eee99390d37c4996fc24cc", "src/_lcm/egm/nbegm_validation.py": "9d3748b4930a872a8a3016e0e49a23a8f22c35213dcc574c485a8c7997d4daf0", - "src/_lcm/egm/negm_validation.py": "a857bb699760993fcd380456b09f950008cd11ca1ec0346d50db2f2b51a44f8b", + "src/_lcm/egm/negm_validation.py": "2703757df73749b73e0e5503ca1af228e4722050bdeb773491c7aea87ef1d738", "src/_lcm/egm/nested_floor.py": "8983b037774946af7a90aa106268659a69963e2d8f5dd4b55c6f5532dd2dbb72", "src/_lcm/egm/nested_published_policy.py": "971e4de8d8c8cfb2a48d2d6f105b988139a607748314ad30f0ea6d5c9d2c5b6b", - "src/_lcm/egm/nnbegm_validation.py": "9b61ad6cd176b0b2fe00aca45c39e06186ae1b3ce55c017ccf9d92fe531c8ac0", + "src/_lcm/egm/nnbegm_validation.py": "81b847ca7c0bb62ee0bccb5b81dc83d2f120b3b4867eb60314286a7eaa477dd4", "src/_lcm/egm/numeric_inverse.py": "57b4d9983131c5b4ce102c96372c21517b7d8932e0e5d576a4e95e585a7597ea", "src/_lcm/egm/one_asset_egm_step.py": "c63df7e9a681def81e2fcf6b578f3f817af7d402b819e674f441989abce403ff", "src/_lcm/egm/outer_affine_structure.py": "febdd2ab612dead7007a4440b9217e3492cad0cc6906b5dea6ab89e268a05944", "src/_lcm/egm/outer_candidates.py": "7a30d25c51c0254d2fb20a86d30b1865854f8134954bce5bb7a8c72eac218f2f", "src/_lcm/egm/outer_carry.py": "eb115cbab6814020a4e49fdc4d9ebd7542d569703fe5e784db383e93126a4003", - "src/_lcm/egm/outer_envelope.py": "25dfb63f6271b084bf67cbd941629db79e0229cd51c250477d166eee7cc8db2f", + "src/_lcm/egm/outer_envelope.py": "0c17015f9a980411b047387354f23886cc7aead0e461eec1b87ceca07911b7fe", "src/_lcm/egm/outer_interpolation.py": "fd68eb3baa62055bf4a92a572fbec5e055a08809be044a647a31ff7982fc92a8", "src/_lcm/egm/outer_inversion.py": "110044e7224ed614150e479368313b686465506c4d237fa916ef8cbc28a5560b", - "src/_lcm/egm/outer_refinement.py": "7335546f8df6f1981544cca692d29823f4dc7b7af52d737b7df5c62ac62b8368", + "src/_lcm/egm/outer_refinement.py": "03f1fc3529d3ec003948d515940407118533799f966dc5ca7f4a1ec4329de109", "src/_lcm/egm/outer_replay_capability.py": "4b0204feaead4a4a7bb8ec04c46d1291b08c02543e38153c162d25ddd0bd05a6", "src/_lcm/egm/outer_search.py": "a20f234b45b324a1ba0ee7aa7692530ed0fcfa6001d4047806919d5bc9c1c634", "src/_lcm/egm/preferences.py": "12d41ccb73192a7742267ffaa688fff3fe337ae40ef2373f6fe93541b8effcba", - "src/_lcm/egm/published_policy.py": "469ca23b7e32b14f816f0c4301265334ae1b857d335dc182161ec166afb711b6", - "src/_lcm/egm/query_data.py": "70c56e67d3df83c00868c052c440b9071c4f5a5698f23517f7463d389c6571e5", + "src/_lcm/egm/published_policy.py": "6e0e77a3e47cec4690b9e3d917159c5a2503efd1a6e7239fcc72f74ae0146316", + "src/_lcm/egm/query_data.py": "5ca53117248f9009d4d9b696fdb46a361fa47c5b082757ccc9beb6ccd967bde3", "src/_lcm/egm/regime_introspection.py": "e1268a84eb34d1377c1fdf4672ccca73353190e0a77ebec405b7846fea11bbd0", "src/_lcm/egm/scalar_query.py": "709d16f6377da621eee7292c7eb33c7b2c40f65cf8916d7b80d149f6f87c94d8", - "src/_lcm/egm/step.py": "34fbffddd5e4d263759adc0737b1dded95c6244a2f51a146c78979efd68c314b", - "src/_lcm/egm/step_core.py": "5759435323866f08fa9a85dd65e81ddb3aafc96fad3ef0fdf38793ccdee26d59", + "src/_lcm/egm/step.py": "97f9fa73f3001584eafebb3ac40696702a3faa9752947f91642ae9e1115942cd", + "src/_lcm/egm/step_core.py": "7bc45cc8737af19bdae76b61eae5319e0122d6fe2e15e62cfe8d6a489b941559", "src/_lcm/egm/terminal.py": "6186383e7474df6928a5345a7d69486490ead4445f48be8910e84e10a54d6491", - "src/_lcm/egm/upper_envelope/__init__.py": "79fbbac531b6be0fd6d5b88236f9b56011b8300975bdef9941e24dfd8eea33c3", + "src/_lcm/egm/upper_envelope/__init__.py": "2615b9a364b7ca1c927ca68b752cff17b318268adddbb2c234c145ed59c196d8", "src/_lcm/egm/upper_envelope/_exact_affine/__init__.py": "49b3e25534818e9310d818cce6caf06e0eae240f221a781d19818065669ae4f7", "src/_lcm/egm/upper_envelope/_exact_affine/ffi.py": "54a706f7dea3a91810c66a1810f8cf6a045234173126c73eb3d150c44acbcfa0", "src/_lcm/egm/upper_envelope/_exact_affine/handler_symbols.py": "89c45a477959e574566367b95cb00b0fa5f3f814073fb3dc823e298293c211ef", "src/_lcm/egm/upper_envelope/cell_hull.py": "cfcc6a3de32b559bbee41690d95772d5632a1df1c9c763cd7e32a679a8071763", - "src/_lcm/egm/upper_envelope/certified_sign.py": "50adb090d22ec915f25b63faaf1471d32f229c2c0bf9914ebf7c79fa37c10d15", - "src/_lcm/egm/upper_envelope/double_double.py": "1d38dcb0e720b20944dd03be82740953c5592efcbcae32c014ad27687d221179", - "src/_lcm/egm/upper_envelope/fues.py": "845b77daa0e9d06763421f2d527c55a1ee87576306afc3b92683422702cd9b6f", + "src/_lcm/egm/upper_envelope/certified_sign.py": "cf7d509cb1a1bf26f21f823f3bf1d259ecc16ee1b4f961e86c94bded9630c786", + "src/_lcm/egm/upper_envelope/double_double.py": "da41d969363acbca496f751ae8c4c6995fc4b300521e6fafdaf81d01e51fef15", + "src/_lcm/egm/upper_envelope/fues.py": "b929e2c8b6377b0008a4e38b22dd982cb68e50083f4435facaea1fef5bcb3b22", "src/_lcm/egm/upper_envelope/ltm.py": "7c8300bb699c794fe3249174fe05e57e5ae18c228311e263a473d36401f32ce3", - "src/_lcm/egm/upper_envelope/mss.py": "9c04d5274a15a2081702a4c06e0600f1bb3f869684d142ea0ebc40e68747c7ee", - "src/_lcm/egm/upper_envelope/query.py": "01e245542fabe9f82f239ba69395a561b82a78a2abdfbb4f15ddb6a549f67ba9", + "src/_lcm/egm/upper_envelope/query.py": "c555477ccb82c30b5ef4b037b3bffb7867664963da0304479e16e3726bce4487", "src/_lcm/egm/upper_envelope/rfc.py": "1d2a61a0be5d4515a7a766cb06249680d777805f672959b52d880a42d6856384", - "src/_lcm/egm/upper_envelope/segment_envelope.py": "706b3f3c7c52c5de2b1553e34be7863653aa0cd14d834fd3b68d9533f7c1273c", + "src/_lcm/egm/upper_envelope/segment_envelope.py": "54be1eb40f33f9176a1732fe9a06c08df957034da98aa01cf7984f8ff3525131", "src/_lcm/egm/upper_envelope/topology.py": "352eb1671ca283517b561f4ab436cd7b2a9fcc261ad8ccbb96de0c3a5d560166", - "src/_lcm/egm/validation.py": "5140329b046d7cdb2cd9301603301be634b859dd63bad29eb414d7d450011e63", - "src/_lcm/engine.py": "9c103e2271e6d5d655be37ce4eda10bf02c811915a5b4b2a3eee25cc02f30c18", + "src/_lcm/egm/validation.py": "3b1abed14448e38e25e58516b7b71d6c4e516e13f026b56898bae50ea0bbe269", + "src/_lcm/egm/validation_materialization.py": "30548a89c2a8994956f081b9515cd8553862eaa14f3aa94b194a2cd42f80c391", + "src/_lcm/egm/validation_stages.py": "39c9b10f3e08a33acbc86cc65fcd38327c77d6bb7709505d0723caafbd36687f", + "src/_lcm/engine.py": "9723b0411730e6bea66d1812f9bdab63d720aadb2c3a2adf8b8ad7da19680640", "src/_lcm/execution/__init__.py": "d5c9a099174ce55348e040c211a0ffe3f6a6ced35b8a3f6daa38561fa2404828", "src/_lcm/execution/abstract_program_inputs.py": "1ade513e829c0bd8e053b90ab312e53f7b51a5a4da6ae1000079c5684a8017e4", "src/_lcm/execution/compiler_inputs.py": "c2df405f63a61f7d5201d754c95bcca9fdc213c97c1533025080da80814cda70", "src/_lcm/execution/compiler_memory.py": "3005d69b3ad5e0c3cb3ff2304b9236b7f4339d4d4cd1aa27b55f4a0fd7c8b1f1", - "src/_lcm/execution/core_program.py": "208cc62cf858e2b58d2bee50bfccc3dbb058060db57c193e53825b58d9143778", + "src/_lcm/execution/core_program.py": "7d8197a3d2607a3380be63408ae4cf2b8d8ebbe68b043cc3aff76bf1f5c6b78a", "src/_lcm/execution/donation.py": "49db0bfe3af0f8db766b0f87c93a74203f7e39750ad55e8bd90793822d6d2f64", "src/_lcm/execution/eager_core.py": "d0049c2a38d3b77abc1c4cff1300f20ca034dff37b77edf7183537471d1cdb90", - "src/_lcm/execution/execution_plan.py": "f0eb5f68d91fae2756d86d8155d4ab6421a5f5ea836d5b0fb1e15c4f9e41c5f7", - "src/_lcm/execution/footprint.py": "c597eebdf007776d00481a6c6311a1e0976671cfd44795fba58898f4d3104e62", + "src/_lcm/execution/execution_plan.py": "a02fc9eb9fa8c9da0a96ae5e913f0a0b9921edd1235b1af798cb07775d8f04a9", + "src/_lcm/execution/footprint.py": "229c23faa12723aeb8725c2a1681ee56011b317f31ba75896762876a0a143de0", "src/_lcm/execution/hlo_fusions.py": "2d65a9471b09d65e9ea46430ae6c674ab0ddd5106ccd6df25d50bdb0ea40bff5", "src/_lcm/execution/internal_outputs.py": "e41e5581295b427e22ecb3f533281c030fec77c01cf224d1a844ae6f54fe28e1", "src/_lcm/execution/invariant_blocks.py": "3ab4d33047348e2e318707ed6143dfb418fd5c619f72ab80a6bb686fb20bd2e6", "src/_lcm/execution/liveness.py": "056bda4d48f26768ed8615925ce8ff89665bb8eed94b59d69f02701a95943dff", - "src/_lcm/execution/output_layout.py": "77f0869c217f746ae5f966040b0d1452958e826cc316c877ab8e4024a871064a", + "src/_lcm/execution/output_layout.py": "c7da1256b36b3b6d89200bbae5267936d84e27746ff2c776dced4ea612ec3eb9", "src/_lcm/execution/pending_work.py": "5629a30a65f402a6c4a542dc3287b045e6b823c7f005f4b92cf0ffaac0930ad6", "src/_lcm/execution/placement.py": "fe1b9ac1a3f8503f909b51fc5ef35950a0ee37dbf1f7a32b4937c6a17d2cb982", "src/_lcm/execution/reductions.py": "84907721eea95ae7c0825831b60107b3539cf86bc9c0cf487a1dac19138520f6", "src/_lcm/execution/runtime_sharding.py": "13f6b68846532c6631f27db1c84b47f6c866a992e037dfd8e40c791c16f50f90", - "src/_lcm/execution/scheduler.py": "8910d9a15e1f1186c48f41aa7f869c4b2f9b0b719430683647f3196e836888e1", - "src/_lcm/execution/value_transfer.py": "c3b8b9df21ea6ebb6d029becdafd4da8905f1a3699d2a1ff5d206af218d097f6", + "src/_lcm/execution/scheduler.py": "772152206f9e9b8361f276e995123ba1b6109e9a476a455aa322e9c6503197ec", + "src/_lcm/execution/value_transfer.py": "70da0e8d7f9ad1f29a1fec7deb4d0fe014bfd2b00b1e332b0e6b66c912a21d2a", "src/_lcm/execution/value_views.py": "dad9163615245d0cc063c6cf196ee5715abdbcbffcf7c0cdce725b4af52e38a0", - "src/_lcm/execution/workspace_planning.py": "c5cb4ef56e436e5620ef16575fb6f2a92a6c5a5162e3ef005acb855ce259d493", - "src/_lcm/gated_edge.py": "d7ba827f3338e239c1421b8c4bce5b4c8bddfa96c27d7b644e6958fcd96cccea", + "src/_lcm/execution/workspace_planning.py": "43fddf0c606fa3dbd64a733b77226f5edb2301aa1ca70b683792058b2dc66e62", + "src/_lcm/exit_queries.py": "c2722be7f1f84b1c53d3854a23546d4fc40f6497149b32f399d80c9b976da3b4", + "src/_lcm/exits.py": "06b6d9d08bf8cd064009ce8fa7e628db8bf5e4fc93b1c30d717b94c8fb072dc9", + "src/_lcm/gated_edge.py": "adfb4daf7089f10c4704d805370ac143b8970cdc5ecda9717a5484641b657580", "src/_lcm/grids/__init__.py": "3c720bc2240dd1cfd45855ce501f03f8a05abda5de1142b9d00208e517b9ddce", "src/_lcm/grids/base.py": "2d9c7f1a0827f3ca172417a2ee2bf60b15c9ccb3dcedf3a94fb502e2d57538de", "src/_lcm/grids/categorical.py": "f115e008999bdb32321bf12a7390519ee37bf7459b61e6121027d2303cfcc3b9", - "src/_lcm/grids/characteristics.py": "14a16d87d81a706e4aa77a3093cd4ca4c5d53b83d44e4c7d70ef5c54b01628eb", + "src/_lcm/grids/characteristics.py": "d15aa68c65cfdb37d8573d198ec47e14fb42c6e8510b1d8b4ded7fcebe8052f3", "src/_lcm/grids/conditional_action.py": "0614766a2bc7622808e4a7466d5f77dd368ed5465c863947ff163182c55e10d4", "src/_lcm/grids/continuous.py": "37eeadb95ca49855248da90a99fd5b5424f2acc28c9bf1535d228bfcf0b112f5", "src/_lcm/grids/coordinates.py": "9dd0cf9e3c702023cd3cfa40a3164bf399ea295c57349223b8ab617c7f3533d5", - "src/_lcm/grids/discrete.py": "67430fdd7be09d897878420b474e0ddd50e2137a2d9cd7beb43dd157cc7cbb59", + "src/_lcm/grids/discrete.py": "0d729b4544bc578cb0a95dca01b01e8c202fa3dea2e84984b5c7b497c500f144", + "src/_lcm/grids/materialization.py": "d2574783c9e7b39bcaa642bb12ddc8db1d285873ad57fd6625a6b01eeba2a2db", "src/_lcm/grids/piecewise.py": "88dea9f6573e8b88db1a4f7a28f77b80eeb7a06bc29e70d4314be76237a1bc9f", "src/_lcm/identity_transition.py": "5f2460c78e7b45d0f479691af5dae6f22dccb3b81b716a85be14e46c9294c323", "src/_lcm/logsum.py": "e12061dd4f0f0176324182a2eb875cb6ebe4b97174091c597d46a622df93ff1b", - "src/_lcm/model_graph.py": "d6fe3873e97c62dee2ea01d1a3121aa381b03fb5327b3c5c54ba24a184dd8b19", - "src/_lcm/model_processing.py": "a161bc1d7f07906e2ce3d551d57f586d0c710fbbc9b95af7f7a3edb79be60c8a", + "src/_lcm/materialization.py": "6a78a2f375745f63c3fd9db61b2b17b9c8256084fa647ed99fc227fd186e386b", + "src/_lcm/model_graph.py": "f2c0f7ac84962003e85f7930bd35c42a9d525acbb189a302cdfdad517b116f71", + "src/_lcm/model_processing.py": "9c1c2dd039a3740e2a295eb34207ec933bdf901e9f6248a913d564420b3f0119", "src/_lcm/off_grid.py": "af8f87bb9510a6a7017df99b0a5ed7d04a19f8e24675d0ddbad7485cf67e9010", "src/_lcm/optimization/__init__.py": "208a86255bc6cb1dfe903499403de5dae8a06b609e59d3a5897425d3e1e885c7", - "src/_lcm/optimization/golden_section.py": "a94984361b828a2112ed3907b589ab421788201d8b6af42e1ea8fc6c70a043db", + "src/_lcm/optimization/golden_section.py": "9e76572097e0281e76e59c0b7b430929cc9147754354780a6321f500bcd53f85", "src/_lcm/optimization/implicit_outer_derivative.py": "60999a9ccc30d6eab52eeea3701d5c4af32e84d251fa073127c6994a9065f99e", - "src/_lcm/pandas_utils.py": "c49e3df2c076ad1c74e3c13f881bae3fcdce513777e260d6e57e545f98334769", + "src/_lcm/pandas_utils.py": "f6159fa52ce590f1cccc9cf140da40ca144e5b6bfb72a995d80dd26bb5054055", "src/_lcm/params/__init__.py": "1365aae44f72abe31193a5d7352af837aab80a78f42b68e72186345e55b3f339", - "src/_lcm/params/edges.py": "7a7a0f62ca39c6ddd3f1618486cb371ff9c8fd6c6d2c734c26b7835238d15c1e", - "src/_lcm/params/mapping_leaf.py": "e13da0a6c8c43f6a28625c8f749528bb419892d4d9ea626f1cd97d15edb6ed7e", - "src/_lcm/params/processing.py": "a6640eef75e746b50024d11c51c572d1daa062cf3d5256afe31a97b121a5410d", - "src/_lcm/params/regime_template.py": "7dfea64b17ffdf9e976a799590edb486675b385f1b1698645fa2085984b2d755", - "src/_lcm/params/sequence_leaf.py": "b5ec7ce27c36022ad7640d877847a680e82bfb43d7652c4976caab5c88c39d8e", + "src/_lcm/params/edges.py": "7dce03896be47f916390bf2aca786db64b040e1dbc83f1bfba537d5a02d2027e", + "src/_lcm/params/mapping_leaf.py": "6f68c2715fa16a8eca32fb531e9326510e27799502140cf401eccb787ce7c417", + "src/_lcm/params/processing.py": "cd703789b7defbf24801e2450efc536600351b905d5b2a211c3a634bbc3cb4c9", + "src/_lcm/params/regime_template.py": "d1f9eca748b625c00c33351118682171b65ccd813ffdaf1abd52469be7f16a35", + "src/_lcm/params/sequence_leaf.py": "8671eaabc6bf26521a59480404010c33c440fa55b0214e72bfe5dfa1e32c0d70", "src/_lcm/params/temporal.py": "d86cb0becd49b6e92278d599cf2ffca3071c66ab3eca2d02bc7aba68cbd9ca58", + "src/_lcm/participation_continuation.py": "c286810539477e6150fa2a51241720d3656d243fc510e03f28cd2f4d3918a37c", + "src/_lcm/participation_publication.py": "9b4fe064c2901b407ee616209684f68b2f21d89d1a7786f132cdec340ecbb083", + "src/_lcm/participation_queries.py": "0f0f11cdc2ff9742d5cf2f24f6cd21c874830dba881ef27677788c2047bc5976", "src/_lcm/persistence/__init__.py": "a46309a6f55379307095944cfa2e5465ad6cf3b980ccb15a79a3892384b5fffb", - "src/_lcm/persistence/io.py": "1371f7d3a6587b1b46aed99ab256fa3d2fd1c3434204ef61c67e565cbc661e03", + "src/_lcm/persistence/io.py": "accbf1cae9d2c742ab78745d7e861137bcf3aa2ef239f2877c05cd52e65ce045", "src/_lcm/persistence/period.py": "05b9d8ff49644b246c9bcc7b8a1f4dd80a1ac7a283bfa9bd127421d916eba40a", "src/_lcm/persistence/snapshots.py": "a1f019d89db90b170e98a7338dc8950c732dc6d5fccdd6597239d97cde88f2da", - "src/_lcm/persistence/solution.py": "783325f05360277cf31d45076bc4041a12143fe66469d9eba1c9c69fb36934c7", + "src/_lcm/persistence/solution.py": "91f8be448c576a9c039ec7285f420ed9f3b316101bb2908687e7efcdac7c3040", + "src/_lcm/policy_queries.py": "97bf1b8e133069198a69808c6e51d22763a29bf22fc9b5b0a950580d95bb90fa", "src/_lcm/post_decision_bound.py": "4ff8b8c7b64be2395c821acb5f328765c7a9ac2c5198fd0b2be3960227837f6c", - "src/_lcm/power_mean.py": "1580447a1ca5f6385556438105069bfb15d211bd6da40819b096ad84b2e77cb5", - "src/_lcm/probability.py": "60ccd04b143c714360388fcce2730804a4ca729ea4db82e4a0100732e155e53f", + "src/_lcm/post_decision_shocks.py": "4f3d8ca077a63f6d429d22793176b7a8d62c6d4533eb5835ade7cef794124ccf", + "src/_lcm/power_mean.py": "cc82199d42488b7619917fcfb3d8112c7c76d99253ca8812cb41b2a79b5e3e59", + "src/_lcm/probability.py": "e5f5dc2fa9d123673ecd9e56680cba77285a21d3dfe74611daa64510c6090295", "src/_lcm/processes/__init__.py": "fbce6ed4c889cf4c30f5242c142b4dcf2fa9e186b75cd17be1557f827abff00a", - "src/_lcm/processes/ar1.py": "00720117e85027b487947dc8f28c028a56cb0cc7a3dc4f011f4d7932646af313", - "src/_lcm/processes/base.py": "d58cde6ce85e550fa957eedcce87a65185a8b46015b7ad275fe604fd9383c5ac", + "src/_lcm/processes/ar1.py": "a7f766eacf08a2f907942a0a7383950ec2e166e19007504a78e2133d6a0dbdb2", + "src/_lcm/processes/base.py": "3e9c95ca2a4de89a90d954ec227ddbb20c8a12f57e7140c8056817ebf93dfcd8", "src/_lcm/processes/grid_resolution.py": "c9eb81f9442d7628793d6ad905b2e96e4655e9eb48bf3de32f636541b985269f", - "src/_lcm/processes/iid.py": "6a622d0886aa903d9c5f98ae3e26e0a94eb4d16209a2481074a89fda99b1e308", - "src/_lcm/processes/joint_normal.py": "bd80b6187fccd869ae33fcdc2394204abcab86ab78d6e806be7e18bee731b350", - "src/_lcm/processes/joint_normal_lowering.py": "d61baece4839b02caa6744fe2f27f7ab0687c72132216e79e60125e3c960ee95", + "src/_lcm/processes/iid.py": "0ac786980fdd6346363fbf6cd569d9766727c250c2695b06fae732d079ffe1d2", + "src/_lcm/processes/joint_normal.py": "0f67dad62326554299dc79c51832a044041f10f7b9544f7b02adc39bd015fbe3", + "src/_lcm/processes/joint_normal_lowering.py": "134be360ec57a32457ce55edbbe919a21e48bc55ab5eee3501c09cee1b629375", "src/_lcm/processes/state_conditioned.py": "c1f698ad41090d598edb983525fc62a4200488b77965facffe51a21f5f3ffa1a", + "src/_lcm/query_information.py": "e3b07659235efa757bbe6dab2915813f0476a45c420feb656cfdbacee6ae4199", "src/_lcm/reachability.py": "0c7c467df350b0f0dd918b74cfbef35315c3edc549ef41e2113aec469d6fcb79", - "src/_lcm/regime_building/Q_and_F.py": "cbbe8874b69ec1408d077036f8fce255249f15a291de5c15d43100e8ecef05e8", - "src/_lcm/regime_building/V.py": "bab8666f22d9e532da54f23ec153cc366c88a636ee44509dc1525261eea461f4", + "src/_lcm/regime_building/Q_and_F.py": "3e892a765747c0a8c2d8bacbc2c02df77a9ff01b57924628d855723be8107d16", + "src/_lcm/regime_building/V.py": "c38a8108cbcac4168e4201e6b077f76e0e4feaad90c62b4dbc1c15dc0ba06ffe", "src/_lcm/regime_building/__init__.py": "3cd0b9c59039baacf38733fb6d63f835548e69514be127cb54ccb020519d17ac", - "src/_lcm/regime_building/action_partitioning.py": "36cc1e127eff2b6ec196fe4c192c305706a34fae1fd8284419c825707030b660", - "src/_lcm/regime_building/age_normalization.py": "65601fa2da76f018fb695a76500e2917f518e98407fa6d2dd259a3f3a5bd1df9", + "src/_lcm/regime_building/action_partitioning.py": "99f9be1b5b3e8aa82a644670ec22f56ccfac51ed594fbe93ada10e0d82d2d3e6", + "src/_lcm/regime_building/age_normalization.py": "e1be1cea72f9aa5228a76523477405e8bbee9dde28de08248f14c7e4b8cfc5e8", "src/_lcm/regime_building/age_specialization.py": "bba505db6d6139696365a187a3c5f52ef2b3e39e957d2913ec1085d23e35764d", - "src/_lcm/regime_building/argmax.py": "b508d4e10350de8b54707db238d01c7de6c73b4ca6b0176e0c6c12ec762952dc", - "src/_lcm/regime_building/broadcast.py": "a8c70dc728f9b9651d4c50a7f4b35c702e3cfa7c3a451d6418bd068c831ce57b", + "src/_lcm/regime_building/argmax.py": "9717f9c2ef6a6999e278455e62cf0bfda87fe8b4fdd68b8c113851223437ce18", + "src/_lcm/regime_building/broadcast.py": "13046567156fb496c3986da32f52d27dac58d616b4fd3b7e64c5b7bb5106ba0b", "src/_lcm/regime_building/canonicalize.py": "9dbf850be0d3ce3d106420901fb425f614060d50fb838b84a2514f7fe0f557fa", "src/_lcm/regime_building/collective.py": "4cc0683d493f597684f5801909d297145d8bade0aa752c3e35cf8af2cb55edd9", - "src/_lcm/regime_building/composite_states.py": "cb9164f6c4176e363e8a6d7fb3407d606249e2cb62965cef315d63922ae80978", + "src/_lcm/regime_building/composite_states.py": "747d14a6e0d9d175164aa6c4fae6742d671b962bc6114e24cc59b57055af5384", "src/_lcm/regime_building/conditional_actions.py": "50f4330c5def755737dd330b4a1a1c6da8ff330b040b241f931a863098ed4f9c", - "src/_lcm/regime_building/decoupled.py": "f86bcae9805cf3c72cb3be638d20070dc80b5cd3b94fcfdd2dfe85a0da4757cf", - "src/_lcm/regime_building/diagnostics.py": "d091971142068bb8ae07101dcd7286fdf2f97ec978f5e05e4c4484cbb5934872", - "src/_lcm/regime_building/finalize.py": "b1d98965ffd77c7c387d8f974c001985075e19e6c93b7e8246c2d1ea08b9a18b", + "src/_lcm/regime_building/decoupled.py": "9a78743edda1d4b2cc13b65d42451c0568040cfd8fa4bdbe9f31c3fdba950316", + "src/_lcm/regime_building/diagnostics.py": "cc61e4b516d5d6f5f0b0c1828f0e7ef76d8e9b4c4e1a82640f7d322b9a7fb89b", + "src/_lcm/regime_building/finalize.py": "c1c697f79d2346d409a11340841c068b1a3527f27704bc26fa94a84b38e50a4a", "src/_lcm/regime_building/fixed_components.py": "d798b7628a5c0df8f5fc7d348daf23c494d6c8c5bfa6e700f523e0b086d34441", - "src/_lcm/regime_building/fixed_process_laws.py": "5cd5f1116595d06775dbff8a285c920700d774ed5c0d9b51a55c9fbf76ee87c0", - "src/_lcm/regime_building/fixed_regime_support.py": "fd3b76126e0ba2f0d3d1b76dd07d599f7fe750f01238cfe182f6467b7a02b74f", - "src/_lcm/regime_building/gated_edges.py": "96c1512c77b9a286c9ca95ea9ca50a9508e45f27ba7083340316950e1498e570", - "src/_lcm/regime_building/invariant_blocking.py": "ea8b52dee11b5d53de61b521eadce3f8555179694070cda230ab0dd56fa168d2", + "src/_lcm/regime_building/fixed_process_laws.py": "bc8b4fa146974954bd6e57e7ef2846f67c86b2df1e3ec15d021f307369e30824", + "src/_lcm/regime_building/fixed_regime_support.py": "883797f823fc4ed6135fe0171fd515caf1cdd7101601ddff00968626103c9517", + "src/_lcm/regime_building/gated_edges.py": "62bd27fa83eac3dfc10434dbbe2de2124880ea6bed996425ba895ffd379183e4", + "src/_lcm/regime_building/invariant_blocking.py": "15ad774021616752674e1860773846ce4031dceee64fad69a49544f9c1f86433", "src/_lcm/regime_building/invariant_components.py": "da9dbffe515c89808bc734407eeb5363bc8e9efb87f82411547571f03acbd671", - "src/_lcm/regime_building/max_Q_over_a.py": "ef60bcee2800cfda754523241f57d5d6fa3168f1cd16b27cf64b6a639886ced1", + "src/_lcm/regime_building/lottery_contraction.py": "860712c06f1554c96367f6e1df957be42f443ef028b4133178d8c485de62baec", + "src/_lcm/regime_building/max_Q_over_a.py": "62e5010e5f535ed3731218a5549167d6f5ea332b145d2dcece88d492949fd78c", "src/_lcm/regime_building/ndimage.py": "b2661e125e57a4eaa54751e408882cf6e59661647b1cb52f6e3c65421d01dd1b", - "src/_lcm/regime_building/next_state.py": "82f7fd17599b07c3b9abe227278d99003d772453648f86e51591f0e021e1d365", - "src/_lcm/regime_building/phases.py": "1a362e1c1cae0b0e3c7eabb1d10cd9635092b0d213e462ac9f0e4942f2febed3", - "src/_lcm/regime_building/processing.py": "d1cb8174d58ac0a6855b44365c0e6efd90ae878b768b8758a4289be056b448c0", + "src/_lcm/regime_building/next_state.py": "71f9a99f7f4857b993021a3bf369d70daa62cc98843e976c5d611650a2f6954c", + "src/_lcm/regime_building/phases.py": "8d1fcc0fe25ba5d93c0ff99464a451ca7f8701bd38e96332e81e59df99f25e73", + "src/_lcm/regime_building/processing.py": "9fbfd279585732c44169dfd4966d962df85c8c70d79991e47c3888838f39a7a6", "src/_lcm/regime_building/reachable_states.py": "1663f30c4efc434d26a80a8e668fb3243fa907eabdc4ec5719ad016dbd81b865", - "src/_lcm/regime_building/schedules.py": "cefa5b2cec79d78d920f954bfd2a96768748eb7b987e27e0f5e9a583d71e6934", - "src/_lcm/regime_building/shock_average.py": "7d3f19ce68639b12a6939ac0ec16766be8254a81dab58dbbad189e4622f27cfc", + "src/_lcm/regime_building/schedules.py": "a6d5b3e9a861607d4e77f1b686e54ef817811db3b30dc8dbe474fd433ca6c64e", + "src/_lcm/regime_building/shock_average.py": "1792c93a10cb181c89b1f43d819d81b017c998a34e473ebaf766831f11840377", "src/_lcm/regime_building/stochastic_state_transitions.py": "16389f689ef80d79f2e6907afc65f68640c820c24d37d50885788158e3bba156", "src/_lcm/regime_building/transition_invariants.py": "9ab1f61f7df13d9f6e09d922d87f1e5fc585c1220ac2a976232e3f8a4954a7db", "src/_lcm/regime_building/transition_support.py": "40b09a4e739186e8e0cbbd7b0f249309e198b4183ed5465facc20c3d5411d690", "src/_lcm/regime_building/transitions.py": "d1f0b456ba8b7687ff1bd3548056b2cd7ac048a6be46b51690ae4cef4f7fb22c", - "src/_lcm/regime_building/value_adapter.py": "46c9463c5cfdb6461160b5ade77eb86f32467241f7d44db8377b90a47552698f", + "src/_lcm/regime_building/value_adapter.py": "030fdfaf3842033b43ba4544c9f245c14e44ad24633f352b746100751f0f8e32", "src/_lcm/regime_building/w_dag.py": "62b92363cffbe2da77dd0e836c3dd69e8bc587ba1fbdee4a9af289ffb8b21f0f", - "src/_lcm/regime_building/zero_safe.py": "301fcd3bec1211b60872159fe585e55e9742be62a975dd76b33f6f5cb45971e5", - "src/_lcm/regime_law.py": "cccada21e199b936f66b579b733ab45890a87a1e86c8c5353f8d59ecdf359805", + "src/_lcm/regime_building/zero_safe.py": "cec0ac91ee07ef0b6893114cf61ce779c13c44c0c89bb440a643829f1870902e", + "src/_lcm/regime_law.py": "caedf5b259fe9473392a758c38dddf31f033bb5ec7345645c5418658a85343e6", + "src/_lcm/shock_nodes.py": "7732f75ace256f629441f59efa23243bd4277e01d0f35055be04597e45f20fc2", + "src/_lcm/shock_overrides.py": "89d13b523a6d0270e144ea60077c5e5f7e306a1b9da7878a9a9b565f920f6808", + "src/_lcm/shock_projection.py": "2d3732931830f49911f5c72294eb19d02d74c87107311f445d034a65b7b667ff", + "src/_lcm/shock_quantile.py": "32656493a80a31e26bc20151d06510765f87ff83fb0d8720cec4018f1b1e06ad", + "src/_lcm/shock_registry.py": "0ec75739a5515015bdb7c27e2bb62e350662a6e8d39d61a51b6522f65f6e1b63", "src/_lcm/simulation/__init__.py": "8343981acf2e7748482cefe97e998ba901ccd488e236b77dc3edde80d88b0c94", "src/_lcm/simulation/action_grids.py": "76a059f7cc7d7e7d2a99e0ffd626ddbd76b89724d5e24f3bb10ad86501268309", - "src/_lcm/simulation/additional_targets.py": "3a4d95d5c88c801bb8bb0881a52cd8985e1cc17efdbfbf5474332e46b8d46614", + "src/_lcm/simulation/additional_targets.py": "3769b0eb0dad646767068fd4cf6e73a707115d2ede3ae5e3d9859b82b75d63fd", "src/_lcm/simulation/assembly.py": "7e1a7967d013827a9fe51862d304e686105ae7886b3539122289ef3866f5f94a", - "src/_lcm/simulation/chunk_admission.py": "1bf5fdb05046e9edfd7f93a6e666999b48973fae4c2025320c3b79011f967716", + "src/_lcm/simulation/chunk_admission.py": "8ef493023e0d43b0bb07fbfb9e4d6b5ee91fc1c336033abce9dc8ce707257da7", "src/_lcm/simulation/chunk_inputs.py": "33449e9833e30dbe50f455603916489145b5ec9484639acf0609e8927bca42ed", "src/_lcm/simulation/chunk_offload.py": "4afae1dea7452ecada529d2ffd60026bae24c945fcf9ac8c021445c4ec7e073c", "src/_lcm/simulation/chunk_operations.py": "481b768fc97b134c671c386336a25e9e3e78b631a0a3bc4643d9e74d0ba47e54", "src/_lcm/simulation/chunk_planning.py": "807378c7ac745eb7fc3d42c27020f6b40d10d40da3041dcdb647e7e2d3e0d90a", "src/_lcm/simulation/chunk_profile_cache.py": "d4265db08160034d152e9ff71789312fa4085eee8077ff1e5faec8b25fad3c35", "src/_lcm/simulation/chunk_profile_inventory.py": "85070e5f57210e201be248c1f2deae8068dce674112f13efdb0eb94c1dd7f7b4", - "src/_lcm/simulation/chunk_profiles.py": "88ce35370ccb53d115d33733c625d5300d1f2b518a939181cb51fc8981e3615a", + "src/_lcm/simulation/chunk_profiles.py": "b36d0a0da5b27eeb1f8c3131c97bf12d5d3ac630d89d217a267a893f1225f41a", "src/_lcm/simulation/compile.py": "2c54bd385d0205897bebd42c6b63d55eb0896a04e208786f4e0028b20e81074d", + "src/_lcm/simulation/current_iid.py": "c675e9dffaa205b4049bf4c26438a70005766c368bc69a3dbb1d6e35cb66db99", + "src/_lcm/simulation/current_iid_entry.py": "fa97e4c695d499da2f740dbe37d1d1884ab49028a0bd0766c9d51bdc76ad0e6a", + "src/_lcm/simulation/current_iid_overrides.py": "c5b8d450cdad4980a694df285502b70cf1238762440f1302d664b2e84d964ced", "src/_lcm/simulation/diagnostic_operations.py": "477f39609fff5371d88d941cc5c4a0c9ab9fe3692ad2845a3fc3a6befb633f42", - "src/_lcm/simulation/dissolution_route.py": "87ed2acfade35ce506725e60ba393bf63ada4cb7a303b7de524c5b2b4f06ef0d", - "src/_lcm/simulation/entry_allocations.py": "4e50d79fe971c9d5f0e59fc7b6942868cb09a1223bcde15754019d72efa2d979", - "src/_lcm/simulation/entry_inputs.py": "44f24b2c57d551088ed220b6726c17f0b6a4a0bf37ee56f1f20c29a0560f216f", - "src/_lcm/simulation/forward_program_profiles.py": "a5321421f904540ec5fdcadb96f8f6273bd19d3becdefbfcb423cbcc5da4e93d", - "src/_lcm/simulation/gated_routing.py": "3a1685c78c9d1dd345e4242bc008f2858578725232b85610d12fa08535f82274", - "src/_lcm/simulation/host_operations.py": "31d4b52aabb9c02b21e206a896932ce4bfe183a0edf46af53593afbdeb9359ec", - "src/_lcm/simulation/initial_conditions.py": "7d8181debcef963165e5f50ea9aea9ebc1c2e69ced040cb3486f01fe58181bfc", + "src/_lcm/simulation/dissolution_route.py": "86c5f0cd567f4bcb81e52a7e3e5e699da8ece647a7468e4a71cac10126265622", + "src/_lcm/simulation/eager_stages.py": "d0a52778e4966ecf9bbac4ecaee87f85f49df0aeb4bf7c390f8599bf7d97efa8", + "src/_lcm/simulation/entry_allocations.py": "28ae3aad596122c83038cc4057e4ba71abfab13bb6abf959ea90d160f4240e38", + "src/_lcm/simulation/entry_inputs.py": "4cc1968398b169fe94d7ebde349b58192dabfca4bee93f1d5e98a0d3da0839e7", + "src/_lcm/simulation/exit_profiles.py": "1d521900a2071f84d56a7e6a573013b6e29f2398e7a259634b5a379682333489", + "src/_lcm/simulation/exit_replay.py": "a4a806406b6406467febae6ac0165ed7802986b76fcb4174d50269c2f8d0acdb", + "src/_lcm/simulation/exits.py": "9f763d244e11c9b6a437896d33c2ac73e2c1db13026b4ab50222187c1105bbf1", + "src/_lcm/simulation/forward_program_profiles.py": "d55a408f27578b893246a76522e5374d5fe995c0fbf05e802e609e9930f7ef44", + "src/_lcm/simulation/gated_routing.py": "f12dbe6046cc67839880131e621a98ae94b80a97d9653a1363b82497ee023142", + "src/_lcm/simulation/host_operations.py": "9165cfb70789209277b8cd6f423b3074b36815a58928c2c18401d7521b58ab5b", + "src/_lcm/simulation/initial_conditions.py": "6d1c779d539ec84a0edb13b1926782492fdb5d999da110fde354b9c6fceeb6b4", "src/_lcm/simulation/membership.py": "c0c92de4e55be3e7b814a67761caa75e8affe835e1887359d432341f1d85a18d", - "src/_lcm/simulation/memory.py": "19afb85a7c2d446209cd668aaf90ab50792698f1403e6d2a619a4ed6a49bc874", - "src/_lcm/simulation/operand_placement.py": "7645b400641b5d995e1a2f651dc5d6ccb54df3e16732db64a75765c5a5f31645", - "src/_lcm/simulation/period_inputs.py": "dcdc57a2d7374e2931f71add777e511360aebf44187f2c7becf26be44d1923fe", + "src/_lcm/simulation/memory.py": "95928177916d988acf65aaeebab9118a4f3c3184b956999189014171a804273a", + "src/_lcm/simulation/operand_placement.py": "69c4d3a3574405911eadf22ce698f2d8476038bf2b1ab6450d4bec99cbe79d41", + "src/_lcm/simulation/participation_routing.py": "eee93365f060844845a41a4c4a38e625cd5a69e72be57521c741336282f33c1c", + "src/_lcm/simulation/participation_values.py": "76390ee564569b75653541388cdda2b37f627bb07f2518ff7b23ec23840d5857", + "src/_lcm/simulation/period_inputs.py": "651fb18bec5bbae3e8cfccee2d25ea13979428bd88a51df873b8df2f4eae186e", "src/_lcm/simulation/plan_summary.py": "25d4e90f71e7932e3f05e58bc687220129e107dd861e94f240af8ef86e10376e", - "src/_lcm/simulation/policy_diagnostics.py": "ed41f7f7e0378b0d86e153c53b399bd01350ea24a58a9b80cc88224158a0c0d3", - "src/_lcm/simulation/policy_programs.py": "ec71f5d8637afa3f7309327ebc3baa5a3a80b5725e13e7633f992c5f147f3a81", + "src/_lcm/simulation/policy_programs.py": "2be9ca13d372fede91e4adf0f54ae22f4105aad1f9e28d255eea0c63bc0cf734", "src/_lcm/simulation/population_operations.py": "a9fdd59887462abc4e2f4321730bcfb397f69ba5f44f3db08001288773082ab8", - "src/_lcm/simulation/process_grids.py": "835673768193d0282fb78d8a1223557d6ca087ea0b4bf7b1c58f5e4b903629a0", - "src/_lcm/simulation/program_arguments.py": "c04b3fc05dd31f728a629ff17b9774a97313b65f145216c8eb1dd741e68c5208", - "src/_lcm/simulation/program_types.py": "d6abdc13894b09b44309fb45c571d233bd20cb330101ff8b0ef7a9e4624fc3a7", - "src/_lcm/simulation/programs.py": "519ed76181ac61a8750fa2ef71be3a492e83bfbdc71dcb6c247838319f293ff9", - "src/_lcm/simulation/random.py": "54092637d7965da26670b1f1dca8b04cf780815a349a8a71dbb243d81f5a7c25", - "src/_lcm/simulation/random_address.py": "f8023d109d5f24b9373c2e5c66d00c4d92ff53e4b73d36e8db8f767c309691c4", - "src/_lcm/simulation/replay_inputs.py": "2ee44446e1524d202b474d72a58465e574e8f212b9efaaabb7177da5ded9e054", - "src/_lcm/simulation/residency.py": "269a66f4a0abd46e3bb6b9bd8b9df6c3c73bd5507c2c236edea7d881efe78274", - "src/_lcm/simulation/result_dataframe.py": "6d735b7cb6bb324ad9e8be16cbcdc47aa2fc2b73657c02c23068072bbc58f095", - "src/_lcm/simulation/result_metadata.py": "73e7a346ad752c0addac2455d1255980aef9a57aee0cfd7f223cecb77d07b212", - "src/_lcm/simulation/runtime.py": "b2e308916c1ff657ef06cbd9a5805de868fc28f2d474b9e9f172a341f3fa0fd6", - "src/_lcm/simulation/shock_paths.py": "c44403fd9a37a516856e7c57c834b4bebacdff2b62fa94d5ca0fd8ffe39ba6d6", - "src/_lcm/simulation/simulate.py": "73b80fd36b130fa4e39b4dbd95c7f1d4e844a3313f037fc75823b5b0676799ee", + "src/_lcm/simulation/process_grids.py": "34b15e42a13aa3ab30d352f7b8dc2fef34f656dc5301417795d4ede09539fee7", + "src/_lcm/simulation/program_arguments.py": "c37d2650f9a8cf6ce4b7f6cfeeef9c4b79017d5f491b088b69f57e72f89d9e6f", + "src/_lcm/simulation/program_types.py": "bcb973f9696dc13e15320d8dd6c3bd410e69f8402dccc0def5bc54904e481048", + "src/_lcm/simulation/programs.py": "766e11decc7a84906267e3770a104e3b6be4ef602a88939acfacc098cf7d0fb2", + "src/_lcm/simulation/random.py": "314164a170cf4eb3d4680dd575022c83943998f2c1ec78ba09d1085984d34a5e", + "src/_lcm/simulation/random_address.py": "ffe7406eb2819c4621db6ac9e9a53c58d408c25c4f62e8b8a21f2c5d9866d76e", + "src/_lcm/simulation/replay_inputs.py": "4234adc44743ef852dc788ec8a38f3440849b9f4404e5e15ee6b547da8bc33de", + "src/_lcm/simulation/residency.py": "6e976a72274c36253b015be76a2a42c457886f9b2c21fae2a897f12ad2e052e1", + "src/_lcm/simulation/result_dataframe.py": "4af8073d3412a65c90858dc13a0085a08e6f4765a647e6ec7594eea9960186b5", + "src/_lcm/simulation/result_metadata.py": "ba9ec4f48e7df67b4a57a35cd3e781906d7ef64a35f3bc37238033c1c168df3e", + "src/_lcm/simulation/runtime.py": "c03a33aca9531b78670fba22ecac27ed4c534ce0702cc1907c32d87256a79f41", + "src/_lcm/simulation/shock_paths.py": "1f48ea5f59848049c2ac3c8d4a96c6abe514319ea237ff8f5267c591676a983f", + "src/_lcm/simulation/simulate.py": "12bb1c0c090ee36c7ebda5ee4c62052c5149e75d0598dba35a2cdc127d45c6a8", "src/_lcm/simulation/solution_copies.py": "fbe188d3954a523522624823c769fda4c5831e138d2cb8421fc0f1453946886d", "src/_lcm/simulation/subject_devices.py": "ce0541b054a0455ec7a42ac4237d178f59255fc5820f3e11c751ff80f3725a25", - "src/_lcm/simulation/subject_groups.py": "1d90636dfe47ad358f52838299f18b70f79779fb67334a401532270b7827608f", - "src/_lcm/simulation/subject_parallel.py": "2718be335aa7cf2770cfe63f1e30cff8be8b7a14908e0c50d64756db0b094370", + "src/_lcm/simulation/subject_groups.py": "163578e738d1de0919b734dcffb7b34ebcaa5e969f2c3942b6d6d9c29c3e98d5", + "src/_lcm/simulation/subject_parallel.py": "66d70a81a7ec535d92933bc8841c6bbe7472e227509f88fc6d3bdd00b6c95e76", "src/_lcm/simulation/taste_shock_lookup.py": "843d07baddcdc9ef9374b74ba5801e972ad3f52b2cba64d3927b289572c1a66c", - "src/_lcm/simulation/taste_stream.py": "5b875618ea92b0470d0b7cd160349450e6df124ffec390bc7c6b133e7d484da3", + "src/_lcm/simulation/taste_stream.py": "f6b629ed946bb3e211f890dc20f32741db6497c119ebb3b66adc578f7732352c", "src/_lcm/simulation/time_inputs.py": "363f33a39edf426bbf6d7343720d6413d7424b9c92d04ef270de1af2f9a1e66f", - "src/_lcm/simulation/transitions.py": "3e2c80c07154dbe5f92b7444e1b3e10b5a1b3bcaf1a9ec25397f1e1c1d53b0ed", + "src/_lcm/simulation/transitions.py": "74d8ecfd0726c58d7a33457677079a18f5065b338d29ab14e506bc301456c365", "src/_lcm/simulation/unit_executor.py": "74859e03e21e9861cc7847f49a8cde2301700b656b2556ad0fb47334d6e809c6", "src/_lcm/simulation/value_placement.py": "afd58b343d0385934c3add5552d7926dc3f9ba2700e5a40b26a65a62a75b1e68", "src/_lcm/simulation/value_reads.py": "4ed63570347beab876c3ff87854dae6d84e9e9f2aa8755a261d65897ea0eba32", "src/_lcm/solution/__init__.py": "fd9b6c79f1c4b837da1bbd619b1b5abf4fcafce7c0290d26213137d598e8ab0e", "src/_lcm/solution/action_reduction.py": "26355ac3edf5da80a44b4f9754b71c29e8edffc68b1a7b7ac253b9bfbf749a0f", - "src/_lcm/solution/action_streaming.py": "a2df345ea1a0b8b8f580b0200b77acf8fe7952ef1466f570a0e292bcf346767a", - "src/_lcm/solution/artifacts.py": "3f1272c9c43f438afad0c0e39396bc685d6679408613858b546c749f4a54ad6d", - "src/_lcm/solution/backward_induction.py": "5229b0e46cd9d21b5039a630afe37f9eb2bf68f302b3baa5e556d246e9640efb", - "src/_lcm/solution/block_major.py": "24e8757ffcae0de28882a93649f23dbf7356c570e27d765a80579e8f7f0cde5b", + "src/_lcm/solution/action_streaming.py": "6e0ec0453908057f98b4ebe16cc354e8cf4fe581e0acb4e18f203bb8e8cccdfe", + "src/_lcm/solution/artifacts.py": "e1382ad40fdb081e67e6cd45c3f752021f4fe674955962b42bb7465b25805ebe", + "src/_lcm/solution/backward_induction.py": "d4da7b2c1cfb6d00490972696490a09e6379384222d374b527e80fe10a85133a", + "src/_lcm/solution/block_major.py": "41604ddd6cf4187a8d0b16443de2f1a66bc711c02a8a9baab3a0529e57ae1f1c", "src/_lcm/solution/collective_action_reduction.py": "40a7abd9b738055f00e347e6ac056fe69bf2501ba41f7ec82b40a18bf627c7e0", "src/_lcm/solution/component_fragments.py": "ae90cc58117e8e7109dcc7af2be6954326c5b21cd7f00c69bb1c900ba971d1bf", "src/_lcm/solution/continuation_arguments.py": "2bfffbd49e5a2e267fcfdefadd21cf4249dcc6979a6ff4889098c37a06dcc0e1", - "src/_lcm/solution/continuation_reads.py": "144206aa7175163a4dcb365da8765942a9f2c8a530ea41e102d540fa4dfe057d", + "src/_lcm/solution/continuation_reads.py": "35dfa6999f53742aa6b824578c5105a22c472884daeed0d33d4aaf195200e8e5", "src/_lcm/solution/continuation_target.py": "8e8e1bdf45c0605bc9d8f0f9ecf2a15173b6dfea51ecd13ecf9e4c16927d98ef", - "src/_lcm/solution/contract.py": "e2caab2e0c4f3aacf5ea833875ff9b68aef2e0ec999b43a5894a4bd131233928", + "src/_lcm/solution/contract.py": "ae7dbe52dc596478614d83880f5fdcfd512cc783f34e2c77a40876db1c3f85d8", "src/_lcm/solution/cuda_lowering_identity.py": "6b22781f3dcd8b389a96fd7a6ffdfe6e84f6ec928fa766f7dd66cf8e901d5b52", - "src/_lcm/solution/dcegm.py": "5e12ebcaf9202d45cb6a1916643e522513ee02e36cf79d5f24c3c6e3e394b4ee", - "src/_lcm/solution/diagnostics.py": "ecfb3a3c7f6114cfc7eb8b143150daef6da0014a986cb6cdaf1b346b9d23343e", + "src/_lcm/solution/dcegm.py": "e783727d261f8ef857fa3aa943c99cebe135aeff18d2bffc03d085959970dc73", + "src/_lcm/solution/diagnostics.py": "15aab27db77f3f9f9699697bc32f201a018f43b1a4653f9c3b2caee0e7ae16db", "src/_lcm/solution/egm.py": "c554d6e993da4b3b253ae8235a7fcac56c74a7bdc9c2537e84515d6c39af52bf", - "src/_lcm/solution/feasibility.py": "35a04ee4c4dcdc81886c2ea3c95a429a3ca3f0b8c7aa2066446798e716364b3b", - "src/_lcm/solution/fingerprint.py": "162453f576383a89714c0cbe90a9d132f8e56ee20d927d17f7e0ec8789e8508a", - "src/_lcm/solution/grid_search.py": "44b0a59948d1c3fd3c65af8bc952e4e02f23f6fa2a4f6f95a1eb8b796dcb619c", + "src/_lcm/solution/feasibility.py": "8cb8cb1ec3da487dac2b5eec451aa4ac61d5222f565c91986c6c2ca7baed1402", + "src/_lcm/solution/fingerprint.py": "9ef247e6e2b80129705d7899f0bc5790072aa13ec0a2d5ce882f0aa4d860c133", + "src/_lcm/solution/generation.py": "5f27b48b79f0cddb0d7759d221018fdd7d4f520598277f0cfc609296d37db3ee", + "src/_lcm/solution/grid_search.py": "df4971fa87372ea97a51aeb4ff8d91a11445c9d93c4cc5458411887de8ef9569", + "src/_lcm/solution/host_values.py": "8f51fa42a882c14c0cfff21ae85c24df564a971b8191a9e7b385bf8b154f61d4", "src/_lcm/solution/kernel_attribution.py": "234ee354e9dd7039b26c4b69afc570393ce6f47793eb7663685d842e179d163c", - "src/_lcm/solution/kernel_output.py": "89ec60c1d59ace639e8df466f06c3a2167e9376633bc7e54c7ba050a84362ab3", - "src/_lcm/solution/landing_counts.py": "e8eebe529c899d8e503fb3bc9ab2f1043a19016c381c40f828c140d3e356f6aa", + "src/_lcm/solution/kernel_output.py": "4b814b0aecacb22cc1f5b47d6bb9006f3f0f5eb08dc0eb18f1345fcd4becb770", + "src/_lcm/solution/landing_counts.py": "6c26aa29647db96c0ad3ec0f3fe6a80879904a35842ae027d5f1671b5ec9cbed", "src/_lcm/solution/logsumexp_action_reduction.py": "4799ad9bfbc02ae1e5d5270a18ed81fe682f1004d63ae6cf796ff48ac5699445", - "src/_lcm/solution/lower_candidate.py": "319c96a86dc854196f003ba37931986523d082fcfc88f253418d0c7fbf0e00d8", + "src/_lcm/solution/lower_candidate.py": "432ff96f0349aa482016aeb141acc499232cafcb24cb562ac60d139c397ab2e0", "src/_lcm/solution/lowering_descriptors.py": "37be061ab3dd6a4c11c660602cf6f9d2bafcfdc4489608e36dbda0613330f910", - "src/_lcm/solution/model_authority.py": "d6ca19e5d2f00b959116ab78cb7211bd3f8359d71402461b6f74dc66ec344a66", + "src/_lcm/solution/model_authority.py": "09e76e5a1349c3393090af6207156df6deaa6b467fe1c10ae2d0ca1b4020b2c3", "src/_lcm/solution/model_seal.py": "44cd05fe67b0c037e0c30dfcb45a72c3f6eb19e043b4f6f4592be7fb4de18823", "src/_lcm/solution/native_values.py": "4e7302d6cacb53a20f6a0a08e7f57d6e074dedddd8f6a95944a9ed1ed4df7bda", - "src/_lcm/solution/nbegm.py": "fec7a5fbb235f536098b182de5afff4d4ed7a6edd0a36b65fa9a054e9e32cdd6", - "src/_lcm/solution/negm.py": "5ec1a833ee8a69b4f0438f13e4ce056669fd3b1f467f1851f19ef0a3c02a2538", - "src/_lcm/solution/nnbegm.py": "c6208c79591a0d2ea7b953a55bf447e2f58bf4743a4a85fca75d8c00b8ae358a", - "src/_lcm/solution/period_capture.py": "c9e955596137b839c50e3616eec73aa6c0326ac6a67eac8828f749cd87f72f05", - "src/_lcm/solution/period_replay.py": "2f0253693e474c70760a80ab6c07b5bdeb25ffa4aa77224e27ea5d15af5b1a55", + "src/_lcm/solution/nbegm.py": "99dd2e916cb6d265c4bf7d12de55992a9ba925cddec40ca53a5777c234e6fe20", + "src/_lcm/solution/negm.py": "468409fccaef9285d98e57a50485de6d5d4c2a94e730ce9103b84183e92b6782", + "src/_lcm/solution/nnbegm.py": "24b95297357f96334dd499fdc2edd903e5b8e3487ba52293245c77dffb84b24e", + "src/_lcm/solution/period_capture.py": "bf7b0c053dc3863de6c8893448161a515e6f8ed45e07e8070332505f1d51a275", + "src/_lcm/solution/period_replay.py": "d504ad8064dd8d7fc127ebd05510dc7ef1abc939627ab3f004b1ee75427e19ae", "src/_lcm/solution/periodization.py": "469b05c169c99b2c9d0e8d46f331682285256543b4f36786c6a29eb67a9fd361", - "src/_lcm/solution/preconditions.py": "52c97f5f2f6e9e3b6a7ac7215181874cef52948f613f59c270ef9638a51493ac", - "src/_lcm/solution/public_period_capture.py": "b2998c0d6f974bdbaa736a1dcd2b71a43e6dbb4f77c5f67dd96eb9492323fea0", - "src/_lcm/solution/public_period_replay.py": "2204eeebc6a1d4f6a9b5dcdfc5585a0206414a0c3a9d36ff0149bdb6560115dd", - "src/_lcm/solution/replay_validation.py": "612b36eaade8aa9c62fa36aebed7d457861f4ccb1e1f68f2561d802aa4d3ae22", - "src/_lcm/solution/result_snapshot.py": "95a3cd4e31bff7587defb208790620657eea96bfe6d78559f82ebfe7947aed18", - "src/_lcm/solution/retained_buffers.py": "ff70f53aa60b37acda0e851d7ee319b7d3d0c935ab1013227f671b44d39610af", + "src/_lcm/solution/preconditions.py": "5df8b182b8cb3c37f6ab76719386cc809052bcc00cda63772d698c75071f4092", + "src/_lcm/solution/public_period_capture.py": "4ceb8f7ebf628cd9c89ddd583fc33af80d81031129905ee2f38fad6f50d414df", + "src/_lcm/solution/public_period_replay.py": "98002b65559c248667da3bf9e165448481fb9f71f6ab3beb3e9bfc57e457ec03", + "src/_lcm/solution/replay_validation.py": "3a186a9cfaabfc57d3cf09bb7ce587390cedbeadd9aa7ae5f427a865ad873add", + "src/_lcm/solution/result_snapshot.py": "0d095decbc6cf19a34480032be5324695a04196de84d6df90789e397d0352c7b", + "src/_lcm/solution/retained_buffers.py": "bd8a0c05f900e3f2a2781ec0b8734f65e081d85e8f86d1dd4803ac09b8487aa9", "src/_lcm/solution/shipped_solvers.py": "ff9d9c7b3b7e2f0805ced66790965fe217586d57ea192f4b040124296caa8c36", - "src/_lcm/solution/solve_inputs.py": "df2acb9efaa218f46ef49ce73293a7bab5355b5d13c20c90fc0f54f3162f40f1", + "src/_lcm/solution/solve_inputs.py": "3ac8d07e459c1e1b5cb901a115dd32af3ce112fa2b98fe62e2147feaccd1698d", "src/_lcm/solution/solve_phase_records.py": "89de8a2b8a1279ef5c61577d6263941d84d862dbf679194f820c68c733cb7c86", "src/_lcm/solution/solver_diagnostics.py": "396183db9518dd0ffb0c31f29bd8e3df526a613a59d73d14103dda80281869a9", "src/_lcm/solution/structural_blueprints.py": "28bbe1b8f6301458e86ad7ee8bcf3bfb02184b163c3f3b038d88b0a261cf8af9", - "src/_lcm/solution/undeclared_reads.py": "a73321e540f1851b0290aaaccc16e229bceed97e57c73844971832cbeeffc4ff", - "src/_lcm/solution/v_topology.py": "0cdf79a071b34cdae497863d1b1a56e3cee3d39dda86239615a078b51eaf6026", - "src/_lcm/solution/validate_V.py": "70609bbd14dba6eeccf204a8f112c78cbd85799efbd007ecb880157259ecd2f3", - "src/_lcm/state_action_space.py": "bc1d4b798ae1beeef6ce6f655ba61cd3bbf064dbd1910b14aa5cf8ce28954e95", + "src/_lcm/solution/undeclared_reads.py": "a6bed1f4ba8c4df3852c532cbbc392cab4c7787b07c02e696b3908f46635c595", + "src/_lcm/solution/v_topology.py": "829818395b0a71ea20ae89a3be9c0f69e1d8bc94fdcf7713e6e2d8fdbc4322bf", + "src/_lcm/solution/validate_V.py": "b3df0d987fbce502fd1dd5f88868cd96b54fe6911bbcce19ea9fffffe4856358", + "src/_lcm/state_action_space.py": "761150639f8756f1157abbcc425e39e5d0b8a949afc0ccaf6f29bdad964d7476", "src/_lcm/time.py": "3ed1f81a9bb3ff0d0fed4e86bbb1131cad6df6f75191d2bed9643535d9fe0468", "src/_lcm/time_validation.py": "380da86f45779d52ee98a1585cf750d04e8ae1bae3855d34a3301c09e473d05c", - "src/_lcm/transition_checks.py": "ee319c669318000bdb89df173ea33c3e4752128f32d3ad919ed5a4bfb7c2452a", - "src/_lcm/transition_plans.py": "9248259ba2e6dad238eb1aa2e13b96182ef9d049b3afd0d71183afb7e675feb6", - "src/_lcm/typing.py": "9132d3cb69dad6810bedd06defe32e72d297361f6cd6ed731a176ed745983213", - "src/_lcm/user_regime_validation.py": "e5e08058bf65d35be158e91c9f8cba2c5b0fba843f55586daaeace5f2502e49e", + "src/_lcm/transition_checks.py": "ffcef4097c227add9201e89f492b3bb87bd4cf4b939571a65a24fccd283efa6e", + "src/_lcm/transition_plans.py": "8f4075aad3b8e44253bf9d90423daf13366c1a758f0ab2b7df84f0ed44fb820c", + "src/_lcm/typing.py": "11f1984c6c0506351259c26b78348ff8e60fc96bdb169334f62b4af0255b0989", + "src/_lcm/user_regime_validation.py": "6b274f2ddbc3ef7f05a36535335f02ff23270cab58298702692f0cb347250d33", "src/_lcm/utils/__init__.py": "b7343b80366cac4c3e54fe45293193cc752677b17a587ce9899989e4e4d7eb57", "src/_lcm/utils/ast_inspection.py": "2fb1928ee6ae394da5577e12aa5e906424f797245681b612cd57a88f55f9cf3d", "src/_lcm/utils/containers.py": "1b58c79878a182dd61929a15d4e3a2f3c249411d19d5df8853476bc57c2a87e1", "src/_lcm/utils/counts.py": "a9087a3c42d32ff0ca82cf24fda2b59ed57cb77efef94714a37a6ca7cf7a3f82", - "src/_lcm/utils/dispatchers.py": "9a01a33bc5f437bc7fec9ef3056e15c10e1c877462e19ccd23373141e12890c8", + "src/_lcm/utils/dispatchers.py": "a78d5271fcfc7437b68bd755ce7c2b8b0b78d5f26ed00a3fb4424133725da8b2", "src/_lcm/utils/error_messages.py": "6e4568ee95596710ea49afaeb647b451a15d9d0a7c6f06c988a795ced89214c6", - "src/_lcm/utils/functools.py": "70cc0206b7a59519ef0ad664da07221ce5fa5e0dc98e8341f214e4b60c572d2d", + "src/_lcm/utils/functools.py": "8dbb11ab2f7bac3cefe98c732a0ddb429d9e4189ea79517cff3f54d90d405cd5", "src/_lcm/utils/logging.py": "95f189e5713c7e97516b69e8298a79eea24f2baca9f7b55b62b56b81a1163023", "src/_lcm/utils/namespace.py": "9a33080663f01a6d65501663e8436b132176be51c8223c28b2e749d8dbf8b570", "src/_lcm/value_grid_inputs.py": "47c794a6c6bdf628fea8fab3428e2f0c7730e1c90470a6d8b4a7aef7761bf490", "src/_lcm/variables.py": "8445fd5d92144d013955027460ee204debfdcedf8bb5ef5d10092538cd18de8c", - "src/_lcm/version.py": "bd08c23ede1ca7099f76c7ee1388c46db5c4386c804152bbec03a4822004d5e7", - "src/_lcm/zero_safe.py": "99fc6b5647425c11e2c15abc9ff49c84d1b1ff3bace3f8e51e593ff8f98ec4ad", - "src/lcm/__init__.py": "5869d74b2c39977d3a6aca6f139f667640f43960dcf565f9d0a088c88dffe109", + "src/_lcm/version.py": "af0c503c255a9348dcdd745186f6c3731a8b78a7d9c6db921652f348ff8e879c", + "src/_lcm/zero_safe.py": "8d54492b73e33461f750420eef45ba8c8281c467acd0c77ba2eb90281793c8d3", + "src/lcm/__init__.py": "5aec44ab2985c072cec8dc3ce4085d9f9705ed7e3b6e845440e7bd3461379d78", "src/lcm/_compilation_cache.py": "c9fa151996cd77f69658133b467c24c8cce3cab9bb97e2b6895c431101cc743e", "src/lcm/_solver_api/__init__.py": "d9225eb6190a9d78c8e7d9e1a5ebf55d43c68bc4a18fb7654a79b74e3ffa7731", - "src/lcm/_solver_api/authority.py": "9bac2b806c1a9440d3ef4ca7701ca820fa2c39091cde1ed607802b7c3a1e1f04", + "src/lcm/_solver_api/authority.py": "2f838ac88c9429a8ae8ac03244ccd6ffd0998e66edc900412294a138664ee5d3", "src/lcm/_solver_api/beartype_conf.py": "a7d8f6403e2c62b430881b3fee08299828f3dca979f6bb61264fefdb51f92119", "src/lcm/_solver_api/capabilities.py": "ccfb3213a24925aefb28e2728a170bca2555c70bac94d4366378dc2f7d65ba4e", "src/lcm/_solver_api/contract.py": "7f42b6e0f675cb49d9399a877f170ffbe5068350f42dd53d3e8cf3cbdb10da0e", "src/lcm/_solver_api/descriptors.py": "014a943349d0b12ef8637039239ed8ba2f03070acf922a6d5ffb99d003ab15ca", - "src/lcm/_solver_api/entries.py": "298ba9790d6fab60fd88729b476c75206319dba64f246a0979c7a58444f99bfb", - "src/lcm/_solver_api/identity.py": "c15ec5114b0ba1878ffdcb0945558023e0c2529b8a5b313834561c0169d6bfb5", - "src/lcm/_solver_api/replay.py": "bc9e7cd94009998acfc1f11d8da823475030879790a49f8192e1260012496c96", - "src/lcm/_solver_api/result.py": "2763b2a23f91ca70a75de2658a3df0cf69ccdb1153b72ff590da7793c62c59b5", - "src/lcm/_solver_api/stores.py": "f40c0fdb20ebf37ff924fb970525084961ebf25e63ebfa142fff5082f2648a0d", + "src/lcm/_solver_api/entries.py": "0c27d42858dde4a34b5e82a3622dee9c7b240c0c9c3284a2ba4a898bbf9a6510", + "src/lcm/_solver_api/identity.py": "a150f9703341d351af0cbc4fbf785eca0a7f003214da859a8aa5d58e6a8579b8", + "src/lcm/_solver_api/replay.py": "65c8235466fdeda91e14b94863e8e8fa84eaa4fefc7b0e0fd30e5efcd514ffc5", + "src/lcm/_solver_api/result.py": "67a2f441394d8ab07889f655e7ac278a05e3796671e4a18ac8c80d90cbf57ca9", + "src/lcm/_solver_api/stores.py": "6c7be7157d70fab084f524f93fd182cff90b612a96dddacaf6e05ef7a1bf9bf7", "src/lcm/ages.py": "19a8dfaaedcbfc56e07b974eb68d0cc71fbca3abfb384759733e8fc9b1b6bb07", "src/lcm/branch_aggregation.py": "198dd252bfe7c542f4f24a0db64553194504712f6caa6c4485f71e1a98c984fe", "src/lcm/case_piece.py": "371ccbbf63cf94c023946b70029d618c9e5fe2372547f5123e6ef4a7aabf701b", "src/lcm/certainty_equivalent.py": "ae5ff47885a759544cadb3c8aef8a3cf177347b796906f27641b87a6589e06d2", - "src/lcm/collective.py": "0b10149d8dbd705e99a1b58fa5f5c71de5d592bd79df19d4dd76dd534cbb45b3", - "src/lcm/component_jobs.py": "9f219c638180d05648eda46cb6b2aafe4b39cc2534cc35a5f60da821818bfaef", + "src/lcm/collective.py": "37bb791783a5457610dbbf9bf78b1e0ffe221736705a119d6f4c9314a79cdd9d", + "src/lcm/component_jobs.py": "6b4c64f4b1df01d379b64acb91fc86ffb78335b114f4d1e5a92d88bf2c5ebdc2", "src/lcm/composite_state.py": "32c2fc034e9d5157a0b1006d5a18163f81a56124e339521b4f1eab4a4f28c0f8", "src/lcm/condition.py": "d31cc966e6c86e8444d15767c40ebe63d5d944cc1810cca66c8ed44a46e5976d", "src/lcm/consumption_savings_regime.py": "16118c29929f206f05925d88688edbc447f31c3a7aae1e73f022570e981ab886", "src/lcm/decoupled.py": "4505fc7bd833029d64b70e9c5d5e8ad10adf604c4907d846bc91759fa28f7199", - "src/lcm/exceptions.py": "93cdc46c17a6ec93403f7255c54b3a75fd83faf468d93b555b817bb01be626c1", - "src/lcm/execution.py": "039805b2518642e0655abec0896cc7d6c3b17e889f788222a52dac001aeb1df0", + "src/lcm/exceptions.py": "255dc372b7e0dd14da6ce0c0e978e60b8981067b328ed0f29a4e54748b9bce82", + "src/lcm/execution.py": "cb9c344ad9bb78fd55a008bec279e2cb88d60948da63feaf4fdb0050b6ca0d5b", + "src/lcm/exits.py": "912784aa0dac09cce58090a714e6b10495cb3389cbde85257f64b1a334308acc", "src/lcm/fixed_forms.py": "d6d069ed73eb7bcec13422261cea99cfcdeaa3b246bd7510cccd5c88f4be3613", "src/lcm/grids.py": "8b0cf35c51c0e3d65982a0b49ce347878e311c0680b45cd708b74d06732e1c6f", "src/lcm/initial_nodes.py": "2e198f5f8d3cceb369330bf9f6e10144b443bcf065e25930bf50cebe80833e6c", "src/lcm/koopmans_aggregation.py": "0aef5ec2724093997ac613de57fd09c6d5a139c13e89e4542e9e2ef77f150d77", "src/lcm/lowering.py": "e812ec0b50c40a0a15e300cbd9075a823ca36c43418dbeed9e9e4c0606ff8c62", - "src/lcm/model.py": "9b5381fbbe567b1414676b5941bae93cab8617d83b101f53689f4b04697be549", + "src/lcm/model.py": "6ac5cbb6335d79cdba8ebae0dedd67444e9a4a548e34841e3c3f4d981f5a867e", "src/lcm/outer_search.py": "40586c4ff6c45017646a7378af702060b119b34f0e9a3e7fac7d849436ba0b70", "src/lcm/params.py": "42bb2afbe4056431a3ecdcf65b74040a2e1ced09ea98d419e25e45fe31c6705d", + "src/lcm/participation.py": "19cc45ca193a562403f57f5d96525cf1e68641bef68abc3d4f4f6ea352d8301a", "src/lcm/period_capture.py": "73bdee8ed60ba30bf26b5f4852353d3f8941307b2426c82f7b6bc0b4eed1745d", "src/lcm/persistence.py": "09e56b5b00d388996a26757889af5581581ae7a1187188c67df20cb0a8d62b77", "src/lcm/phased.py": "045240ba4a5afd07dfa6f556f8adf59d3121b69c21c12327ee223573da33a042", "src/lcm/processes.py": "8f101680d5c7aaae84e4fcd4325837199e3ba506cfdc10311b36a831c055f618", - "src/lcm/regime.py": "f427974f45cccb642d76f4fe79d33eab48022436467d641504b3a0aa6eadde1c", - "src/lcm/result.py": "ab78a05bb03216b5d7df3d089aeaa43c1377374984c761815a7c0728c8981d52", - "src/lcm/solver_api.py": "6c7bd4a98b4eaec39f8f137b2953a2a46b53be9652b86ae25278fd040d9d553e", - "src/lcm/solvers.py": "94e88c724593be721730f84c9f8146334878ad1286cdd63dda77a9c8d0cffef4", - "src/lcm/taste_shocks.py": "ae0a87c888a55619bfa4f37deae62a6ae91e3ef8c5623e4da278ce375e9af523", - "src/lcm/temporal.py": "9c8b23f1f305192a52e55124167e1811054cea27c84efd51d206a612cc92e135", - "src/lcm/transition.py": "e92d12eac13dae77989e0581384b761d192fdc65183153fa927cd03613a57919", - "src/lcm/tuning.py": "c8dad9fd460290a6f1deef323c204505d53bc310b564e01311856f9898852e76", - "src/lcm/typing.py": "a9fab00dcc93c41af43b36308342c5bc21d522747479fc3c7245a7a552513d47", + "src/lcm/regime.py": "d22b78d7c65b6df9af71073a303285aeca85ca9b1b2efa903f805280d0bf3464", + "src/lcm/result.py": "d2b09b95537cb65dff52e87a4b9b91a6fe99570e8b98c7ce33a95f5e9d7f5ef1", + "src/lcm/shocks.py": "0e598f34741ae302425675fc2887cdc426471cd2cff220709054da4af75af7d2", + "src/lcm/solver_api.py": "1a28e0362e18de234456fa832ca03e9df468e33d972178e47b9579bb8425f575", + "src/lcm/solvers.py": "a89ed3b24ddd59bfd4adbfed6f81e1532e0441345a0b688d2a8891304c3d413c", + "src/lcm/taste_shocks.py": "bc0c77568bac4d28547b02b19a40c783bafb3223854d2fc625124a34eaebc36c", + "src/lcm/temporal.py": "4d4c9125844b0e0612a28eeb20288dbcc0d2591a0a91c89f12f4528605e415a0", + "src/lcm/transition.py": "bee97101a92d339e52e930066ac63b88158ca786f3d63cbb562d129ea10c1383", + "src/lcm/tuning.py": "cccc6f0402ac93b1e41850a193a1c0106223b3875089c7ad83227637a22000c5", + "src/lcm/typing.py": "5335c3c4cdfdcc48c231bd7ba3e44285d93be331242d77404d7778f977fe6c99", "src/lcm/version.py": "f8432f8c523598a60538648f954e11f03d227af5cf914587a9294f44304bc7b5", "src/lcm_examples/__init__.py": "714d95eab934bbdadc0b9e1418903a08299e3b0759d3f10ea980d3c18df22e54", - "src/lcm_examples/collective_household.py": "f49c9a23e23e4bc1f225ae243d43fa83fbcb2051aae1d262c729dc56cbcc69ba", - "src/lcm_examples/collective_regimes.py": "c83830626e1af8a95aab0ead40a036ef49df91ceb9903a0c464bef7c70864734", + "src/lcm_examples/collective_household.py": "f53928ef125c088b854e3fc89c6d1af439b00a520b397a039c2964d0b7a8db1f", + "src/lcm_examples/collective_regimes.py": "a21eaba3ef0653c00d4cdc270f8cd153991c5abfa2006ab30db4b6692c7c3541", "src/lcm_examples/epstein_zin.py": "1843dce8539cf423edaa080b3a2820a53bdf8d33efe7068d0292470725b2919e", - "src/lcm_examples/iskhakov_et_al_2017.py": "42aef063c4bf90db4b47239568c95fa6807d24ef89b08cadcb7fa96226f27aa7", + "src/lcm_examples/iskhakov_et_al_2017.py": "6c9d928f7656da9034811375d1923e936e8fccaa73db1a50bdb64886fe807790", "src/lcm_examples/mahler_yum_2024/__init__.py": "6444ec4509309c26901a3f2cf392037e2d77b92f7e538db176f59bb61dd8650d", "src/lcm_examples/mahler_yum_2024/implicit_pilot.py": "34fbfe7610b333a41428389c37cceb15875d05f5227d9453e0f7d06c6b39e3cf", "src/lcm_examples/mahler_yum_2024/paper.py": "51268af2d7aed1fddbf53e88d3e2a0f9ccbee936b296183c076ba213f18db76c", "src/lcm_examples/mortality.py": "70639e172c7702e9ca938af367865180625949fd8615ed15030e596468e08d09", - "src/lcm_examples/precautionary_savings.py": "6b29897a8e93d6fe9f66b7eafb0efa1ce694eec74d0f6ca7b8e600b2ce0854c9", + "src/lcm_examples/precautionary_savings.py": "1d164184ff786421d1a4f746088db56ee8e86c6b64b259bb8488de4193ef552f", "src/lcm_examples/precautionary_savings_health.py": "8ea0d7021651054fda4558ae03d0b721343d00041e750662d00977fed2049442", "src/lcm_examples/specialized_consumption_savings.py": "cdfbc34253f0a7399328e27a21d6049ee181bdfecaea3b0232b65581afb5e7cf", - "src/lcm_examples/stochastic_volatility.py": "ecfc6cfef4f4b01d0e2719be97867d7375b7e14ed9a3018f72ab777bdff4ebbf", + "src/lcm_examples/stochastic_volatility.py": "4478ce96959f71325625971f5f6f2116eb71e347daa4c6bbc2266c061de4c890", "src/lcm_examples/tiny.py": "408ca0627ad72f21770f55a65e93b04d1f9caeb8201353ff541c13f74f9729d4" }, - "recipe_sha256": "77e23619f21b8a70989677e18b9fb5eec8eb13c0045673b862d5776b5cf41e8e", - "jax_version": "0.11.2", - "jaxlib_version": "0.11.2", + "recipe_sha256": "30fed95bf91d2d3ecc45d2a24fa3ced59db75e324bce5e834f1aa2aa8b8f59f2", + "jax_version": "0.12.0.1", + "jaxlib_version": "0.12.0.1", "backend": "cpu", "devices": [ "cpu:0" @@ -388,10 +426,10 @@ "precision": 64, "prng_impl": "threefry2x32", "files": { - "simulation_lognormal.pkl": "feb5d5e2b3fc7790b81dae69010edad08d4cbc9ae5803512c87678b3443394b4", - "simulation_normal.pkl": "05412c57406218b5a4b4eca62fc8eb61fee31236e047f18958904ada4118ad99", - "simulation_rouwenhorst.pkl": "14357ff29d1c7a50ba7b9e38766a886f4038795c88286a919bee004fc3311c8e", - "simulation_tauchen.pkl": "0b41b14b684d9702d8ab29d9809a467714f1e06d6b014e6e5019f85ee0a80ce9", - "simulation_uniform.pkl": "837385ad82588df8744248ca3aa2138bc603abe3d08db68c6bc8fa20eea93c55" + "simulation_lognormal.pkl": "48699c426510adc1e0e54374e1432b30bd2f1e317dc9555cf0155363d6bef5c8", + "simulation_normal.pkl": "f2ae99b1fc8dcfcc66cfa1ff39e7eb00bfa6100084eea4756646b2d920a5cab5", + "simulation_rouwenhorst.pkl": "9b23c2372c8ecacd93e6e8bfb89c76f1f7400f58eca1ae241b24cae204ca10ec", + "simulation_tauchen.pkl": "551e4be309e7715289740e06f11f84b45673de5f9fc65297be885f1b5275abdc", + "simulation_uniform.pkl": "c1d369347b5f8fd4d46e714bfa270edd9a697303a6b849f882b246c5e91ce8b6" } } diff --git a/tests/data/processes/random-v1/simulation_lognormal.pkl b/tests/data/processes/random-v1/simulation_lognormal.pkl index bbba901fa..fe9fc0aec 100644 Binary files a/tests/data/processes/random-v1/simulation_lognormal.pkl and b/tests/data/processes/random-v1/simulation_lognormal.pkl differ diff --git a/tests/data/processes/random-v1/simulation_normal.pkl b/tests/data/processes/random-v1/simulation_normal.pkl index 3116eb8dd..6f42aed10 100644 Binary files a/tests/data/processes/random-v1/simulation_normal.pkl and b/tests/data/processes/random-v1/simulation_normal.pkl differ diff --git a/tests/data/processes/random-v1/simulation_rouwenhorst.pkl b/tests/data/processes/random-v1/simulation_rouwenhorst.pkl index 242aad7ed..0d8a5cad5 100644 Binary files a/tests/data/processes/random-v1/simulation_rouwenhorst.pkl and b/tests/data/processes/random-v1/simulation_rouwenhorst.pkl differ diff --git a/tests/data/processes/random-v1/simulation_tauchen.pkl b/tests/data/processes/random-v1/simulation_tauchen.pkl index 228c5f139..e1bfb9b52 100644 Binary files a/tests/data/processes/random-v1/simulation_tauchen.pkl and b/tests/data/processes/random-v1/simulation_tauchen.pkl differ diff --git a/tests/data/processes/random-v1/simulation_uniform.pkl b/tests/data/processes/random-v1/simulation_uniform.pkl index 0a738e4f6..31238323a 100644 Binary files a/tests/data/processes/random-v1/simulation_uniform.pkl and b/tests/data/processes/random-v1/simulation_uniform.pkl differ diff --git a/tests/data/regression_tests/generate_benchmark_data.py b/tests/data/regression_tests/generate_benchmark_data.py index ca95e8ac9..b3cbb75e7 100644 --- a/tests/data/regression_tests/generate_benchmark_data.py +++ b/tests/data/regression_tests/generate_benchmark_data.py @@ -101,7 +101,7 @@ def _generate_process_panels(data_dir: Path) -> None: params=processes.get_params(distribution_type), initial_conditions={ "health": jnp.asarray([0, 0], dtype=jnp.int32), - "income": jnp.asarray([0.0, 0.0]), + "income": jnp.full(2, processes.get_initial_income(distribution_type)), "wealth": jnp.asarray([1.0, 1.0]), "age": jnp.asarray([0.0, 0.0]), "regime_id": jnp.asarray([processes.RegimeId.alive] * 2), diff --git a/tests/regime_building/test_continuation_expectation_oracle.py b/tests/regime_building/test_continuation_expectation_oracle.py index ef97d4eac..07f1c5960 100644 --- a/tests/regime_building/test_continuation_expectation_oracle.py +++ b/tests/regime_building/test_continuation_expectation_oracle.py @@ -871,6 +871,31 @@ def _outer_weighted_params(*, model: Model, peak: np.floating) -> UserParams: } +@pytest.mark.parametrize("enable_jit", [False, True], ids=["eager", "jit"]) +@pytest.mark.parametrize(("fixture_name", "dtype"), _FINITE_RANGE_PRECISIONS) +def test_half_weighted_near_max_target_publishes_its_finite_expectation( + *, + enable_jit: bool, + fixture_name: str, + dtype: np.dtype, + request: pytest.FixtureRequest, +) -> None: + """A half-probability near-max lottery publishes its finite expected value.""" + request.getfixturevalue(fixture_name) + model = _outer_weighted_model(dtype=dtype, enable_jit=enable_jit, with_choice=False) + peak = np.finfo(dtype).max + params = _outer_weighted_params(model=model, peak=peak) + solution = model.solve(params=params, log_level="off") + # Halve first: the analytical expectation never needs an overflowing sum. + expected = (dtype.type(0.5) * peak) * _near_one(dtype) + np.testing.assert_allclose( + np.asarray(solution.values[0]["alive"]), + expected, + rtol=32 * np.finfo(dtype).eps, + atol=0.0, + ) + + @pytest.mark.parametrize("enable_jit", [False, True], ids=["eager", "jit"]) @pytest.mark.parametrize(("fixture_name", "dtype"), _FINITE_RANGE_PRECISIONS) def test_certain_three_quarters_of_max_beats_a_half_weighted_near_max_target( diff --git a/tests/simulation/test_host_preparation_lifetime.py b/tests/simulation/test_host_preparation_lifetime.py index 2aad5f8dd..d724b47e2 100644 --- a/tests/simulation/test_host_preparation_lifetime.py +++ b/tests/simulation/test_host_preparation_lifetime.py @@ -18,10 +18,7 @@ 2. Value-dependent per-call checks still run: a same-shaped rejected input still raises, at every log level. 3. Backend compile requests are zero on the warm hit. -4. The per-call jaxpr trace-request count on a warm call is unaffected by - migrating `_trace_process_jaxpr`'s nested callback: `_produce_staged` - calls it, uncached, on every solve, so the trace itself is a separate, - already-known cost (P2), not something this wrapper migration removes. +4. Warm calls reuse the process-grid trace from the first call. """ import builtins @@ -289,24 +286,18 @@ def test_migrated_process_grid_call_is_module_level_and_reused() -> None: assert "" not in first.__qualname__ -def test_warm_call_trace_request_count_is_unaffected_by_the_migration() -> None: - """Migrating `_trace_process_jaxpr`'s nested callback does not remove the - per-warm-call jaxpr retrace: `_produce_staged` calls `jax.make_jaxpr` fresh - on every solve, uncached, so this is the separate, already-known P2 - one-retrace-per-warm-call cost, not a side effect of the beartype-wrapper - migration. This test documents the current (post-migration) count so a - future change to that caching boundary shows up here. - """ +def test_warm_call_reuses_the_process_grid_trace() -> None: + """The first call traces the process grid and an identical call reuses it.""" model, params = _model(execution_config=None) initial_conditions = _initial_conditions() - # Warm the executable cache. - _run_simulate( - model=model, - params=params, - initial_conditions=initial_conditions, - log_level="off", - ) + with count_compile_requests() as cold: + _run_simulate( + model=model, + params=params, + initial_conditions=initial_conditions, + log_level="off", + ) with count_compile_requests() as counts: _run_simulate( @@ -316,10 +307,8 @@ def test_warm_call_trace_request_count_is_unaffected_by_the_migration() -> None: log_level="off", ) - # A warm call still retraces the continuous-process jaxpr at least once - # (the known P2 site); this migration only removes the beartype wrapper - # compile, not the trace itself. - assert counts.trace_requests >= 1 + assert cold.trace_requests > 0 + assert counts.trace_requests == 0 def _module_level_pure_operation(*, value: PytreeValue) -> PytreeValue: diff --git a/tests/solution/test_invariant_structural_cache.py b/tests/solution/test_invariant_structural_cache.py index 11ac3adc5..368161429 100644 --- a/tests/solution/test_invariant_structural_cache.py +++ b/tests/solution/test_invariant_structural_cache.py @@ -172,6 +172,59 @@ def _warm(*, model: Model, params: UserParams, n: int = 2) -> None: del warmed +def test_same_schema_warm_calls_reuse_the_compiled_executables( + *, monkeypatch: pytest.MonkeyPatch +) -> None: + """A repeat solve plans with the already compiled programs, not new wrappers.""" + model, params = _workload( + name="independent_types", execution_config=_config(blocked=False) + ) + with _captured_plans(monkeypatch) as plans: + first = _solve(model=model, params=params) + second = _solve(model=model, params=params) + first_programs, second_programs = ( + { + (regime, period, name): core.compiled + for (regime, period), cores in plan.executables.items() + for name, core in cores.items() + } + for plan in plans + ) + assert first_programs + assert first_programs.keys() == second_programs.keys() + assert all( + executable is second_programs[identity] + for identity, executable in first_programs.items() + ) + _assert_values_identical(first=first, second=second) + + +def test_cached_executables_release_a_calls_runtime_parameter() -> None: + """Keeping executables must not keep the last solve's dynamic operand.""" + model, params = _workload( + name="independent_types", execution_config=_config(blocked=False) + ) + + def solve_with_unique_operand() -> weakref.ReferenceType[jax.Array]: + changed = copy.deepcopy(params) + working = changed["working"] + assert isinstance(working, dict) + utility = working["utility"] + assert isinstance(utility, dict) + weight = utility["weight"] + assert isinstance(weight, jax.Array) + unique = weight * 1.125 + utility["weight"] = unique + reference = weakref.ref(unique) + _solve(model=model, params=changed) + return reference + + parameter = solve_with_unique_operand() + assert model._solve_executable_cache.compiled + gc.collect() + assert parameter() is None + + @pytest.mark.parametrize("blocked", [False, True]) @pytest.mark.parametrize("workload", _WORKLOADS) def test_same_schema_warm_calls_rebind_values_without_rebuilding_structure( @@ -479,11 +532,15 @@ def test_pickling_a_model_drops_its_blueprints() -> None: ) first = _solve(model=model, params=params) assert len(model._structural_blueprints) > 0 + assert model._solve_executable_cache.compiled assert "_structural_blueprints" not in model.__getstate__() + assert "_solve_executable_cache" not in model.__getstate__() restored = cloudpickle.loads(cloudpickle.dumps(model)) assert len(restored._structural_blueprints) == 0 + assert not restored._solve_executable_cache.compiled _assert_values_identical(first=first, second=_solve(model=restored, params=params)) assert len(restored._structural_blueprints) == 1 + assert restored._solve_executable_cache.compiled def test_a_blueprint_holding_other_program_objects_is_rebuilt( diff --git a/tests/solution/test_kernel_attribution.py b/tests/solution/test_kernel_attribution.py index fd4618fd0..cf312c4e9 100644 --- a/tests/solution/test_kernel_attribution.py +++ b/tests/solution/test_kernel_attribution.py @@ -153,7 +153,7 @@ def test_a_deduplicated_module_reports_how_many_triples_it_serves( and the log has to say which it is. """ monkeypatch.setenv("LCM_LOG_KERNEL_ATTRIBUTION", "1") - model = get_model(n_periods=_N_PERIODS) + model = get_model.__wrapped__(n_periods=_N_PERIODS) params = get_params(n_periods=_N_PERIODS) with caplog.at_level(logging.NOTSET, logger="lcm"): model.solve(params=params, log_level="off") diff --git a/tests/solution/test_participation_pricing_depth.py b/tests/solution/test_participation_pricing_depth.py index 905f9aed6..fdf566dec 100644 --- a/tests/solution/test_participation_pricing_depth.py +++ b/tests/solution/test_participation_pricing_depth.py @@ -309,7 +309,13 @@ def test_a_saved_solution_replays_its_stored_participation_surfaces( tmp_path: Path, ) -> None: """A loaded archive simulates exactly like the solution that wrote it.""" - model = household.get_model(n_periods=4, wealth_n_points=4, consumption_n_points=3) + # Use narrow programs to keep the archive comparison cheap to compile. + model = household.get_model( + n_periods=4, + wealth_n_points=4, + consumption_n_points=3, + execution_config=ExecutionConfig(axis_widths={"subject": 1}), + ) params = household.get_params() solution = model.solve(params=params, log_level="off") loaded = load_solution(path=solution.save(path=tmp_path / "solution.h5")) @@ -325,7 +331,9 @@ def simulate(solved: SolutionResult) -> pd.DataFrame: seed=0, ).to_dataframe() - pd.testing.assert_frame_equal(simulate(loaded), simulate(solution)) + pd.testing.assert_frame_equal( + simulate(loaded), simulate(solution), check_exact=True + ) # The household stores one surface of the couple's participation check, at the diff --git a/tests/solution/test_wide_exponent_spread_lottery.py b/tests/solution/test_wide_exponent_spread_lottery.py index d406d101b..e19eefb8d 100644 --- a/tests/solution/test_wide_exponent_spread_lottery.py +++ b/tests/solution/test_wide_exponent_spread_lottery.py @@ -27,7 +27,6 @@ scaled_exact_product, ) from _lcm.regime_building.zero_safe import zero_safe_average -from _lcm.zero_safe import scaled_weighted_terms # A competing continuation the exact lottery loses to and an enlarged one wins. _ALTERNATIVE = 0.47 @@ -325,66 +324,3 @@ def test_a_rare_node_keeps_its_infinity_through_a_general_transform(): ) assert float(np.asarray(got)) == float("-inf") - - -def test_a_terms_scale_is_split_so_a_rare_weight_does_not_underflow(): - """Committing the whole residual to the weight drops a representable term.""" - dtype = jnp.zeros(()).dtype - spread = 200 if dtype == jnp.float32 else 1500 - value_exponent = 100 if dtype == jnp.float32 else 1000 - - terms = scaled_weighted_terms( - coefficients=jnp.asarray([1.0, 0.75], dtype=dtype), - shifts=jnp.asarray([0, spread], dtype=jnp.int32), - values=jnp.asarray( - [0.0, jnp.ldexp(jnp.asarray(1.5, dtype=dtype), value_exponent)], - dtype=dtype, - ), - ) - - expected = jnp.ldexp(jnp.asarray(1.125, dtype=dtype), value_exponent - spread) - np.testing.assert_array_equal(np.asarray(terms[1]), np.asarray(expected)) - - -def test_a_terms_scale_is_split_so_a_large_value_does_not_overflow_it(): - """A node's contribution stays in range when its value is near the top of it. - - An ordinary weight meeting a value near the format's largest, at a scale - that brings the product back down, has an answer the format holds. Applying - the whole scale to the product first would overflow on the way to it. - """ - dtype = jnp.zeros(()).dtype - largest = jnp.finfo(dtype).max - - terms = scaled_weighted_terms( - coefficients=jnp.asarray([1.9, 1.0], dtype=dtype), - shifts=jnp.asarray([10, 0], dtype=jnp.int32), - values=jnp.asarray([largest, 1.0], dtype=dtype), - ) - - # Scale the weight before it meets the value, so the oracle stays inside the - # dtype's range: `1.9 · 2**-10` is exact, and the product is the answer itself - # rather than an overflow the oracle has to hold on the way to it. - expected = np.float64(np.ldexp(1.9, -10)) * np.float64(largest) - np.testing.assert_allclose( - np.asarray(terms)[0], expected, rtol=_relative_tolerance() - ) - - -def test_a_node_that_cannot_occur_contributes_nothing_against_an_infinity(): - """A represented-zero weight annihilates its value however the scale falls. - - The scale is applied around the product rather than to the weight alone, so - the null event has to survive that reordering: `0 * -inf` is the NaN the - weighted term exists to prevent, and it would take the well-specified node - beside it down too. - """ - dtype = jnp.zeros(()).dtype - - terms = scaled_weighted_terms( - coefficients=jnp.asarray([1.0, 0.0], dtype=dtype), - shifts=jnp.zeros(2, dtype=jnp.int32), - values=jnp.asarray([2.0, -jnp.inf], dtype=dtype), - ) - - np.testing.assert_allclose(np.asarray(terms), np.asarray([2.0, 0.0])) diff --git a/tests/solution/test_zero_probability_node.py b/tests/solution/test_zero_probability_node.py index f8164cd93..8462d6bad 100644 --- a/tests/solution/test_zero_probability_node.py +++ b/tests/solution/test_zero_probability_node.py @@ -172,12 +172,12 @@ def test_the_expectation_drops_a_zero_weight_node_rather_than_multiplying_it() - np.testing.assert_allclose(np.asarray(got), np.asarray(1.0)) -def test_a_negative_weight_is_not_laundered_into_a_zero_contribution() -> None: +def test_a_negative_weight_poisons_the_row() -> None: """A weight below zero is a malformed transition, not an impossible node. - Values `[1, 2]` at weights `[1, -1/2]` give `(1 - 1) / (1/2) = 0`. Dropping - the negative node instead would give `1`, a value that looks like the answer - to a well-posed question, so the malformed weight has to carry through. + Dropping the negative node from values `[1, 2]` at weights `[1, -1/2]` would + give `1`, and carrying it through would give `0`; both look like the answer + to a well-posed question. The row is poison instead. """ got = zero_safe_average( a=jnp.asarray([1.0, 2.0]), @@ -185,7 +185,7 @@ def test_a_negative_weight_is_not_laundered_into_a_zero_contribution() -> None: shifts=jnp.zeros(2, dtype=jnp.int32), ) - np.testing.assert_allclose(np.asarray(got), np.asarray(0.0), atol=1e-6) + assert bool(jnp.isnan(jnp.asarray(got))) def test_a_nan_weight_stays_poison() -> None: diff --git a/tests/test_hatch_build.py b/tests/test_hatch_build.py index fd9e78198..525d436db 100644 --- a/tests/test_hatch_build.py +++ b/tests/test_hatch_build.py @@ -439,9 +439,12 @@ def test_the_export_manifest_names_every_registered_ffi_target(): assert set(hatch_build.EXACT_AFFINE_HANDLER_SYMBOLS) == set(ffi._TARGETS) -@pytest.mark.parametrize("executable", [None, "/owned/example/compiler"]) +@pytest.mark.parametrize( + ("executable", "flags"), + [(None, []), ("/owned/example/compiler", ["--version"]), ("cl.exe", [])], +) def test_tool_version_preserves_report_and_absent_tool( - *, monkeypatch: pytest.MonkeyPatch, executable: str | None + *, monkeypatch: pytest.MonkeyPatch, executable: str | None, flags: list[str] ) -> None: """Preserve the exact version report and avoid probing an absent tool.""" calls: list[tuple[tuple[list[str]], _ToolProbeKwargs]] = [] @@ -468,7 +471,7 @@ def record_run( "exit=7\ncompiler v1\ndiagnostic", [ ( - ([executable, "--version"],), + ([executable, *flags],), { "capture_output": True, "text": True, @@ -480,6 +483,21 @@ def record_run( ) +def test_native_build_inputs_fingerprint_msvc_on_windows( + *, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Fingerprint the Windows compiler that builds the native payload.""" + monkeypatch.setattr(hatch_build.sys, "platform", "win32") + monkeypatch.delenv("CXX", raising=False) + tools = {"cl": "cl.exe", "c++": "c++.exe"} + monkeypatch.setattr(hatch_build.shutil, "which", tools.get) + monkeypatch.setattr(hatch_build, "_tool_version", lambda executable: executable) + + inputs = hatch_build.native_build_inputs(root=_fake_checkout(tmp_path)) + + assert (inputs["compiler"], inputs["compiler_version"]) == ("cl.exe", "cl.exe") + + def test_tool_version_propagates_timeout(monkeypatch: pytest.MonkeyPatch) -> None: """Propagate a timed-out probe instead of reporting unavailable metadata.""" command = ["/owned/example/compiler", "--version"] diff --git a/tests/test_models/processes.py b/tests/test_models/processes.py index 9fdd04bb0..24c4452fe 100644 --- a/tests/test_models/processes.py +++ b/tests/test_models/processes.py @@ -1,7 +1,9 @@ import functools +from collections.abc import Callable from typing import Literal from jax import numpy as jnp +from typing_extensions import TypedDict from _lcm.grids import DiscreteGrid, LinSpacedGrid, categorical from lcm import ( @@ -19,14 +21,27 @@ from lcm.regime import Regime as UserRegime from lcm.regime import StochasticTransition from lcm.typing import ( + BoolND, ContinuousAction, ContinuousState, DiscreteState, FloatND, + RegimeName, ScalarInt, UserParams, ) +type DistributionType = Literal[ + "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" +] + + +class ProcessRegimeParams(TypedDict, total=False, closed=True): + discount_factor: float + next_health: dict[str, FloatND] + income: dict[str, float] + + _SHOCK_GRID_CLASSES = { "uniform": UniformIIDProcess, "normal": functools.partial(NormalIIDProcess, gauss_hermite=True), @@ -43,10 +58,21 @@ def next_health(*, health: DiscreteState, probs_array: FloatND) -> FloatND: def next_wealth( *, consumption: ContinuousAction, wealth: ContinuousState, income: ContinuousState ) -> FloatND: - """Carry forward unspent wealth plus income, as `wealth_constraint` counts it.""" + """Carry forward unspent wealth plus income, as `wealth_constraint` counts it. + + `income` is log income here; the lognormal variant holds income in levels and + uses `next_wealth_from_level` instead. + """ return wealth - consumption + jnp.exp(income) +def next_wealth_from_level( + *, consumption: ContinuousAction, wealth: ContinuousState, income: ContinuousState +) -> FloatND: + """Carry forward unspent wealth plus income held in levels.""" + return wealth - consumption + income + + def next_regime(*, age: float, final_age_alive: float) -> ScalarInt: return jnp.where( age >= final_age_alive, @@ -57,10 +83,37 @@ def next_regime(*, age: float, final_age_alive: float) -> ScalarInt: def wealth_constraint( *, wealth: ContinuousState, income: ContinuousState, consumption: ContinuousAction -): +) -> BoolND: return wealth - consumption + jnp.exp(income) >= 0 +def wealth_constraint_from_level( + *, wealth: ContinuousState, income: ContinuousState, consumption: ContinuousAction +) -> BoolND: + """Check resources with income held in levels.""" + return wealth - consumption + income >= 0 + + +def get_wealth_functions( + distribution_type: DistributionType, +) -> tuple[Callable[..., FloatND], Callable[..., BoolND]]: + """Return the wealth transition and constraint matching the income process. + + The lognormal process draws income in levels, every other one in logs, so the + lognormal variant is the normal one with the exponential moved into the process. + """ + if distribution_type == "lognormal": + return next_wealth_from_level, wealth_constraint_from_level + return next_wealth, wealth_constraint + + +def get_initial_income( + distribution_type: DistributionType, +) -> float: + """Return the period-0 income that corresponds to a zero log-income draw.""" + return 1.0 if distribution_type == "lognormal" else 0.0 + + def utility( *, wealth: ContinuousState, # noqa: ARG001 @@ -87,12 +140,11 @@ class RegimeId: def get_model( *, n_periods: int, - distribution_type: Literal[ - "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" - ], -): + distribution_type: DistributionType, +) -> Model: final_age_alive = n_periods - 2 stays = tuple(range(final_age_alive)) + wealth_transition, wealth_feasible = get_wealth_functions(distribution_type) alive = UserRegime( states={ @@ -101,13 +153,13 @@ def get_model( "health": DiscreteGrid(category_class=Health), }, state_transitions={ - "wealth": next_wealth, + "wealth": wealth_transition, "health": StochasticTransition(func=next_health), }, actions={ "consumption": LinSpacedGrid(start=0.1, stop=2, n_points=4), }, - constraints={"wealth_constraint": wealth_constraint}, + constraints={"wealth_constraint": wealth_feasible}, functions={"utility": utility}, ) dead = UserRegime( @@ -141,9 +193,7 @@ class MultiRegimeId: def get_multi_regime_model( *, n_periods: int, - distribution_type: Literal[ - "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" - ], + distribution_type: DistributionType, execution_config: ExecutionConfig | None = None, ) -> Model: """Create a model with two non-terminal regimes that each have shock grids. @@ -160,6 +210,7 @@ def get_multi_regime_model( retire_final_age = n_periods - 2 shock_grid_cls = _SHOCK_GRID_CLASSES[distribution_type] + wealth_transition, wealth_feasible = get_wealth_functions(distribution_type) # `work` and `retire` share one declaration but are built separately, so the # two regimes hold distinct regime and grid objects across the shock handoff. @@ -171,13 +222,13 @@ def get_multi_regime_model( "health": DiscreteGrid(category_class=Health), }, state_transitions={ - "wealth": next_wealth, + "wealth": wealth_transition, "health": StochasticTransition(func=next_health), }, actions={ "consumption": LinSpacedGrid(start=0.1, stop=2, n_points=4), }, - constraints={"wealth_constraint": wealth_constraint}, + constraints={"wealth_constraint": wealth_feasible}, functions={"utility": utility}, ) for name in ("work", "retire") @@ -214,9 +265,7 @@ def get_multi_regime_model( def _get_default_multi_regime_model( *, n_periods: int, - distribution_type: Literal[ - "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" - ], + distribution_type: DistributionType, ) -> Model: """Return the multi-regime model under the default execution config, cached.""" return get_multi_regime_model( @@ -227,9 +276,7 @@ def _get_default_multi_regime_model( def get_multi_regime_params( - distribution_type: Literal[ - "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" - ] = "tauchen", + distribution_type: DistributionType = "tauchen", ) -> UserParams: """Return parameter dict for the multi-regime shock model.""" shock_params = _SHOCK_PARAMS[distribution_type] @@ -256,10 +303,8 @@ def get_multi_regime_params( def get_params( - distribution_type: Literal[ - "uniform", "normal", "lognormal", "tauchen", "rouwenhorst" - ] = "tauchen", -): + distribution_type: DistributionType = "tauchen", +) -> dict[RegimeName, ProcessRegimeParams]: return { "alive": { "discount_factor": 1.0, diff --git a/tests/test_process_off_grid.py b/tests/test_process_off_grid.py index 785d6d83f..5137a002d 100644 --- a/tests/test_process_off_grid.py +++ b/tests/test_process_off_grid.py @@ -15,7 +15,12 @@ from lcm.exceptions import GridInitializationError, OffGridStateError from lcm.typing import OffGrid from tests.test_models.processes import RegimeId -from tests.test_process_simulation_laws import _model, _tauchen +from tests.test_process_simulation_laws import ( + _model, + _reference_row, + _rouwenhorst, + _tauchen, +) _RULES: tuple[OffGrid, ...] = ("extrapolate", "clip_lookup", "clip_state", "raise") @@ -94,34 +99,29 @@ def test_process_off_grid_rule_enters_the_fingerprint(*, rule: OffGrid) -> None: ) -def _expected_row(*, process: TauchenAR1Process, value: float, rule: OffGrid): - nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) - rows = np.asarray(process.get_transition_probs(), dtype=np.float64) - if rule != "extrapolate": - return rows[0] if value < nodes[0] else rows[-1] - if value > nodes[-1]: - t = (value - nodes[-1]) / (nodes[-1] - nodes[-2]) - return rows[-1] + t * (rows[-1] - rows[-2]) - t = (nodes[0] - value) / (nodes[1] - nodes[0]) - return rows[0] + t * (rows[0] - rows[1]) - - @pytest.mark.parametrize("side", ["above", "below"]) -@pytest.mark.parametrize("rule", _RULES[:3]) -@pytest.mark.parametrize("build", [_tauchen, _on_nodes], ids=["tauchen", "on-nodes"]) -def test_transition_row_beyond_the_outer_nodes_follows_the_rule( - *, build: Callable[..., TauchenAR1Process], rule: OffGrid, side: str +@pytest.mark.parametrize("rule", ["clip_lookup", "clip_state"]) +@pytest.mark.parametrize( + "build", + [_tauchen, _on_nodes, _rouwenhorst], + ids=["tauchen", "on-nodes", "rouwenhorst"], +) +def test_transition_row_beyond_the_outer_nodes_is_the_edge_node_row( + *, + build: Callable[..., _ContinuousStochasticProcess], + rule: OffGrid, + side: str, ) -> None: - """Extrapolate the edge segment's rows, or read the nearest edge node's row.""" + """A clipped rule reads the nearest edge node's row beyond the nodes.""" process = build(off_grid=rule) nodes = np.asarray(process.get_gridpoints()) value = float(nodes[-1] + 0.7) if side == "above" else float(nodes[0] - 0.7) weights = _get_weights_func_for_process(name="income", grid=process) + rows = np.asarray(process.get_transition_probs()) np.testing.assert_allclose( np.asarray(weights(income=jnp.asarray(value))), - _expected_row(process=process, value=value, rule=rule), - rtol=1e-5, - atol=1e-6, + rows[-1] if side == "above" else rows[0], + rtol=1e-6, ) @@ -147,25 +147,24 @@ def test_policy_read_beyond_the_top_node_blends_rows_by_the_rule( np.testing.assert_allclose(coefficients, expected, rtol=0, atol=1e-6) -def _continuations(*, process: TauchenAR1Process, starts: np.ndarray) -> np.ndarray: - values, _ = _simulate(process=process, starts=starts) - return values - starts**2 - - @pytest.mark.parametrize("rule", _RULES[:3]) def test_value_beyond_the_top_node_reads_the_continuation_by_the_rule( *, rule: OffGrid ) -> None: - """Clipped rules read the top node's continuation; extrapolate extends the edge.""" + """Clipped rules read the top node's row; extrapolate reads the law's row there. + + The next period is the last alive one, so its value at a node is its utility. + """ process = _tauchen(rho=0.9, off_grid=rule) nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) beyond = nodes[-1] + 2.0 - got, middle, top = _continuations( - process=process, starts=np.array([beyond, nodes[-2], nodes[-1]]) + values, _ = _simulate(process=process, starts=np.array([beyond])) + row = ( + _reference_row(process=process, value=beyond) + if rule == "extrapolate" + else np.asarray(process.get_transition_probs(), dtype=np.float64)[-1] ) - t = (beyond - nodes[-1]) / (nodes[-1] - nodes[-2]) - expected = top + t * (top - middle) if rule == "extrapolate" else top - np.testing.assert_allclose(got, expected, rtol=1e-5) + np.testing.assert_allclose(values[0] - beyond**2, 0.9 * row @ nodes**2, rtol=1e-5) @pytest.mark.parametrize("rule", ["clip_lookup", "clip_state"]) diff --git a/tests/test_process_simulation_laws.py b/tests/test_process_simulation_laws.py index 83e520737..2d4604176 100644 --- a/tests/test_process_simulation_laws.py +++ b/tests/test_process_simulation_laws.py @@ -1,40 +1,63 @@ """Process simulation uses either solve nodes or its declared phase law.""" +import functools +import itertools +import math from collections.abc import Callable from dataclasses import replace from types import MappingProxyType +from typing import Literal, cast import jax import jax.numpy as jnp import numpy as np import pytest +from numpy.typing import NDArray from _lcm.grids import Grid +from _lcm.processes.ar1 import _TauchenOnNodesProcess from _lcm.processes.base import _ContinuousStochasticProcess +from _lcm.regime_building import Q_and_F as q_and_f from _lcm.regime_building.next_state import _create_continuous_stochastic_next_func -from _lcm.typing import StochasticNextFunction +from _lcm.regime_building.processing import _get_weights_func_for_process +from _lcm.typing import ( + ArrayTree, + EconFunctionsMapping, + RegimeName, + StochasticNextFunction, +) from _lcm.utils.logging import LogLevel from lcm import ( AgeGrid, + CertaintyEquivalent, DiscreteGrid, + LinearExpectation, LinSpacedGrid, Model, NormalIIDProcess, Phased, + PowerMean, Regime, + RouwenhorstAR1Process, StateConditioned, + StochasticTransition, TauchenAR1Process, + TauchenNormalMixtureAR1Process, + Transition, UniformIIDProcess, categorical, fixed_transition, ) from lcm.exceptions import ( GridInitializationError, + InvalidParamsError, ModelInitializationError, PyLCMError, RegimeInitializationError, + ScaledLotteryDifferentiationError, ) from lcm.typing import ContinuousState, FloatND, ScalarInt, UserParams +from tests.conftest import DECIMAL_PRECISION from tests.test_models.processes import Health, RegimeId @@ -718,3 +741,1045 @@ def test_phased_process_with_one_law_is_accepted() -> None: assert isinstance( Regime(states={"income": process}, functions={"utility": _utility}), Regime ) + + +def _positive_utility(income: ContinuousState) -> FloatND: + return income**2 + 1.0 + + +def _normal_cdf(x: np.ndarray) -> np.ndarray: + return 0.5 * (1.0 + np.vectorize(math.erf)(np.asarray(x) / math.sqrt(2.0))) + + +def _binned_row(cdf_at_midpoints: np.ndarray) -> np.ndarray: + """First bin the lower tail, last the upper tail, the rest CDF differences.""" + return np.concatenate( + [cdf_at_midpoints[:1], np.diff(cdf_at_midpoints), 1 - cdf_at_midpoints[-1:]] + ) + + +def _reference_row(*, process: _ContinuousStochasticProcess, value: float): + """The process's transition row from `value`, written from the law itself.""" + params = {k: float(v) for k, v in process.params.items()} + nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) + mean = params["mu"] + params["rho"] * value + if isinstance(process, TauchenNormalMixtureAR1Process): + half = 0.5 * (nodes[-1] - nodes[0]) / (len(nodes) - 1) + + def mixture(x: np.ndarray) -> np.ndarray: + return params["p1"] * _normal_cdf( + (x - params["mu1"]) / params["sigma1"] + ) + (1 - params["p1"]) * _normal_cdf((x - params["mu2"]) / params["sigma2"]) + + return _binned_row(mixture(nodes[:-1] + half - mean)) + rule = getattr(process, "transition_rule", "midpoint") + sigma = params["sigma"] + if rule == "density": + density = np.exp(-0.5 * ((nodes - mean) / sigma) ** 2) + return density / density.sum() + if rule == "innovation_quadrature": + process = cast("_TauchenOnNodesProcess", process) + weights = np.asarray(process.innovation_weights) + weights = weights / weights.sum() + row = np.zeros_like(nodes) + for shock, weight in zip(process.innovation_nodes, weights, strict=True): + target = np.clip(mean + sigma * shock, nodes[0], nodes[-1]) + lower = min( + int(np.searchsorted(nodes, target, side="right")) - 1, len(nodes) - 2 + ) + lower = max(lower, 0) + share = (target - nodes[lower]) / (nodes[lower + 1] - nodes[lower]) + row[lower] += weight * (1 - share) + row[lower + 1] += weight * share + return row + return _binned_row(_normal_cdf(((nodes[:-1] + nodes[1:]) / 2 - mean) / sigma)) + + +_TAUCHEN_FAMILY = { + "tauchen": lambda: _tauchen(rho=0.9, mu=0.2), + "tauchen-gauss-hermite": lambda: TauchenAR1Process( + n_points=3, gauss_hermite=True, rho=0.9, sigma=0.3, mu=0.2 + ), + "on-nodes-midpoint": lambda: TauchenAR1Process.on_nodes( + nodes=jnp.array([-1.0, 0.0, 1.5]), rho=0.9, sigma=0.3, mu=0.2 + ), + "on-nodes-density": lambda: TauchenAR1Process.on_nodes( + nodes=jnp.array([-1.0, 0.0, 1.5]), + rho=0.9, + sigma=0.3, + mu=0.2, + transition_rule="density", + ), + "on-nodes-innovation-quadrature": lambda: TauchenAR1Process.on_nodes( + nodes=jnp.array([-1.0, 0.0, 1.5]), + rho=0.9, + sigma=0.3, + mu=0.2, + transition_rule="innovation_quadrature", + ), + "normal-mixture": lambda: TauchenNormalMixtureAR1Process( + n_points=3, + rho=0.9, + mu=0.2, + n_std=2.0, + p1=0.7, + mu1=-0.1, + sigma1=0.2, + mu2=0.2333333, + sigma2=0.5, + ), +} + + +@pytest.mark.parametrize("position", ["between", "above", "below"]) +@pytest.mark.parametrize("family", list(_TAUCHEN_FAMILY)) +def test_tauchen_family_row_off_the_nodes_is_the_law( + *, family: str, position: str +) -> None: + """Off its nodes, a Tauchen-family row bins the law from the actual value.""" + process = _TAUCHEN_FAMILY[family]() + nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) + value = { + "between": 0.3 * nodes[0] + 0.7 * nodes[1], + "above": nodes[-1] + 0.8, + "below": nodes[0] - 0.8, + }[position] + weights = _get_weights_func_for_process(name="income", grid=process) + np.testing.assert_allclose( + np.asarray(weights(income=jnp.asarray(value))), + _reference_row(process=process, value=value), + rtol=1e-5, + atol=1e-6, + ) + + +@pytest.mark.parametrize("family", list(_TAUCHEN_FAMILY)) +def test_tauchen_family_row_at_a_node_is_the_tabulated_row(*, family: str) -> None: + process = _TAUCHEN_FAMILY[family]() + weights = _get_weights_func_for_process(name="income", grid=process) + nodes = process.get_gridpoints() + np.testing.assert_array_equal( + np.stack([np.asarray(weights(income=node)) for node in nodes]), + np.asarray(process.get_transition_probs()), + ) + + +def _rouwenhorst(**kwargs: float | str | None) -> RouwenhorstAR1Process: + law = {"n_points": 3, "rho": 0.9, "sigma": 0.3, "mu": 0.0} + return RouwenhorstAR1Process(**(law | kwargs)) # ty: ignore[invalid-argument-type] + + +@pytest.mark.parametrize( + ("position", "expected"), + [("between", lambda rows: 0.25 * rows[0] + 0.75 * rows[1]), ("above", None)], +) +def test_rouwenhorst_row_blends_neighbouring_rows_and_reads_the_edge_beyond( + *, position: str, expected: Callable[[np.ndarray], np.ndarray] | None +) -> None: + """Rows exist only at nodes: a convex blend between them, the edge row beyond.""" + process = _rouwenhorst() + nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) + rows = np.asarray(process.get_transition_probs(), dtype=np.float64) + value = 0.25 * nodes[0] + 0.75 * nodes[1] if position == "between" else 9.0 + weights = _get_weights_func_for_process(name="income", grid=process) + np.testing.assert_allclose( + np.asarray(weights(income=jnp.asarray(value))), + rows[-1] if expected is None else expected(rows), + rtol=1e-6, + ) + + +def test_carried_tauchen_onto_narrower_nodes_solves_with_the_law_row() -> None: + """A source node beyond the target's nodes reads the target law's row there.""" + work, retired = _tauchen(n_std=3.0), _tauchen(n_std=2.0) + solution = _work_retired_model(work=work, retired=retired).solve( + params={}, log_level="off" + ) + work_nodes = np.asarray(work.get_gridpoints(), dtype=np.float64) + retired_values = np.asarray(solution.values[2]["retired"], dtype=np.float64) + expected = [ + z**2 + 0.9 * _reference_row(process=retired, value=z) @ retired_values + for z in work_nodes + ] + np.testing.assert_allclose( + np.asarray(solution.values[1]["work"]), expected, rtol=1e-5 + ) + + +def test_carried_rouwenhorst_with_different_nodes_is_refused() -> None: + with pytest.raises(ModelInitializationError, match="Rouwenhorst"): + _work_retired_model( + work=_rouwenhorst(sigma=0.3), retired=_rouwenhorst(sigma=0.2) + ) + + +def test_carried_rouwenhorst_with_different_runtime_nodes_is_refused() -> None: + """The solve must compare nodes even when both declarations leave sigma free.""" + model = _work_retired_model( + work=_rouwenhorst(sigma=None), retired=_rouwenhorst(sigma=None) + ) + params = { + "work": {"income": {"sigma": 0.3}}, + "retired": {"income": {"sigma": 0.2}}, + } + with pytest.raises(InvalidParamsError, match=r"Rouwenhorst.*income.*work.*retired"): + model.solve(params=params, log_level="off") + + +def test_carried_rouwenhorst_matching_runtime_nodes_match_fixed_solve() -> None: + """Supplying a common sigma at solve time preserves the solved values.""" + runtime = _work_retired_model( + work=_rouwenhorst(sigma=None), retired=_rouwenhorst(sigma=None) + ).solve(params={"sigma": 0.3}, log_level="off") + fixed = _work_retired_model(work=_rouwenhorst(), retired=_rouwenhorst()).solve( + params={}, log_level="off" + ) + np.testing.assert_allclose(runtime.values[1]["work"], fixed.values[1]["work"]) + + +def _period_zero_continuations( + *, + process: _ContinuousStochasticProcess, + certainty_equivalent: CertaintyEquivalent | None, + starts: np.ndarray, +) -> np.ndarray: + """Return each start's period-0 simulated value minus its utility.""" + model = Model( + regimes={ + "alive": Regime( + states={"income": process}, + functions={"utility": _positive_utility}, + certainty_equivalent=certainty_equivalent, + ), + "dead": Regime(functions={"utility": lambda: jnp.asarray(0.0)}), + }, + ages=AgeGrid(start=0, inclusive_stop=2, step="Y"), + initial_nodes={0: "alive"}, + edges={"alive": {"alive": 0, "dead": 1}}, + regime_id_class=RegimeId, + fixed_params={"discount_factor": 0.9}, + ) + params = ( + {} + if certainty_equivalent is None + else {"alive": {"certainty_equivalent": {"risk_aversion": 4.0}}} + ) + frame = model.simulate( + params=params, + solution=model.solve(params=params, log_level="off"), + initial_conditions={ + "income": jnp.asarray(starts), + "age": jnp.zeros(len(starts)), + "regime_id": jnp.full(len(starts), RegimeId.alive, dtype=jnp.int32), + }, + seed=11, + log_level="off", + ).to_dataframe(use_categorical_codes=True) + values = frame.loc[frame["period"] == 0].sort_values("subject_id")["value"] + return values.to_numpy() - (starts**2 + 1.0) + + +@pytest.mark.parametrize("side", ["above", "below"]) +@pytest.mark.parametrize("simulated_draws", ["continuous", "nodes"]) +@pytest.mark.parametrize( + "certainty_equivalent", [None, PowerMean()], ids=["expectation", "power-mean"] +) +def test_rouwenhorst_continuation_beyond_an_outer_node_extends_the_edge_segment( + *, + certainty_equivalent: CertaintyEquivalent | None, + simulated_draws: str, + side: str, +) -> None: + """Beyond the nodes, the continuation is linear in the two edge nodes' values. + + The continuation at a node is the expectation (or certainty equivalent) under + that node's transition row, so the extension is linear in those, not the + certainty equivalent of an extrapolated, signed row. + """ + process = _rouwenhorst(simulated_draws=simulated_draws) + nodes = np.asarray(process.get_gridpoints(), dtype=np.float64) + edge, inner = (nodes[-1], nodes[-2]) if side == "above" else (nodes[0], nodes[1]) + beyond = edge + 2.0 * (edge - inner) + got, at_edge, at_inner = _period_zero_continuations( + process=process, + certainty_equivalent=certainty_equivalent, + starts=np.array([beyond, edge, inner]), + ) + np.testing.assert_allclose(got, at_edge + 2.0 * (at_edge - at_inner), rtol=1e-5) + + +@categorical(ordered=False) +class _ForkId: + source: ScalarInt + left: ScalarInt + right: ScalarInt + + +class _LinearExpectationSubclass(LinearExpectation): + """Use the declared aggregate rather than the exact-type engine reduction.""" + + +def _fork_model( + *, + certainty_equivalent: CertaintyEquivalent | None, + different_laws: bool = False, + two_coordinates: bool = False, + process: RouwenhorstAR1Process | None = None, +) -> Model: + """Build two mutually exclusive targets with carried process coordinates.""" + if process is None: + process = RouwenhorstAR1Process( + n_points=2, + rho=0.6, + sigma=0.8, + mu=0.0, + simulated_draws="continuous", + off_grid="extrapolate", + ) + + def left_utility(income: ContinuousState) -> FloatND: + return 1.5 + 0.5 * income + + def right_utility(income: ContinuousState) -> FloatND: + return 2.5 + 1.5 * income + + def source_utility(income: ContinuousState) -> FloatND: + return 1.0 + income**2 + + def source_product(*, income: ContinuousState, wage: ContinuousState) -> FloatND: + return 1.0 + income**2 + wage**2 + + def left_product(*, income: ContinuousState, wage: ContinuousState) -> FloatND: + return 4.0 + income * wage + + def right_product(*, income: ContinuousState, wage: ContinuousState) -> FloatND: + return 6.0 + 2.0 * income * wage + + states = {"income": process, **({"wage": process} if two_coordinates else {})} + return Model( + regimes={ + "source": Regime( + states=states, + functions={ + "utility": source_product if two_coordinates else source_utility + }, + certainty_equivalent=certainty_equivalent, + ), + "left": Regime( + states=states, + functions={ + "utility": left_product if two_coordinates else left_utility + }, + ), + "right": Regime( + states=( + {"income": replace(process, rho=-0.6)} if different_laws else states + ), + functions={ + "utility": right_product if two_coordinates else right_utility + }, + ), + }, + ages=AgeGrid(start=0, inclusive_stop=1, step="Y"), + initial_nodes={0: "source"}, + edges={ + "source": Transition( + targets={"left": 0, "right": 0}, + law={ + "left": StochasticTransition(func=lambda: jnp.asarray(0.5)), + "right": StochasticTransition(func=lambda: jnp.asarray(0.5)), + }, + ) + }, + regime_id_class=_ForkId, + fixed_params={"discount_factor": 0.9}, + ) + + +type _EdgeBuildResult = tuple[ + Callable[..., q_and_f.ContinuationAggregate], + tuple[Callable[..., ArrayTree], ...], + frozenset[str], +] + + +def _build_literal_process_corners( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + build: Callable[..., _EdgeBuildResult], +) -> tuple[q_and_f._ComputeCE, ...]: + """Enumerate original row substitutions independently of the index/loop program.""" + prefixes = tuple(f"weight_{target}__" for target in period_targets) + edges = { + name: rows + for name, func in functions.items() + if name.startswith(prefixes) + and isinstance(rows := getattr(func, "edge_rows", None), q_and_f.EdgeRows) + } + corners = [] + for choices in itertools.product((False, True), repeat=len(edges)): + corner = build( + functions=MappingProxyType( + dict(functions) + | { + name: rows.neighbour + for (name, rows), use_neighbour in zip( + edges.items(), choices, strict=True + ) + if use_neighbour + } + ), + period_targets=period_targets, + )[0] + assert isinstance(corner, q_and_f._ComputeCE) + assert corner.edge_extension is None + corners.append(corner) + return tuple(corners) + + +@pytest.mark.parametrize("certainty_equivalent", [None, PowerMean()]) +def test_process_edges_build_one_reusable_corner_program( + *, + monkeypatch: pytest.MonkeyPatch, + certainty_equivalent: CertaintyEquivalent | None, +) -> None: + """Build the base and one corner program for every joint process extension.""" + original = q_and_f._get_compute_CE_with_process_edges + observations: list[int] = [] + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + count = 0 + + def counted( + *, functions: EconFunctionsMapping, period_targets: tuple[RegimeName, ...] + ) -> _EdgeBuildResult: + nonlocal count + count += 1 + return build(functions=functions, period_targets=period_targets) + + result = original( + functions=functions, + period_targets=period_targets, + phase=phase, + build=counted, + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + observations.append(count) + return result + + monkeypatch.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model(certainty_equivalent=certainty_equivalent, two_coordinates=True) + assert observations + assert set(observations) == {2} + + +@pytest.mark.parametrize("two_coordinates", [False, True]) +def test_process_edge_program_builds_each_target_twice( + *, monkeypatch: pytest.MonkeyPatch, two_coordinates: bool +) -> None: + """Build each target once for the base and once for the indexed corner.""" + target_builds = 0 + observations: list[int] = [] + original_target = q_and_f._build_target_continuation + original_edges = q_and_f._get_compute_CE_with_process_edges + + def count_target[**P, R](func: Callable[P, R]) -> Callable[P, R]: + @functools.wraps(func) + def counted(*args: P.args, **kwargs: P.kwargs) -> R: + nonlocal target_builds + target_builds += 1 + return func(*args, **kwargs) + + return counted + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + before = target_builds + result = original_edges( + functions=functions, period_targets=period_targets, phase=phase, build=build + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + observations.append(target_builds - before) + return result + + monkeypatch.setattr( + q_and_f, "_build_target_continuation", count_target(original_target) + ) + monkeypatch.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model(certainty_equivalent=None, two_coordinates=two_coordinates) + assert observations + assert set(observations) == {4} + + +@pytest.mark.parametrize("two_coordinates", [False, True]) +@pytest.mark.parametrize("certainty_equivalent", [None, LinearExpectation()]) +def test_linear_process_edges_read_only_each_targets_local_corners( + *, + monkeypatch: pytest.MonkeyPatch, + two_coordinates: bool, + certainty_equivalent: CertaintyEquivalent | None, +) -> None: + """Reuse a target's expectation when only another target's row changes.""" + reader_calls = 0 + captured: list[q_and_f._ComputeCE] = [] + original_target = q_and_f._build_target_continuation + original_edges = q_and_f._get_compute_CE_with_process_edges + + def count_reader[**P, R](func: Callable[P, R]) -> Callable[P, R]: + @functools.wraps(func) + def counted(*args: P.args, **kwargs: P.kwargs) -> R: + nonlocal reader_calls + reader_calls += 1 + return func(*args, **kwargs) + + return counted + + def wrap_target[**P]( + func: Callable[P, q_and_f._TargetContinuation], + ) -> Callable[P, q_and_f._TargetContinuation]: + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> q_and_f._TargetContinuation: + target = func(*args, **kwargs) + assert target.next_V is not None + return replace(target, next_V=count_reader(target.next_V)) + + return wrapped + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + result = original_edges( + functions=functions, period_targets=period_targets, phase=phase, build=build + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + assert isinstance(result[0], q_and_f._ComputeCE) + captured.append(result[0]) + return result + + monkeypatch.setattr( + q_and_f, "_build_target_continuation", wrap_target(original_target) + ) + monkeypatch.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model( + certainty_equivalent=certainty_equivalent, two_coordinates=two_coordinates + ) + values = MappingProxyType( + { + "left": jnp.asarray( + [[5.0, 3.0], [3.0, 5.0]] if two_coordinates else [1.0, 2.0] + ), + "right": jnp.asarray( + [[8.0, 4.0], [4.0, 8.0]] if two_coordinates else [1.0, 4.0] + ), + } + ) + reader_calls = 0 + with jax.disable_jit(): + captured[0]( + next_regime_to_V_arr=values, + zero=jnp.asarray(0.0), + states_actions_params=MappingProxyType( + { + "income": jnp.asarray(3.0), + **({"wage": jnp.asarray(3.0)} if two_coordinates else {}), + } + ), + ) + assert reader_calls == (8 if two_coordinates else 4) + + +@pytest.mark.parametrize("two_coordinates", [False, True]) +def test_process_edge_program_traces_each_target_twice( + *, monkeypatch: pytest.MonkeyPatch, two_coordinates: bool +) -> None: + """Trace the base and one corner body without leaking state between transforms.""" + reader_calls = 0 + captured: list[q_and_f._ComputeCE] = [] + original_target = q_and_f._build_target_continuation + original_edges = q_and_f._get_compute_CE_with_process_edges + + def count_reader[**P, R](func: Callable[P, R]) -> Callable[P, R]: + @functools.wraps(func) + def counted(*args: P.args, **kwargs: P.kwargs) -> R: + nonlocal reader_calls + reader_calls += 1 + return func(*args, **kwargs) + + return counted + + def wrap_target[**P]( + func: Callable[P, q_and_f._TargetContinuation], + ) -> Callable[P, q_and_f._TargetContinuation]: + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> q_and_f._TargetContinuation: + target = func(*args, **kwargs) + assert target.next_V is not None + return replace(target, next_V=count_reader(target.next_V)) + + return wrapped + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + result = original_edges( + functions=functions, period_targets=period_targets, phase=phase, build=build + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + assert isinstance(result[0], q_and_f._ComputeCE) + captured.append(result[0]) + return result + + monkeypatch.setattr( + q_and_f, "_build_target_continuation", wrap_target(original_target) + ) + monkeypatch.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model(certainty_equivalent=None, two_coordinates=two_coordinates) + assert captured + compute = captured[0] + assert compute.edge_extension is not None + assert len(compute.edge_extension.distances) == (4 if two_coordinates else 2) + values = MappingProxyType( + { + "left": jnp.asarray( + [[5.0, 3.0], [3.0, 5.0]] if two_coordinates else [1.0, 2.0] + ), + "right": jnp.asarray( + [[8.0, 4.0], [4.0, 8.0]] if two_coordinates else [1.0, 4.0] + ), + } + ) + + def evaluate(next_values: MappingProxyType[RegimeName, FloatND]) -> FloatND: + result = compute( + next_regime_to_V_arr=next_values, + zero=jnp.asarray(0.0), + states_actions_params=MappingProxyType( + { + "income": jnp.asarray(3.0), + **({"wage": jnp.asarray(3.0)} if two_coordinates else {}), + } + ), + ) + assert isinstance(result, tuple) + return result[0] + + reader_calls = 0 + with jax.checking_leaks(): + compiled = jax.jit(evaluate) + actual = compiled(values) + assert reader_calls == 4 + # E[income] = E[wage] = rho * 3 = 1.8; the two target weights are one half. + expected = 9.86 if two_coordinates else 3.8 + np.testing.assert_allclose(actual, expected, rtol=10.0**-DECIMAL_PRECISION) + np.testing.assert_allclose( + compiled(jax.tree.map(lambda value: value + 10.0, values)), + expected + 10.0, + rtol=10.0**-DECIMAL_PRECISION, + ) + with jax.checking_leaks(): + np.testing.assert_allclose( + evaluate(values), expected, rtol=10.0**-DECIMAL_PRECISION + ) + with jax.disable_jit(): + np.testing.assert_allclose( + evaluate(values), expected, rtol=10.0**-DECIMAL_PRECISION + ) + batched = jax.vmap(evaluate)( + jax.tree.map(lambda value: jnp.stack((value, value + 10.0)), values) + ) + np.testing.assert_allclose( + batched, [expected, expected + 10.0], rtol=10.0**-DECIMAL_PRECISION + ) + _, tangent = jax.jvp(evaluate, (values,), (jax.tree.map(jnp.ones_like, values),)) + np.testing.assert_allclose(tangent, 1.0, rtol=10.0**-DECIMAL_PRECISION) + gradients = jax.grad(evaluate)(values) + expected_gradient = ( + [[0.08, -0.28], [-0.28, 0.98]] if two_coordinates else [-0.2, 0.7] + ) + for gradient in gradients.values(): + np.testing.assert_allclose( + gradient, expected_gradient, rtol=10.0**-DECIMAL_PRECISION + ) + + +@pytest.mark.parametrize("compiled", [False, True], ids=["eager", "jit"]) +@pytest.mark.parametrize("case", ["negative-inf", "signed-zero", "finite-overflow"]) +def test_process_edge_corners_keep_nonfinite_and_zero_semantics( + *, monkeypatch: pytest.MonkeyPatch, case: str, compiled: bool +) -> None: + """Keep the tensor expansion's nonfinite outcomes and represented zero sign.""" + captured: list[tuple[q_and_f._ComputeCE, tuple[q_and_f._ComputeCE, ...]]] = [] + original = q_and_f._get_compute_CE_with_process_edges + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + result = original( + functions=functions, period_targets=period_targets, phase=phase, build=build + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + assert isinstance(result[0], q_and_f._ComputeCE) + captured.append( + ( + result[0], + _build_literal_process_corners( + functions=functions, + period_targets=period_targets, + build=build, + ), + ) + ) + return result + + dtype = np.asarray(jnp.asarray(1.0)).dtype + rho = np.nextafter(dtype.type(1.0), dtype.type(0.0)) + process = RouwenhorstAR1Process( + n_points=2, + rho=0.6 if case == "finite-overflow" else float(rho), + sigma=0.8 if case == "finite-overflow" else float(np.sqrt(1.0 - rho**2)), + mu=0.0, + off_grid="extrapolate", + ) + with monkeypatch.context() as context: + context.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model(certainty_equivalent=None, process=process) + assert captured + compute, corners = captured[0] + extension = compute.edge_extension + assert extension is not None + assert len(corners) == 4 + nodes = process.get_gridpoints() + assert np.isfinite(np.asarray(nodes)).all() + rows = np.asarray(process.get_transition_probs()) + if case == "finite-overflow": + assert np.all(rows > 0) + left = right = [np.finfo(dtype).max, 1.0] + else: + np.testing.assert_array_equal(rows, np.eye(2, dtype=dtype)) + left = [-np.inf, 1.0] if case == "negative-inf" else [-0.0, 0.0] + right = [2.0, 2.0] if case == "negative-inf" else [0.0, -0.0] + values = MappingProxyType( + { + "left": jnp.asarray(left, dtype=dtype), + "right": jnp.asarray(right, dtype=dtype), + } + ) + + def evaluate(corner: q_and_f._ComputeCE) -> NDArray[np.float32 | np.float64]: + def read(next_values: MappingProxyType[RegimeName, FloatND]) -> FloatND: + aggregate = corner( + next_regime_to_V_arr=next_values, + zero=jnp.asarray(0.0, dtype=dtype), + states_actions_params=MappingProxyType({"income": 3.0 * nodes[-1]}), + ) + assert isinstance(aggregate, tuple) + return aggregate[0] + + return np.asarray(jax.jit(read)(values) if compiled else read(values)) + + actual = evaluate(compute) + f00, f01, f10, f11 = (evaluate(corner) for corner in corners) + with np.errstate(invalid="ignore", over="ignore"): + literal = 4.0 * f00 - 2.0 * f01 - 2.0 * f10 + f11 + np.testing.assert_array_equal(actual, literal) + if case == "negative-inf": + assert np.isnan(actual) + elif case == "finite-overflow": + assert np.isneginf(actual) + else: + assert not np.signbit(actual) + assert not np.signbit(literal) + + +@pytest.mark.parametrize( + ("certainty_equivalent", "different_laws", "two_coordinates"), + [ + (None, False, False), + (LinearExpectation(), False, False), + (PowerMean(), False, False), + (_LinearExpectationSubclass(), False, False), + (None, True, False), + (None, False, True), + ], + ids=["default", "linear", "power-mean", "subclass", "distinct-laws", "two-states"], +) +def test_process_edges_retain_the_original_cartesian_corners( + *, + monkeypatch: pytest.MonkeyPatch, + certainty_equivalent: CertaintyEquivalent | None, + different_laws: bool, + two_coordinates: bool, +) -> None: + """Every process weight retains its corner in the original tensor expansion.""" + original = q_and_f._get_compute_CE_with_process_edges + observations: list[int] = [] + captured: list[tuple[q_and_f._ComputeCE, tuple[q_and_f._ComputeCE, ...]]] = [] + + def observed( + *, + functions: EconFunctionsMapping, + period_targets: tuple[RegimeName, ...], + phase: Literal["solution", "simulation"], + build: Callable[..., _EdgeBuildResult], + ) -> _EdgeBuildResult: + count = 0 + + def counted( + *, functions: EconFunctionsMapping, period_targets: tuple[RegimeName, ...] + ) -> _EdgeBuildResult: + nonlocal count + count += 1 + return build(functions=functions, period_targets=period_targets) + + result = original( + functions=functions, + period_targets=period_targets, + phase=phase, + build=counted, + ) + if phase == "simulation" and set(period_targets) == {"left", "right"}: + observations.append(count) + assert isinstance(result[0], q_and_f._ComputeCE) + captured.append( + ( + result[0], + _build_literal_process_corners( + functions=functions, + period_targets=period_targets, + build=build, + ), + ) + ) + return result + + monkeypatch.setattr(q_and_f, "_get_compute_CE_with_process_edges", observed) + _fork_model( + certainty_equivalent=certainty_equivalent, + different_laws=different_laws, + two_coordinates=two_coordinates, + ) + assert observations + assert set(observations) == {2} + compute, literal_corners = captured[0] + extension = compute.edge_extension + assert extension is not None + assert len(literal_corners) == (16 if two_coordinates else 4) + values = MappingProxyType( + { + "left": jnp.asarray( + [[5.0, 3.0], [3.0, 5.0]] if two_coordinates else [1.0, 2.0] + ), + "right": jnp.asarray( + [[8.0, 4.0], [4.0, 8.0]] if two_coordinates else [1.0, 4.0] + ), + } + ) + states = MappingProxyType( + { + "income": jnp.asarray(3.0), + **({"wage": jnp.asarray(3.0)} if two_coordinates else {}), + **{ + name: jnp.asarray(-1.0) for name in compute.ce_flat_param_names.values() + }, + } + ) + for index, literal in enumerate(literal_corners): + reference = literal( + next_regime_to_V_arr=values, + zero=jnp.asarray(0.0), + states_actions_params=states, + ) + actual = extension.read_corner( + index=index, + next_regime_to_V_arr=values, + zero=jnp.asarray(0.0), + states_actions_params=states, + ) + assert isinstance(actual, tuple) + assert isinstance(reference, tuple) + np.testing.assert_allclose( + actual[0], reference[0], rtol=10.0**-DECIMAL_PRECISION + ) + if isinstance(certainty_equivalent, PowerMean): + for read in ( + literal_corners[0], + functools.partial(extension.read_corner, index=0), + ): + # keyword-only-exempt: library-callback=jax.jvp + def evaluate( + next_values: MappingProxyType[RegimeName, FloatND], + *, + read: Callable[..., q_and_f.ContinuationAggregate] = read, + ) -> FloatND: + aggregate = read( + next_regime_to_V_arr=next_values, + zero=jnp.asarray(0.0), + states_actions_params=states, + ) + assert isinstance(aggregate, tuple) + return aggregate[0] + + with pytest.raises(ScaledLotteryDifferentiationError): + jax.jvp(evaluate, (values,), (jax.tree.map(jnp.ones_like, values),)) + with pytest.raises(ScaledLotteryDifferentiationError): + jax.vjp(evaluate, values) + + +@pytest.mark.parametrize( + "case", ["linear", "power-mean", "distinct-laws", "two-states"] +) +def test_process_edge_sharing_preserves_the_continuation(case: str) -> None: + """Carried targets retain their analytic values on and beyond the process nodes.""" + model = _fork_model( + certainty_equivalent=PowerMean() if case == "power-mean" else None, + different_laws=case == "distinct-laws", + two_coordinates=case == "two-states", + ) + params = ( + {"source": {"certainty_equivalent": {"risk_aversion": -1.0}}} + if case == "power-mean" + else {} + ) + starts = jnp.asarray([3.0, 1.0, -1.0]) + initial_conditions = { + "income": starts, + "age": jnp.zeros(3), + "regime_id": jnp.full(3, _ForkId.source, dtype=jnp.int32), + **({"wage": starts} if case == "two-states" else {}), + } + frame = model.simulate( + params=params, + solution=model.solve(params=params, log_level="off"), + initial_conditions=initial_conditions, + seed=11, + log_level="off", + ).to_dataframe(use_categorical_codes=True) + got = frame.loc[frame["period"] == 0].sort_values("subject_id")["value"] + expected = { + "linear": [3.8, 2.6, 1.4], + "distinct-laws": [1.1, 1.7, 2.3], + "two-states": [9.86, 5.54, 5.54], + "power-mean": [ + 4.0 * math.sqrt(8.2) + - 2.0 * math.sqrt(3.7) + - 2.0 * math.sqrt(7.3) + + math.sqrt(2.8), + math.sqrt(8.2), + math.sqrt(2.8), + ], + }[case] + np.testing.assert_allclose( + got.to_numpy() + - (1.0 + np.asarray(starts) ** 2 * (2 if case == "two-states" else 1)), + 0.9 * np.asarray(expected), + rtol=10.0**-DECIMAL_PRECISION, + ) + + +def test_process_edge_program_observes_another_targets_row( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Select another target's row before a dependent probability callback reads it.""" + captured: list[q_and_f._ComputeCE] = [] + + def inject_cross_read[**P, R](func: Callable[P, R]) -> Callable[P, R]: + @functools.wraps(func) + def observed(*args: P.args, **kwargs: P.kwargs) -> R: + if kwargs.get("extend_process_edges") != "simulation" or set( + cast("tuple[RegimeName, ...]", kwargs["period_targets"]) + ) != {"left", "right"}: + return func(*args, **kwargs) + functions = cast("EconFunctionsMapping", kwargs["functions"]) + original_left = functions["weight_left__next_income"] + rows = getattr(original_left, "edge_rows", None) + assert isinstance(rows, q_and_f.EdgeRows) + + def left_row( + *, income: ContinuousState, weight_right__next_income: FloatND + ) -> FloatND: + return ( + 0.5 * original_left(income=income) + 0.5 * weight_right__next_income + ) + + def left_neighbour( + *, income: ContinuousState, weight_right__next_income: FloatND + ) -> FloatND: + return ( + 0.5 * rows.neighbour(income=income) + + 0.5 * weight_right__next_income + ) + + monkeypatch.setattr( + left_row, + "edge_rows", + replace(rows, neighbour=left_neighbour), + raising=False, + ) + functions = MappingProxyType( + dict(functions) | {"weight_left__next_income": left_row} + ) + result = functools.partial(func, *args, **kwargs)(functions=functions) + compute = cast("_EdgeBuildResult", result)[0] + assert isinstance(compute, q_and_f._ComputeCE) + captured.append(compute) + return result + + return observed + + monkeypatch.setattr( + q_and_f, "_get_compute_CE", inject_cross_read(q_and_f._get_compute_CE) + ) + _fork_model(certainty_equivalent=None) + assert captured + compute = captured[0] + extension = compute.edge_extension + assert extension is not None + assert len(extension.distances) == 2 + + def evaluate(index: int | None) -> FloatND: + read = ( + compute + if index is None + else functools.partial(extension.read_corner, index=index) + ) + result = read( + next_regime_to_V_arr=MappingProxyType( + {"left": jnp.asarray([1.0, 2.0]), "right": jnp.asarray([1.0, 4.0])} + ), + zero=jnp.asarray(0.0), + states_actions_params=MappingProxyType({"income": jnp.asarray(3.0)}), + ) + assert isinstance(result, tuple) + return result[0] + + # Literal two-node probabilities for the four joint edge/neighbour rows. + np.testing.assert_allclose( + [evaluate(index) for index in range(4)], + [2.6, 1.55, 2.45, 1.4], + rtol=10.0**-DECIMAL_PRECISION, + ) + np.testing.assert_allclose(evaluate(None), 3.8, rtol=10.0**-DECIMAL_PRECISION) diff --git a/tests/test_processes.py b/tests/test_processes.py index 723482447..63821e351 100644 --- a/tests/test_processes.py +++ b/tests/test_processes.py @@ -4,11 +4,12 @@ import shutil import subprocess import textwrap +from collections.abc import Callable from fractions import Fraction from functools import partial from itertools import pairwise from pathlib import Path -from typing import Literal +from typing import Literal, cast import jax import numpy as np @@ -53,6 +54,7 @@ from lcm.execution import ExecutionConfig from lcm.solver_api import SolutionResult from lcm.typing import ( + BoolND, ContinuousState, Float1D, FloatND, @@ -78,8 +80,10 @@ make_case as normalized_case, ) from tests.test_models.processes import ( + DistributionType, MultiRegimeId, RegimeId, + get_initial_income, get_model, get_multi_regime_model, get_multi_regime_params, @@ -88,10 +92,102 @@ # Grid centering is float-eps-limited at the active precision. _CENTERING_DECIMAL = 10 if X64_ENABLED else 5 -# Bound value error in the fixture whose lognormal tail extends far beyond its grid. +# Bound value error against independent finite-grid backward induction. _LOGNORMAL_RELATIVE_VALUE_ERROR = 1e-4 +def test_lognormal_fixture_wealth_transition_uses_income_levels() -> None: + """Add a level-valued income draw once when carrying wealth forward.""" + model = get_model(n_periods=4, distribution_type="lognormal") + transition = cast( + "Callable[..., FloatND]", + model.user_regimes["alive"].state_transitions["wealth"], + ) + np.testing.assert_allclose( + transition( + wealth=jnp.asarray(1.0), + consumption=jnp.asarray(0.5), + income=jnp.asarray(2.0), + ), + 2.5, + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + + +def test_lognormal_fixture_constraint_uses_income_levels() -> None: + """Refuse consumption that exceeds wealth plus level-valued income.""" + model = get_model(n_periods=4, distribution_type="lognormal") + constraint = cast( + "Callable[..., BoolND]", + model.user_regimes["alive"].constraints["wealth_constraint"], + ) + np.testing.assert_array_equal( + constraint( + wealth=jnp.asarray(1.0), + consumption=jnp.asarray(2.0), + income=jnp.asarray(0.5), + ), + desired=False, + ) + + +def _solve_process_representation( + distribution_type: Literal["normal", "lognormal"], +) -> tuple[SolutionResult, pd.DataFrame]: + """Solve and simulate matched income economies with a common random seed.""" + model = get_model(n_periods=4, distribution_type=distribution_type) + params = get_params(distribution_type) + solution = model.solve(params=params, log_level="off") + panel = model.simulate( + params=params, + initial_conditions={ + "health": jnp.asarray([0, 0], dtype=jnp.int32), + "income": jnp.full(2, get_initial_income(distribution_type)), + "wealth": jnp.asarray([1.0, 1.0]), + "age": jnp.asarray([0.0, 0.0]), + "regime_id": jnp.array([RegimeId.alive] * 2), + }, + solution=solution, + seed=42, + log_level="off", + ).to_dataframe() + return solution, panel + + +@pytest.mark.skipif( + not X64_ENABLED, reason="Income representation parity uses float64." +) +@pytest.mark.parametrize("period", [0, 1, 2]) +def test_lognormal_fixture_values_match_normal_income_representation( + period: int, +) -> None: + """Moving exponentiation into the income process preserves solved values.""" + lognormal, _ = _solve_process_representation("lognormal") + normal, _ = _solve_process_representation("normal") + np.testing.assert_allclose( + np.asarray(lognormal.values[period]["alive"]), + np.asarray(normal.values[period]["alive"]), + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + + +@pytest.mark.skipif( + not X64_ENABLED, reason="Income representation parity uses float64." +) +def test_lognormal_fixture_panel_matches_normal_income_representation() -> None: + """A common seed gives the same panel with income expressed in levels.""" + _, lognormal = _solve_process_representation("lognormal") + _, normal = _solve_process_representation("normal") + assert_frame_equal( + lognormal, + normal.assign(income=np.exp(normal["income"])), + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + + @pytest.mark.skipif(not X64_ENABLED, reason="Not working with 32-Bit because of RNG") @pytest.mark.parametrize( "distribution_type", ["uniform", "normal", "lognormal", "tauchen", "rouwenhorst"] @@ -110,7 +206,7 @@ def test_model_with_process(distribution_type): params=params, initial_conditions={ "health": jnp.asarray([0, 0], dtype=jnp.int32), - "income": jnp.asarray([0.0, 0.0]), + "income": jnp.full(2, get_initial_income(distribution_type)), "wealth": jnp.asarray([1.0, 1.0]), "age": jnp.asarray([0.0, 0.0]), "regime_id": jnp.array([RegimeId.alive] * 2), @@ -158,29 +254,74 @@ def test_model_with_process(distribution_type): def _lognormal_solution_reference() -> dict[int, dict[RegimeName, NDArray[np.float64]]]: - """Return the four-period fixture's exact discretized Bellman recurrence. - - Each living grid node affords consumption 2. Uniform health transitions and - unit discounting add the mean flow utility at each earlier living period. - Linear extension of a constant continuation keeps that constant outside the grid. - """ - flow = np.asarray([0.7, 1.0], dtype=np.float64) * np.log(2.0) - expected = { - period: { - "alive": np.broadcast_to( - (flow + (2 - period) * np.mean(flow))[None, :, None], (5, 2, 5) - ) - } - for period in range(3) + """Enumerate actions and shocks independently on income/health/wealth axes.""" + roots, quadrature_weights = np.polynomial.hermite.hermgauss(5) + income_nodes = np.exp(np.sqrt(2.0) * roots) + probabilities = quadrature_weights / np.sqrt(np.pi) + wealth_nodes = np.linspace(1.0, 5.0, 5) + consumption_nodes = np.linspace(0.1, 2.0, 4) + health_weights = (0.7, 1.0) + continuation = np.zeros((5, 2, 5), dtype=np.float64) + expected: dict[int, dict[RegimeName, NDArray[np.float64]]] = { + 3: {"dead": np.asarray(0.0, dtype=np.float64)} } - expected[3] = {"dead": np.asarray(0.0, dtype=np.float64)} + for period in (2, 1, 0): + expected_at_wealth_nodes = np.asarray( + [ + math.fsum( + float(probabilities[income] * continuation[income, health, wealth]) + / 2 + for income in range(5) + for health in range(2) + ) + for wealth in range(5) + ] + ) + values = np.empty_like(continuation) + for income, level in enumerate(income_nodes): + for health, preference in enumerate(health_weights): + for wealth, assets in enumerate(wealth_nodes): + candidates = [] + for consumption in consumption_nodes: + next_wealth = assets - consumption + level + if next_wealth < 0: + continue + following = float( + np.interp( + next_wealth, wealth_nodes, expected_at_wealth_nodes + ) + ) + if next_wealth < wealth_nodes[0]: + following = float( + expected_at_wealth_nodes[0] + + (next_wealth - wealth_nodes[0]) + * ( + expected_at_wealth_nodes[1] + - expected_at_wealth_nodes[0] + ) + ) + elif next_wealth > wealth_nodes[-1]: + following = float( + expected_at_wealth_nodes[-1] + + (next_wealth - wealth_nodes[-1]) + * ( + expected_at_wealth_nodes[-1] + - expected_at_wealth_nodes[-2] + ) + ) + candidates.append( + preference * math.log(float(consumption)) + following + ) + values[income, health, wealth] = max(candidates) + expected[period] = {"alive": values} + continuation = values return expected -@pytest.mark.skipif(not X64_ENABLED, reason="The extreme-tail value bound is float64.") +@pytest.mark.skipif(not X64_ENABLED, reason="The Bellman value bound is float64.") @pytest.mark.coverage(backends=("cpu",), precisions="64") def test_lognormal_values_match_the_discretized_bellman_recurrence() -> None: - """Bound extreme-tail value errors against the analytic Bellman recurrence.""" + """Bound value errors against independent finite-grid backward induction.""" model = get_model(n_periods=4, distribution_type="lognormal") params = get_params("lognormal") np.testing.assert_array_equal(params["alive"]["discount_factor"], 1.0) @@ -212,8 +353,14 @@ def test_lognormal_values_match_the_discretized_bellman_recurrence() -> None: assert consumption_nodes.shape == (4,) assert np.isfinite(income_nodes).all() assert (income_nodes > 0).all() - np.testing.assert_array_equal(np.max(consumption_nodes), 2.0) - assert np.min(wealth_nodes) + np.exp(np.min(income_nodes)) >= 2.0 + np.testing.assert_allclose( + consumption_nodes, + np.linspace(0.1, 2.0, 4), + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + np.testing.assert_array_equal(wealth_nodes, np.linspace(1.0, 5.0, 5)) + assert np.min(wealth_nodes) + np.min(income_nodes) > np.min(consumption_nodes) result = model.solve(params=params, log_level="off") for period, regimes in _lognormal_solution_reference().items(): for regime, expected in regimes.items(): @@ -229,7 +376,7 @@ def test_lognormal_values_match_the_discretized_bellman_recurrence() -> None: @pytest.mark.parametrize( "distribution_type", ["uniform", "normal", "lognormal", "tauchen", "rouwenhorst"] ) -def test_model_with_cross_regime_processes(distribution_type: str) -> None: +def test_model_with_cross_regime_processes(distribution_type: DistributionType) -> None: """Verify cross-regime transitions work when both regimes have process grids. Reproducer for a crash where process-state `lambda: None` stubs leak from the @@ -238,16 +385,16 @@ def test_model_with_cross_regime_processes(distribution_type: str) -> None: """ model = get_multi_regime_model( n_periods=6, - distribution_type=distribution_type, # ty: ignore[invalid-argument-type] + distribution_type=distribution_type, ) - params = get_multi_regime_params(distribution_type) # ty: ignore[invalid-argument-type] + params = get_multi_regime_params(distribution_type) result = model.simulate( log_level="debug", params=params, initial_conditions={ "health": jnp.zeros(2, dtype=jnp.int32), - "income": jnp.zeros(2), + "income": jnp.full(2, get_initial_income(distribution_type)), "wealth": jnp.ones(2), "age": jnp.zeros(2), "regime_id": jnp.full(2, MultiRegimeId.work, dtype=jnp.int32), @@ -1187,7 +1334,7 @@ def observe(**kwargs: Any) -> Any: pixi = shutil.which("pixi") assert pixi is not None completed = subprocess.run( # noqa: S603 - fixed, repository-owned test script - [pixi, "run", "-e", "tests-cpu", "python", "-c", script], + [pixi, "run", "--as-is", "-e", "tests-cpu", "python", "-c", script], cwd=root, env={ **os.environ, diff --git a/tests/test_zero_safe.py b/tests/test_zero_safe.py index b837b363c..1c38c4bfd 100644 --- a/tests/test_zero_safe.py +++ b/tests/test_zero_safe.py @@ -8,18 +8,686 @@ exists to avoid, and a coefficient of order one meeting a value near the top of the range overflows to infinity, which no later scaling recovers. -The downscale is therefore split — as much of it onto the coefficient as the -coefficient has room for while staying normal, the remainder onto the product — -which is what `scaled_weighted_terms` does and what these tests pin. +Each node is therefore formed from normal significands and its exponent is +applied only relative to the largest term of its sum, so a node is lost only +when it is immaterial against that term. These tests pin that at both ends of +the range, against exact rational references. """ +from fractions import Fraction +from typing import Literal + +import jax import jax.numpy as jnp +import numpy as np +import pytest from numpy.testing import assert_allclose +from _lcm.probability import is_live from _lcm.regime_building.zero_safe import zero_safe_average +from _lcm.zero_safe import _largest_selected, scaled_lottery_terms_with_scale +from lcm.certainty_equivalent import LinearExpectation +from lcm.typing import FloatND, IntND from tests.conftest import DECIMAL_PRECISION +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize("route", ["average", "linear"]) +def test_scaled_mean_keeps_zero_on_its_mass_scale( + *, mode: Literal["eager", "jit", "vmap"], route: Literal["average", "linear"] +) -> None: + """Positive mass with zero values stays zero under equivalent weight encodings.""" + dtype = np.dtype(jnp.asarray(1.0).dtype) + tiny = float(np.finfo(dtype).tiny) + smallest = float(np.nextafter(dtype.type(0.0), dtype.type(1.0))) + host_weights = np.asarray( + [ + [tiny / 4, tiny / 4], + [smallest, smallest], + [tiny / 4, tiny / 2], + [tiny / 2, tiny / 4], + [tiny / 4, 0.0], + [tiny, tiny], + [tiny / 4, tiny / 4], + [tiny / 4, tiny / 4], + ], + dtype=dtype, + ) + values = jnp.asarray( + [[0.0, 0.0], [-0.0, -0.0], [0.0, -0.0], [-0.0, 0.0]] * 2, + dtype=dtype, + ) + weights = jnp.asarray(host_weights) + shifts = jnp.asarray([[0, 0]] * 5 + [[2, 2], [-7, -7], [7, 7]], dtype=jnp.int32) + np.testing.assert_array_equal(is_live(weights), host_weights > 0) + + def average(*, values: FloatND, weights: FloatND, shifts: IntND) -> FloatND: + if route == "linear": + return LinearExpectation().aggregate_scaled( + values=values, coefficients=weights, shifts=shifts, params={} + ) + return zero_safe_average(a=values, weights=weights, shifts=shifts, axis=-1) + + evaluate = average + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + actual = evaluate(values=values, weights=weights, shifts=shifts) + expected = [ + _scaled_mean_reference( + values=tuple(float(v) for v in row), + weights=tuple(float(w) for w in mass), + shifts=tuple(int(s) for s in scale), + )[0] + for row, mass, scale in zip( + np.asarray(values), host_weights, np.asarray(shifts), strict=True + ) + ] + np.testing.assert_array_equal(actual, np.asarray(expected, dtype=dtype)) + + +@pytest.mark.parametrize("enable_jit", [False, True]) +def test_selected_exponents_keep_the_full_integer_range(*, enable_jit: bool) -> None: + """A real minimum exponent is distinct from a row with no selected entry.""" + exponents = jnp.asarray( + [[-(2**30) - 1, 0], [-(2**30), 0], [np.iinfo(np.int32).min, 0], [1, 2]], + dtype=jnp.int32, + ) + selected = jnp.asarray([[True, False]] * 3 + [[False, False]]) + evaluate = jax.jit(_largest_selected) if enable_jit else _largest_selected + actual = evaluate(selected=selected, exponents=exponents) + expected = np.asarray( + [[-(2**30) - 1], [-(2**30)], [np.iinfo(np.int32).min], [0]], dtype=np.int32 + ) + np.testing.assert_array_equal(actual, expected) + + +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize("sign", [-1, 1]) +def test_scaled_mean_preserves_a_constant_at_the_finite_limit( + *, mode: str, sign: int +) -> None: + """Unequal normal weights retain a constant at either finite endpoint.""" + dtype = np.dtype(jnp.asarray(1.0).dtype) + maximum = float(np.finfo(dtype).max) + values = jnp.asarray([sign * maximum, sign * maximum], dtype=dtype) + coefficients = jnp.asarray([1.0, 1.0 + np.finfo(dtype).eps], dtype=dtype) + + def average(*, values: FloatND, coefficients: FloatND) -> FloatND: + return zero_safe_average( + a=values, weights=coefficients, shifts=jnp.zeros(2, dtype=jnp.int32) + ) + + evaluate = average + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + values = jnp.stack([values] * 2) + coefficients = jnp.stack([coefficients] * 2) + actual = np.asarray(evaluate(values=values, coefficients=coefficients)) + expected, _, _ = _scaled_mean_reference( + values=(sign * maximum, sign * maximum), + weights=(1.0, float(coefficients.reshape(-1)[1])), + shifts=(0, 0), + ) + np.testing.assert_array_equal(actual, np.full(actual.shape, expected, dtype=dtype)) + + +def _scaled_mean_reference( + *, values: tuple[float, ...], weights: tuple[float, ...], shifts: tuple[int, ...] +) -> tuple[float, tuple[float, ...], tuple[float, ...]]: + """Evaluate the mean and its derivatives with exact represented-input rationals.""" + factors = tuple(Fraction(2) ** -shift for shift in shifts) + probabilities = tuple( + Fraction(weight) * factor + for weight, factor in zip(weights, factors, strict=True) + ) + mass = sum(probabilities, Fraction()) + mean = ( + sum( + (p * Fraction(v) for p, v in zip(probabilities, values, strict=True)), + Fraction(), + ) + / mass + ) + weight_slopes = tuple( + float(factor * (Fraction(value) - mean) / mass) + for factor, value in zip(factors, values, strict=True) + ) + return float(mean), weight_slopes, tuple(float(p / mass) for p in probabilities) + + +def _get_tiny_level_derivative_specimen( + *, case: str +) -> tuple[ + tuple[float, ...], + tuple[float, ...], + tuple[int, ...], + tuple[float, ...], + tuple[float, ...], +]: + """Construct normal live values and exact normalized derivative references.""" + dtype = np.dtype(jnp.asarray(1.0).dtype) + tiny = float(np.finfo(dtype).tiny) + level = float(np.ldexp(dtype.type(tiny), np.finfo(dtype).nmant - 2)) + upper = float(np.nextafter(dtype.type(level), dtype.type(np.inf))) + values, coefficients, shifts = (level, upper), (tiny, tiny), (0, 0) + if case in {"unequal", "permuted"}: + coefficients = (tiny, 2 * tiny) + if case == "negative": + values = (-level, -upper) + elif case == "permuted": + values, coefficients = values[::-1], coefficients[::-1] + elif case == "shifted": + shifts = (7, 7) + elif case == "dead_finite": + values, coefficients, shifts = ( + (*values, 0.0), + (*coefficients, 0.0), + (*shifts, 0), + ) + # Only finite values enter the independent rational oracle. The null-event + # nonfinite coefficient partial follows the kernel's explicit zero convention. + _, expected_coefficients, expected_values = _scaled_mean_reference( + values=values, weights=coefficients, shifts=shifts + ) + if case == "dead_nonfinite": + values, coefficients, shifts = ( + (*values, -np.inf), + (*coefficients, 0.0), + (*shifts, 0), + ) + expected_coefficients = (*expected_coefficients, 0.0) + expected_values = (*expected_values, 0.0) + return values, coefficients, shifts, expected_coefficients, expected_values + + +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize( + "case", + [ + "zero", + "positive", + "negative", + "opposite", + "dominant", + "permuted", + "shifted", + "midpoint", + "unequal", + "adjacent_negative", + "adjacent_permuted", + "half_scale", + "sixteenth_scale", + "equivalent_pairs", + "common_shift", + "three_nodes", + "five_nodes", + "tiny_coefficient_adjacent", + "tiny_coefficient_unequal", + "tiny_coefficient_cancelled", + "tiny_coefficient_multinode", + "tiny_coefficient_rare_large", + ], +) +def test_scaled_mean_normalizes_finite_slopes_before_tangent_arithmetic( + *, mode: str, case: str +) -> None: + """Finite normalized derivatives survive extreme levels and opposite-sign gaps.""" + dtype = np.dtype(jnp.asarray(1.0).dtype) + peak = float(np.finfo(dtype).max) + lower = float(np.nextafter(dtype.type(peak), dtype.type(0))) + third = float(np.nextafter(dtype.type(lower), dtype.type(0))) + tiny = float(np.finfo(dtype).tiny) + tiny_level = 1.0 + tiny_upper = float(np.nextafter(dtype.type(tiny_level), dtype.type(np.inf))) + tiny_third = float(np.nextafter(dtype.type(tiny_upper), dtype.type(np.inf))) + rare_shift = int(2 * np.finfo(dtype).maxexp + 2) + specimens = { + "zero": ((peak, peak / 2), (1.0, 0.0), (0, 0)), + "positive": ((peak, peak / 2), (1.0, 0.5), (0, 0)), + "negative": ((-peak, -peak / 2), (1.0, 0.0), (0, 0)), + "opposite": ((peak, -peak), (1.0, 2.0), (0, 0)), + "dominant": ((peak, -peak), (3.0, 1.0), (0, 0)), + "permuted": ((peak / 2, peak), (0.0, 1.0), (0, 0)), + "shifted": ((peak, peak / 2), (1.0, 0.0), (7, 7)), + "midpoint": ((peak, lower), (1.0, 1.0), (1, 1)), + "unequal": ((peak, lower), (1.0, 3.0), (2, 2)), + "adjacent_negative": ((-peak, -lower), (1.0, 1.0), (1, 1)), + "adjacent_permuted": ((lower, peak), (3.0, 1.0), (2, 2)), + "half_scale": ((peak / 2, lower / 2), (1.0, 1.0), (1, 1)), + "sixteenth_scale": ((peak / 16, lower / 16), (1.0, 3.0), (2, 2)), + "equivalent_pairs": ((peak, lower), (2.0, 2.0), (2, 2)), + "common_shift": ((peak, lower), (1.0, 3.0), (9, 9)), + "three_nodes": ((peak, lower, third), (1.0, 3.0, 2.0), (1, 1, 1)), + "tiny_coefficient_adjacent": ((tiny_level, tiny_upper), (tiny, tiny), (0, 0)), + "tiny_coefficient_unequal": ( + (tiny_level, tiny_upper), + (tiny, 2 * tiny), + (0, 0), + ), + "tiny_coefficient_cancelled": ( + (tiny_level, tiny_upper, tiny_third), + (tiny, 2 * tiny, tiny), + (0, 0, 0), + ), + "tiny_coefficient_multinode": ( + (tiny_level, tiny_upper, tiny_third), + (tiny, 2 * tiny, 3 * tiny), + (0, 0, 0), + ), + "tiny_coefficient_rare_large": ( + (tiny_level, tiny_upper, peak), + (tiny, tiny, tiny), + (0, 0, rare_shift), + ), + "five_nodes": ( + (peak, lower, third, lower, peak), + (1.0, 3.0, 2.0, 4.0, 2.0), + (1, 1, 1, 1, 1), + ), + } + values, weights, shifts = specimens[case] + expected_mean, expected_weights, expected_values = _scaled_mean_reference( + values=values, weights=weights, shifts=shifts + ) + scales = jnp.asarray(shifts, dtype=jnp.int32) + + def derivatives( + *, values: FloatND, coefficients: FloatND + ) -> tuple[FloatND, FloatND, FloatND]: + def weight_function(weight: FloatND) -> FloatND: + return zero_safe_average(a=values, weights=weight, shifts=scales) + + def value_function(value: FloatND) -> FloatND: + return zero_safe_average(a=value, weights=coefficients, shifts=scales) + + return ( + jax.grad(weight_function)(coefficients), + jax.jacfwd(weight_function)(coefficients), + jax.grad(value_function)(values), + ) + + evaluate = derivatives + value_array, weight_array = jnp.asarray(values), jnp.asarray(weights) + assert np.isfinite(np.asarray(value_array)).all() + assert not np.array_equal(value_array[0], value_array[1]) + assert_allclose( + zero_safe_average(a=value_array, weights=weight_array, shifts=scales), + expected_mean, + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + value_array = jnp.stack([value_array, value_array]) + weight_array = jnp.stack([weight_array, weight_array]) + actual_weights, actual_forward, actual_values = evaluate( + values=value_array, coefficients=weight_array + ) + expected_weight_array = np.asarray(expected_weights) + # The exact probability can lie below the active format's range. + expected_value_array = np.asarray(expected_values, dtype=value_array.dtype) + if mode == "vmap": + expected_weight_array = np.stack([expected_weight_array] * 2) + expected_value_array = np.stack([expected_value_array] * 2) + for actual in (actual_weights, actual_forward): + assert_allclose( + actual, + expected_weight_array, + rtol=10.0**-DECIMAL_PRECISION, + atol=10.0**-DECIMAL_PRECISION, + ) + assert_allclose(actual_values, expected_value_array, rtol=10.0**-DECIMAL_PRECISION) + + +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize( + "case", + [ + "equal", + "unequal", + "negative", + "permuted", + "shifted", + "dead_finite", + "dead_nonfinite", + ], +) +def test_scaled_mean_retains_partials_below_its_numerator_range( + *, mode: str, case: str +) -> None: + """Local finite partials retain value spacing despite a tiny raw numerator.""" + values, coefficients, shifts, expected_coefficients, expected_values = ( + _get_tiny_level_derivative_specimen(case=case) + ) + dtype = np.dtype(jnp.asarray(1.0).dtype) + scales = jnp.asarray(shifts, dtype=jnp.int32) + + def derivatives( + *, values: FloatND, coefficients: FloatND + ) -> tuple[FloatND, FloatND, FloatND]: + def average(weight: FloatND) -> FloatND: + return zero_safe_average(a=values, weights=weight, shifts=scales) + + def value_average(value: FloatND) -> FloatND: + return zero_safe_average(a=value, weights=coefficients, shifts=scales) + + return ( + jax.grad(average)(coefficients), + jax.jacfwd(average)(coefficients), + jax.grad(value_average)(values), + ) + + value_array, coefficient_array = jnp.asarray(values), jnp.asarray(coefficients) + assert np.isfinite(np.asarray(value_array[:2])).all() + assert not np.array_equal(value_array[0], value_array[1]) + evaluate = derivatives + expected_coefficient_array = np.asarray(expected_coefficients, dtype=dtype) + expected_value_array = np.asarray(expected_values, dtype=dtype) + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + value_array = jnp.stack([value_array, value_array]) + coefficient_array = jnp.stack([coefficient_array, coefficient_array]) + expected_coefficient_array = np.stack([expected_coefficient_array] * 2) + expected_value_array = np.stack([expected_value_array] * 2) + reverse, forward, value_partials = evaluate( + values=value_array, coefficients=coefficient_array + ) + for actual in (reverse, forward): + assert_allclose( + actual, expected_coefficient_array, rtol=10.0**-DECIMAL_PRECISION, atol=0 + ) + assert_allclose( + value_partials, expected_value_array, rtol=10.0**-DECIMAL_PRECISION, atol=0 + ) + + +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize("coefficient_factor", [0.5, 1.0, 2.0, 1048576.0]) +@pytest.mark.parametrize( + "case", + [ + "equal", + "unequal", + "negative", + "permuted", + "shifted", + "dead_finite", + "dead_nonfinite", + ], +) +def test_scaled_mean_preserves_small_values_and_partials( + *, mode: str, coefficient_factor: float, case: str +) -> None: + """Coefficient magnitude cannot erase a normal normalized mean.""" + values, coefficients, shifts, _, _ = _get_tiny_level_derivative_specimen(case=case) + coefficients = tuple(c * coefficient_factor for c in coefficients) + finite_nodes = tuple(i for i, value in enumerate(values) if np.isfinite(value)) + expected_mean, expected_coefficients, expected_values = _scaled_mean_reference( + values=tuple(values[i] for i in finite_nodes), + weights=tuple(coefficients[i] for i in finite_nodes), + shifts=tuple(shifts[i] for i in finite_nodes), + ) + if case == "dead_nonfinite": + expected_coefficients = (*expected_coefficients, 0.0) + expected_values = (*expected_values, 0.0) + dtype = np.dtype(jnp.asarray(1.0).dtype) + scales = jnp.asarray(shifts, dtype=jnp.int32) + + def mean_and_derivatives( + *, values: FloatND, coefficients: FloatND + ) -> tuple[FloatND, FloatND, FloatND, FloatND]: + def average(weight: FloatND) -> FloatND: + return zero_safe_average(a=values, weights=weight, shifts=scales) + + def value_average(value: FloatND) -> FloatND: + return zero_safe_average(a=value, weights=coefficients, shifts=scales) + + return ( + average(coefficients), + jax.grad(average)(coefficients), + jax.jacfwd(average)(coefficients), + jax.grad(value_average)(values), + ) + + operands = { + "values": jnp.asarray(values), + "coefficients": jnp.asarray(coefficients), + } + expected = ( + np.asarray(expected_mean, dtype=dtype), + np.asarray(expected_coefficients, dtype=dtype), + np.asarray(expected_coefficients, dtype=dtype), + np.asarray(expected_values, dtype=dtype), + ) + assert abs(expected_mean) >= np.finfo(dtype).tiny + evaluate = mean_and_derivatives + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + operands = {name: jnp.stack([value, value]) for name, value in operands.items()} + expected = tuple(np.stack([value, value]) for value in expected) + for actual, reference in zip(evaluate(**operands), expected, strict=True): + assert_allclose(actual, reference, rtol=10.0**-DECIMAL_PRECISION, atol=0) + + +@pytest.mark.parametrize("enable_jit", [False, True]) +@pytest.mark.parametrize("common_shift", [-(2**31), 2**31 - 1]) +def test_small_scaled_mean_ignores_common_shift_gauge( + *, enable_jit: bool, common_shift: int +) -> None: + """Common endpoint offsets cancel before coefficient exponent arithmetic.""" + values, coefficients, _, _, _ = _get_tiny_level_derivative_specimen(case="unequal") + expected, slopes, _ = _scaled_mean_reference( + values=values, weights=coefficients, shifts=(0, 0) + ) + shifts = jnp.full(2, common_shift, dtype=jnp.int32) + value_array = jnp.asarray(values) + + def average(weight: FloatND) -> FloatND: + return zero_safe_average(a=value_array, weights=weight, shifts=shifts) + + evaluate = jax.value_and_grad(average) + if enable_jit: + evaluate = jax.jit(evaluate) + mean, actual_slopes = evaluate(jnp.asarray(coefficients)) + assert_allclose(mean, expected, rtol=10.0**-DECIMAL_PRECISION, atol=0) + assert_allclose(actual_slopes, slopes, rtol=10.0**-DECIMAL_PRECISION, atol=0) + + +@pytest.mark.parametrize("enable_jit", [False, True]) +@pytest.mark.parametrize("dead_shift", [-(2**31), 2**31 - 1]) +def test_zero_weight_extreme_shift_keeps_a_zero_finite_right_partial( + *, enable_jit: bool, dead_shift: int +) -> None: + """A finite null node equal to the mean has exactly zero weight slope.""" + dtype = jnp.asarray(1.0).dtype + tiny = jnp.finfo(dtype).tiny + level = jnp.asarray(tiny * 2.0 ** (jnp.finfo(dtype).nmant - 2), dtype=dtype) + values = jnp.full(3, level) + shifts = jnp.asarray([0, 0, dead_shift], dtype=jnp.int32) + + def average(weight: FloatND) -> FloatND: + return zero_safe_average(a=values, weights=weight, shifts=shifts) + + evaluate = jax.value_and_grad(average) + if enable_jit: + evaluate = jax.jit(evaluate) + mean, slopes = evaluate(jnp.asarray([tiny, tiny, 0.0], dtype=dtype)) + assert_allclose(mean, level, rtol=10.0**-DECIMAL_PRECISION, atol=0) + assert_allclose(slopes, np.zeros(3), rtol=0, atol=0) + + +@pytest.mark.parametrize("enable_jit", [False, True]) +@pytest.mark.parametrize("coefficient_factor", [0.5, 1.0, 2.0, 1048576.0]) +def test_normalized_lottery_terms_keep_the_physical_returned_scale( + *, enable_jit: bool, coefficient_factor: float +) -> None: + """The helper scale reconstructs the original represented-input measure.""" + + values, coefficients, _, _, _ = _get_tiny_level_derivative_specimen(case="unequal") + coefficients = tuple(c * coefficient_factor for c in coefficients) + shifts = (0, 3) + evaluate = scaled_lottery_terms_with_scale + if enable_jit: + evaluate = jax.jit(evaluate) + terms, masses, common_scale = evaluate( + values=jnp.asarray(values), + coefficients=jnp.asarray(coefficients), + shifts=jnp.asarray(shifts, dtype=jnp.int32), + ) + scale = int(np.asarray(common_scale).item()) + expected_masses = tuple( + Fraction(c) * Fraction(2) ** (scale - shift) + for c, shift in zip(coefficients, shifts, strict=True) + ) + expected_terms = tuple( + mass * Fraction(v) for mass, v in zip(expected_masses, values, strict=True) + ) + dtype = np.dtype(jnp.asarray(1.0).dtype) + assert_allclose( + masses, + np.asarray(tuple(map(float, expected_masses)), dtype=dtype), + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + assert_allclose( + terms, + np.asarray(tuple(map(float, expected_terms)), dtype=dtype), + rtol=10.0**-DECIMAL_PRECISION, + atol=0, + ) + + +@pytest.mark.parametrize("enable_jit", [False, True], ids=["eager", "jit"]) +def test_unperturbed_coefficients_do_not_poison_finite_value_derivatives( + *, + enable_jit: bool, +) -> None: + """Value-only AD ignores an unperturbed, out-of-format coefficient partial.""" + peak = jnp.finfo(jnp.asarray(1.0).dtype).max + values = jnp.asarray([peak, -peak]) + weights = jnp.asarray([1.0, 0.0]) + shifts = jnp.zeros(2, dtype=jnp.int32) + + def average(value: FloatND) -> FloatND: + return zero_safe_average(a=value, weights=weights, shifts=shifts) + + def forward(value: FloatND) -> FloatND: + return jax.jvp(average, (value,), (jnp.ones_like(value),))[1] + + gradient = jax.grad(average) + evaluate_forward = forward + if enable_jit: + gradient, evaluate_forward = jax.jit(gradient), jax.jit(evaluate_forward) + assert_allclose(gradient(values), np.asarray([1.0, 0.0]), rtol=0, atol=0) + assert_allclose(evaluate_forward(values), 1.0, rtol=0, atol=0) + + +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +@pytest.mark.parametrize("multiple", [1.0, 1.25, 1.5, 1.75, 2.0]) +def test_rare_large_value_keeps_a_normal_small_mean( + *, mode: str, multiple: float +) -> None: + """A negligible large tail does not downscale the dominant normal contribution.""" + dtype = np.dtype(jnp.asarray(1.0).dtype) + tiny = float(np.finfo(dtype).tiny) + values = (multiple * tiny, float(np.finfo(dtype).max)) + weights = (1.0, tiny) + shifts = ( + 0, + 3 * (800 if dtype.itemsize == 8 else 100) + int(np.finfo(dtype).minexp), + ) + expected, _, _ = _scaled_mean_reference( + values=values, weights=weights, shifts=shifts + ) + + def average(*, values: FloatND, coefficients: FloatND) -> FloatND: + return zero_safe_average( + a=values, weights=coefficients, shifts=jnp.asarray(shifts, dtype=jnp.int32) + ) + + evaluate = average + value_array, weight_array = jnp.asarray(values), jnp.asarray(weights) + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + value_array = jnp.stack([value_array] * 2) + weight_array = jnp.stack([weight_array] * 2) + actual = evaluate(values=value_array, coefficients=weight_array) + assert_allclose(actual, expected, rtol=10.0**-DECIMAL_PRECISION, atol=0) + + +@pytest.mark.parametrize("weights", [(0.0, 1.0), (1.0, 2.0)]) +@pytest.mark.parametrize("enable_jit", [False, True], ids=["eager", "jit"]) +def test_scaled_average_preserves_weight_and_value_derivatives( + *, weights: tuple[float, float], enable_jit: bool +) -> None: + """Finite nodes retain their weight derivative even at zero probability.""" + values = jnp.asarray([2.0, 4.0]) + coefficients = jnp.asarray(weights) + shifts = jnp.zeros(2, dtype=jnp.int32) + weight_gradient = jax.grad( + lambda weight: zero_safe_average(a=values, weights=weight, shifts=shifts) + ) + value_gradient = jax.grad( + lambda value: zero_safe_average(a=value, weights=coefficients, shifts=shifts) + ) + if enable_jit: + weight_gradient = jax.jit(weight_gradient) + value_gradient = jax.jit(value_gradient) + total = jnp.sum(coefficients) + expected = jnp.sum(coefficients * values) / total + + assert_allclose( + weight_gradient(coefficients), + (values - expected) / total, + rtol=10.0**-DECIMAL_PRECISION, + atol=10.0**-DECIMAL_PRECISION, + ) + assert_allclose( + value_gradient(values), coefficients / total, rtol=10.0**-DECIMAL_PRECISION + ) + + +@pytest.mark.parametrize("axis", [None, 0, -1]) +@pytest.mark.parametrize("sign", [-1.0, 1.0]) +@pytest.mark.parametrize("enable_jit", [False, True], ids=["eager", "jit"]) +def test_scaled_average_keeps_a_finite_mean_when_its_numerator_overflows( + *, axis: int | None, sign: float, enable_jit: bool +) -> None: + """Large same-sign values have a finite mean, and dead infinities drop out.""" + peak = jnp.finfo(jnp.asarray(1.0).dtype).max + values = jnp.asarray([sign * peak, sign * (peak / 2), -jnp.inf]) + expected = sign * (peak * 0.75) + if axis is not None: + values = jnp.stack([values, values / 2], axis=1 if axis == 0 else 0) + expected = jnp.asarray([expected, expected / 2]) + average = ( + jax.jit(zero_safe_average, static_argnames="axis") + if enable_jit + else zero_safe_average + ) + + result = average( + a=values, + weights=jnp.asarray([1.0, 1.0, 0.0]), + shifts=jnp.zeros(3, dtype=jnp.int32), + axis=axis, + ) + + assert_allclose(result, expected, rtol=10.0**-DECIMAL_PRECISION) + + def test_zero_safe_average_prices_a_downscaled_node_against_a_near_max_value(): """A node whose scale keeps it in range is priced, not sent to infinity. @@ -62,3 +730,113 @@ def test_zero_safe_average_prices_a_downscaled_node_along_a_reduced_axis(): jnp.asarray([largest / 2, largest / 8]), rtol=10.0**-DECIMAL_PRECISION, ) + + +def _get_floor_level_lotteries() -> tuple[ + tuple[tuple[float, float], tuple[float, float], tuple[int, int]], ... +]: + """Construct two-node lotteries whose values sit at the bottom of the normal range. + + Every value, every live coefficient and every mean is normal, and no lottery + cancels. The coefficients are unequal ordinary weights, probability rows, + equivalent scaled encodings and coefficients near the smallest normal, each + with its sign, permutation and common-shift variants. + """ + tiny = float(np.finfo(jnp.asarray(1.0).dtype).tiny) + value_pairs = ( + (1.5 * tiny, 1.5 * tiny), + (1.75 * tiny, 1.75 * tiny), + (2 * tiny, 1.5 * tiny), + ) + weightings = ( + ((1.0, 0.5), (0, 0)), + ((1.0, 0.25), (0, 0)), + ((0.75, 0.25), (0, 0)), + ((0.75, 0.5), (0, 1)), + ((1.0, 1.0), (0, 1)), + ((2 * tiny, tiny), (0, 0)), + ((4 * tiny, tiny), (0, 0)), + ((4 * tiny, 4 * tiny), (1, 2)), + ) + lotteries = [] + for values in value_pairs: + for coefficients, shifts in weightings: + lotteries.extend( + [ + (values, coefficients, shifts), + ((-values[0], -values[1]), coefficients, shifts), + (values[::-1], coefficients[::-1], shifts[::-1]), + (values, coefficients, (shifts[0] + 7, shifts[1] + 7)), + (values, coefficients, (shifts[0] - 7, shifts[1] - 7)), + ] + ) + return tuple(lotteries) + + +@pytest.mark.parametrize("quantity", ["mean", "value_partials", "weight_partials"]) +@pytest.mark.parametrize("mode", ["eager", "jit", "vmap"]) +def test_scaled_mean_keeps_floor_level_nodes_against_unequal_weights( + *, mode: str, quantity: str +) -> None: + """A normal mean of floor-level values keeps every node's weighted contribution.""" + lotteries = _get_floor_level_lotteries() + values = jnp.asarray([lottery[0] for lottery in lotteries]) + coefficients = jnp.asarray([lottery[1] for lottery in lotteries]) + shifts = jnp.asarray([lottery[2] for lottery in lotteries], dtype=jnp.int32) + + def mean_and_partials( + *, values: FloatND, coefficients: FloatND, shifts: IntND + ) -> tuple[FloatND, FloatND, FloatND]: + def value_average(value: FloatND) -> FloatND: + return zero_safe_average( + a=value, weights=coefficients, shifts=shifts, axis=-1 + ) + + def weight_average(weight: FloatND) -> FloatND: + return zero_safe_average(a=values, weights=weight, shifts=shifts, axis=-1) + + if values.ndim == 1: + return ( + value_average(values), + jax.jacfwd(value_average)(values), + jax.grad(weight_average)(coefficients), + ) + # Rows are independent lotteries, so each row's partials are the + # diagonal blocks of the batched Jacobian. + return ( + value_average(values), + jnp.einsum("iij->ij", jax.jacfwd(value_average)(values)), + jnp.einsum("iij->ij", jax.jacfwd(weight_average)(coefficients)), + ) + + evaluate = mean_and_partials + if mode == "jit": + evaluate = jax.jit(evaluate) + elif mode == "vmap": + evaluate = jax.jit(jax.vmap(evaluate)) + results = evaluate(values=values, coefficients=coefficients, shifts=shifts) + index = ("mean", "value_partials", "weight_partials").index(quantity) + actual = np.asarray(results[index]) + + tolerance = Fraction(10) ** -DECIMAL_PRECISION + # A partial below the normal range is not representable on a flushing + # backend, so it may come back as zero; every other quantity is relative. + tiny = Fraction(float(np.finfo(actual.dtype).tiny)) + worst = Fraction() + for row, (v, c, s) in zip(actual, lotteries, strict=True): + mean, weight_partials, value_partials = _scaled_mean_reference( + values=tuple(float(x) for x in np.asarray(v, dtype=actual.dtype)), + weights=tuple(float(x) for x in np.asarray(c, dtype=actual.dtype)), + shifts=s, + ) + expected = { + "mean": (mean,), + "value_partials": value_partials, + "weight_partials": weight_partials, + }[quantity] + for observed, exact in zip(np.atleast_1d(row), expected, strict=True): + error = abs(Fraction(float(observed)) - Fraction(exact)) + if abs(Fraction(exact)) < tiny: + error = max(error - tiny, Fraction()) + worst = max(worst, error / abs(Fraction(exact)) if exact else error) + assert worst <= tolerance