From 9d509d39c8025e7d1b615b5588e67a00f4072e38 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:22:18 +0400 Subject: [PATCH 1/8] Free the SPI imputation's fitted forests before each later fit The UK SPI income imputation kept its stage-1 model and every reference fold's model referenced until it returned, while stage 2 fitted 38 targets at once. It now keeps only the receipts it reports from those models, frees each reference fold's forests before the next fold, frees the stage-1 forests after their draw, and fits and draws stage 2 one target at a time through the QRF chain. The person table and every receipt stay byte-identical. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/uk_runtime/spi_income.py | 186 ++++-- .../build/uk_runtime/spi_rank_transport.py | 3 + .../uk/test_uk_spi_forest_release.py | 311 +++++++++ .../tests/engine_free/uk/test_uk_spi_spine.py | 3 +- .../microcosm_build/uk_spi_forest_release.py | 594 ++++++++++++++++++ test_support/microcosm_build/uk_spi_income.py | 89 ++- 6 files changed, 1135 insertions(+), 51 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py create mode 100644 test_support/microcosm_build/uk_spi_forest_release.py diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py index c4dd0fb27c..ab433a1647 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py @@ -1176,6 +1176,81 @@ class UKSPIIncomeImputationResult: gate_levels: Mapping[str, object] | None = None +@dataclass(frozen=True) +class _FitGateEvidence: + """What the stage's receipts read from one fitted QRF, without its forests. + + A fitted model holds every target's forests, so the stage keeps this in + its place once it has finished drawing from the model. The methods are the + ones :mod:`~microcosm.build.uk_runtime.qrf_gates` reads from a fitted model. + """ + + weight_kind: str + outcomes: Mapping[str, str | None] + levels: Mapping[str, tuple[str, ...]] + level_reports: Mapping[str, dict[str, object]] + + def gate_outcomes(self) -> dict[str, str | None]: + return dict(self.outcomes) + + def gate_levels(self) -> dict[str, tuple[str, ...]]: + return dict(self.levels) + + def gate_level_reports(self) -> dict[str, dict[str, object]]: + return {name: dict(report) for name, report in self.level_reports.items()} + + +def _fit_gate_evidence( + fitted: Any, *, read_outcomes: bool, read_levels: bool +) -> _FitGateEvidence: + """Read a fitted QRF's receipts, only those this run's result reports.""" + + level_reports = getattr(fitted, "gate_level_reports", None) + return _FitGateEvidence( + weight_kind=fitted.weight_kind, + outcomes=fitted.gate_outcomes() if read_outcomes else {}, + levels=fitted.gate_levels() if read_levels else {}, + level_reports=( + level_reports() if read_levels and level_reports is not None else {} + ), + ) + + +def _fit_draw_stage2_target( + model: Any, + frame: Frame, + recipients: pd.DataFrame, + prior_draws: pd.DataFrame, + *, + state: Any, + quantiles: np.ndarray, + sign_uniforms: np.ndarray, + groups: np.ndarray, + read_gate_outcomes: bool, +) -> tuple[Any, np.ndarray, dict[str, str]]: + """Fit and draw the chain's next stage-2 target. + + Returns the next chain state, the draw and the target's gate outcome. The + step result holds the target's forests, so returning without it frees them + before the next target is fitted. + """ + + step = model.fit_draw_next( + frame, + recipients, + prior_draws, + state=state, + weights="importance", + quantiles=quantiles, + sign_uniforms=sign_uniforms, + groups=groups, + ) + outcomes = ( + gate_outcomes(FRS_ONLY_FIT_NAME, step.fitted) if read_gate_outcomes else {} + ) + return step.state, step.raw_draw, outcomes + + @dataclass(frozen=True) class _SPIDonorFingerprint: """Stable-file identity binding a reviewed hash to the parsed donor bytes.""" @@ -1591,6 +1666,10 @@ def impute_uk_spi_income_support( stage1_level_kwargs = ( {"gate_level_columns": stage1_level_columns} if stage1_level_columns else {} ) + # The receipts this run reports, read from each model before it is freed. + read_stage1_gate_outcomes = stage1_gate_calibration != UK_DEFAULT_GATE_CALIBRATION + read_stage2_gate_outcomes = stage2_gate_calibration != UK_DEFAULT_GATE_CALIBRATION + read_stage1_gate_levels = bool(stage1_level_columns) qrf_cls = _qrf_class() stage1 = qrf_cls( n_estimators=n_estimators, @@ -1613,8 +1692,9 @@ def impute_uk_spi_income_support( assert_analogue_map_covers(SPI_INCOME_QRF_OUTPUT_COLUMNS) reference_weights = training_weights.loc[reference_people] reference_targets = list(analogue_targets(SPI_INCOME_QRF_OUTPUT_COLUMNS)) - reference_weight_kind: dict[str, str] = {} - reference_fits: list[Any] = [] + # One entry per fold; the fold's forests are freed once it has located its + # recipients. + reference_evidence: list[_FitGateEvidence] = [] def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): frame = _person_fit_frame( @@ -1635,8 +1715,13 @@ def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): weights="importance", groups=person.loc[encoded.index, "person_household_id"].to_numpy(), ) - reference_weight_kind.setdefault("kind", fitted.weight_kind) - reference_fits.append(fitted) + reference_evidence.append( + _fit_gate_evidence( + fitted, + read_outcomes=read_stage1_gate_outcomes, + read_levels=read_stage1_gate_levels, + ) + ) return fitted training_folds, used_folds = cell_fold_ids( @@ -1683,6 +1768,14 @@ def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): quantiles=transport.quantiles, sign_uniforms=transport.sign_uniforms, ) + # Nothing draws from the stage-1 forests again, so they are freed before + # stage 2 is fitted. + stage1_evidence = _fit_gate_evidence( + stage1, + read_outcomes=read_stage1_gate_outcomes, + read_levels=read_stage1_gate_levels, + ) + del stage1 _validate_predictions( stage1_draws, expected=SPI_INCOME_QRF_OUTPUT_COLUMNS, @@ -1862,42 +1955,47 @@ def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): ) # Stage 2 deliberately derives a distinct RNG stream from the single # reviewed stage seed; changing this edits the derivation convention. - stage2 = qrf_cls( + stage2_model = qrf_cls( n_estimators=n_estimators, seed=seed + 1, gate_calibration=stage2_gate_calibration, - ).fit( + ) + stage2_groups = training_person["person_household_id"].to_numpy() + # The chain fits and draws one target at a time, so one target's forests + # are in memory at once. Its fit stream and each target's conditioning are + # those of one fit over every target followed by predict_from_uniforms. + stage2_state = stage2_model.start_chain( stage2_frame, list(encoded_train.columns), list(stage2_outputs), weights="importance", - groups=training_person["person_household_id"].to_numpy(), + groups=stage2_groups, ) + stage2_weight_kind = stage2_state.weight_kind stage2_keys = integer_record_keys( person.loc[spi_age_domain, "person_id"].to_numpy(), label="SPI stage-2 person_id", ) - stage2_draws = stage2.predict_from_uniforms( - encoded_target, - quantiles={ - target: stable_identity_uniforms( - stage2_keys, - seed=seed + 1, - salt=f"{FRS_ONLY_FIT_NAME}:{_STAGE2_SALT_NAMES.get(target, target)}", - ) - for target in stage2_outputs - }, - sign_uniforms={ - target: stable_identity_uniforms( - stage2_keys, - seed=seed + 1, - salt=( - f"{FRS_ONLY_FIT_NAME}:{_STAGE2_SALT_NAMES.get(target, target)}:sign" - ), - ) - for target in stage2_outputs - }, - ) + stage2_draws = pd.DataFrame(index=encoded_target.index) + stage2_gate_outcomes: dict[str, str] = {} + while not stage2_state.is_complete: + target = stage2_state.next_target + salt = f"{FRS_ONLY_FIT_NAME}:{_STAGE2_SALT_NAMES.get(target, target)}" + stage2_state, stage2_draw, target_gate_outcomes = _fit_draw_stage2_target( + stage2_model, + stage2_frame, + encoded_target, + stage2_draws, + state=stage2_state, + quantiles=stable_identity_uniforms(stage2_keys, seed=seed + 1, salt=salt), + sign_uniforms=stable_identity_uniforms( + stage2_keys, seed=seed + 1, salt=f"{salt}:sign" + ), + groups=stage2_groups, + read_gate_outcomes=read_stage2_gate_outcomes, + ) + stage2_draws[target] = stage2_draw + stage2_gate_outcomes.update(target_gate_outcomes) _validate_predictions( stage2_draws, expected=stage2_outputs, @@ -1961,9 +2059,9 @@ def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): return UKSPIIncomeImputationResult( person=person, fit_weight_records=( - FitWeightRecord(SPI_DONOR_FIT_NAME, stage1.weight_kind), - FitWeightRecord(SPI_TRANSPORT_FIT_NAME, reference_weight_kind["kind"]), - FitWeightRecord(FRS_ONLY_FIT_NAME, stage2.weight_kind), + FitWeightRecord(SPI_DONOR_FIT_NAME, stage1_evidence.weight_kind), + FitWeightRecord(SPI_TRANSPORT_FIT_NAME, reference_evidence[0].weight_kind), + FitWeightRecord(FRS_ONLY_FIT_NAME, stage2_weight_kind), ), donor_path=donor_path, donor_sha256=( @@ -1998,31 +2096,23 @@ def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): gift_anchor=gift_anchor, donor_frame=donor_frame_receipt, gate_outcomes={ - **( - {} - if stage1_gate_calibration == UK_DEFAULT_GATE_CALIBRATION - else { - **gate_outcomes(SPI_DONOR_FIT_NAME, stage1), - **pooled_gate_outcomes(SPI_TRANSPORT_FIT_NAME, reference_fits), - } - ), - **( - {} - if stage2_gate_calibration == UK_DEFAULT_GATE_CALIBRATION - else gate_outcomes(FRS_ONLY_FIT_NAME, stage2) - ), + **gate_outcomes(SPI_DONOR_FIT_NAME, stage1_evidence), + **pooled_gate_outcomes(SPI_TRANSPORT_FIT_NAME, reference_evidence), + **stage2_gate_outcomes, }, gate_levels=( { "declared": list(stage1_gate_level_columns), "settings": gate_level_settings_receipt(), "offset_levels": { - **gate_levels(SPI_DONOR_FIT_NAME, stage1), - **pooled_gate_levels(SPI_TRANSPORT_FIT_NAME, reference_fits), + **gate_levels(SPI_DONOR_FIT_NAME, stage1_evidence), + **pooled_gate_levels(SPI_TRANSPORT_FIT_NAME, reference_evidence), }, "level_fits": { - **gate_level_reports(SPI_DONOR_FIT_NAME, stage1), - **pooled_gate_level_reports(SPI_TRANSPORT_FIT_NAME, reference_fits), + **gate_level_reports(SPI_DONOR_FIT_NAME, stage1_evidence), + **pooled_gate_level_reports( + SPI_TRANSPORT_FIT_NAME, reference_evidence + ), }, } if stage1_level_columns diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_rank_transport.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_rank_transport.py index 596ec88f39..70b032a645 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_rank_transport.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_rank_transport.py @@ -385,6 +385,9 @@ def cross_fit_transport( seed=seed, outputs=outputs, ) + # Freed here, or this fold's forests would stay in memory through the + # next fold's fit. + del reference for target in outputs: quantiles[target][score] = part.quantiles[target] sign_uniforms[target][score] = part.sign_uniforms[target] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py new file mode 100644 index 0000000000..bc2757cf98 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -0,0 +1,311 @@ +"""The UK SPI income imputation frees each fitted model once it is finished with it. + +``impute_uk_spi_income_support`` fits the stage-1 forests on the SPI tape, one +set of reference forests per cross-fitting fold on the FRS rows, then the +stage-2 forests. These tests pin that the stage-1 and reference forests are +dead when stage 2 starts, that each reference fold's forests are dead before +the next fold is fitted, that each stage-2 target's forests are dead before the +next target is fitted, and that the person table and every receipt stay +byte-identical. + +Two kinds of comparison: + +- In this process, against ``FitEveryTargetFirstQRF``: the real model with the + lifetimes and order the stage used to have. It runs on every platform. +- Against SHA-256 digests recorded by running origin/main 402c3587d's + ``impute_uk_spi_income_support`` on the fixture. QRF draws are bitwise + reproducible only within one platform (``docs/graph-qrf-cross-platform.md``), + so the digests are kept per operating system and machine: macOS arm64 + natively, and Linux x86_64 (CI's platform) under Docker emulation on Apple + silicon. They are checked only where the platform and the versions of the + libraries that compute the draws match the recording; elsewhere those tests + skip. + +A change that is meant to move these outputs records new digests from its own +code on each platform, says why the outputs move, and renames what here says +the digests come from origin/main 402c3587d. Any other change must leave them +passing. +""" + +from __future__ import annotations + +import platform +from collections import Counter +from collections.abc import Callable +from dataclasses import dataclass +from importlib.metadata import version + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.spi_income import ( + FRS_ONLY_FIT_NAME, + SPI_DONOR_FIT_NAME, + UKSPIIncomeImputationResult, +) +from microcosm.build.uk_runtime.spi_rank_transport import ( + SPI_TRANSPORT_FIT_NAME, + SPI_TRANSPORT_SEED_OFFSET, + analogue_targets, +) +from microcosm.build.uk_runtime.spi_support import SPI_INCOME_QRF_OUTPUT_COLUMNS +from microcosm.fit import RegimeGatedQRF +from test_support.microcosm_build.uk_spi_forest_release import ( + REFERENCE_FIT, + SPI_FOREST_SCENARIOS, + SPI_FOREST_SEED, + STAGE1_FIT, + STAGE2_FIT, + FitEveryTargetFirstQRF, + SPIForestLifetimes, + fitted_target_parts, + run_spi_forest_scenario, + spi_frozen_digests, + spi_result_digests, + tracked_spi_forest_fits, +) + +# --------------------------------------------------------------------------- +# origin/main's digests, by platform +# --------------------------------------------------------------------------- + +_ORIGIN_MAIN_DIGESTS: dict[tuple[str, str], dict[str, dict[str, str]]] = { + ("Darwin", "arm64"): { + "in_sample": { + "person": "280c69c2248b6741e6b95cf26bd2c9eeb457131283bf1906fd327401340b9c13", + "receipts": "1250371e2c3c3fe425c9497dbeedc09fd6046ffcf532d7f05e7f9a3e950d2280", + }, + "cross_fitted_levels": { + "person": "e938490d187e48bfc2b5f676598d58f898d6d97c71c5f439303a2ca8e64e9760", + "receipts": "aca65550fc5502afb03d78a784018f62dce6d41aa2ed0e5b676e576630caaf3b", + }, + }, + ("Linux", "x86_64"): { + "in_sample": { + "person": "5f582f65cb26446b52c5efa83abedcdcd294744b5dc0b059d9706279a1e15d39", + "receipts": "a6e3f464f10b7c037b908d75a39274f94e253df612b8a99eaa11bf6746cb547e", + }, + "cross_fitted_levels": { + "person": "db4b50143da3dc3927f6de08d6efe51f57dfa9ad2e87c8c65b47d07abfb448be", + "receipts": "d1103a63326a13d88981e9188b48162b62c7ad75cea2be459ef93a837bf6777c", + }, + }, +} + +#: Versions of the libraries that compute the draws, on both recordings. +_RECORDED_DEPENDENCIES = { + "numpy": "2.4.6", + "pandas": "3.0.3", + "scipy": "1.17.1", + "scikit-learn": "1.8.0", + "quantile-forest": "1.4.2", +} + + +def _origin_main_digests(scenario: str) -> dict[str, str]: + """This platform's recorded digests, or a skip where they do not apply.""" + + here = (platform.system(), platform.machine()) + recorded = _ORIGIN_MAIN_DIGESTS.get(here) + if recorded is None: + pytest.skip( + f"origin/main's digests were recorded on {sorted(_ORIGIN_MAIN_DIGESTS)}, " + f"not {here}; the in-process comparison covers this platform." + ) + installed = {name: version(name) for name in _RECORDED_DEPENDENCIES} + if installed != _RECORDED_DEPENDENCIES: + pytest.skip( + f"origin/main's digests were recorded with {_RECORDED_DEPENDENCIES}, " + f"not {installed}; the in-process comparison covers these versions." + ) + return recorded[scenario] + + +# --------------------------------------------------------------------------- +# One run of each scenario, under the lifetime check +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class _TrackedRun: + result: UKSPIIncomeImputationResult + lifetimes: SPIForestLifetimes + + +@pytest.fixture(scope="module") +def tracked_run(tmp_path_factory) -> Callable[[str], _TrackedRun]: + """Each scenario's run with real forests, made once for the tests that read it. + + Lifetime violations are recorded, not raised, so a kept model fails the + lifetime test alone and the byte checks still report on the run's output. + """ + + runs: dict[str, _TrackedRun] = {} + + def run(scenario: str) -> _TrackedRun: + if scenario not in runs: + directory = tmp_path_factory.mktemp(scenario) + with ( + pytest.MonkeyPatch.context() as monkeypatch, + tracked_spi_forest_fits( + monkeypatch, stop_at_first_violation=False + ) as lifetimes, + ): + result = run_spi_forest_scenario(scenario, directory, monkeypatch) + runs[scenario] = _TrackedRun(result, lifetimes) + return runs[scenario] + + return run + + +# --------------------------------------------------------------------------- +# Output and receipts +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) +def test_output_and_receipts_reproduce_origin_main_bytes(scenario, tracked_run) -> None: + expected = _origin_main_digests(scenario) + + assert spi_frozen_digests(tracked_run(scenario).result) == expected + + +@pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) +def test_output_and_receipts_match_fitting_every_target_first( + scenario, tracked_run, tmp_path, monkeypatch +) -> None: + """Freeing models and drawing per target moves no value and no receipt.""" + + FitEveryTargetFirstQRF.kept_fits.clear() + reference = run_spi_forest_scenario( + scenario, tmp_path, monkeypatch, qrf_class=FitEveryTargetFirstQRF + ) + assert FitEveryTargetFirstQRF.kept_fits + FitEveryTargetFirstQRF.kept_fits.clear() + + result = tracked_run(scenario).result + pd.testing.assert_frame_equal(result.person, reference.person, check_exact=True) + assert spi_result_digests(result) == spi_result_digests(reference) + + +def test_the_cross_fitted_scenario_fills_every_receipt_read_from_a_model( + tracked_run, +) -> None: + """The byte checks above would prove little over empty receipts.""" + + result = tracked_run("cross_fitted_levels").result + + every_fit = {SPI_DONOR_FIT_NAME, SPI_TRANSPORT_FIT_NAME, FRS_ONLY_FIT_NAME} + assert {key.split(":", 1)[0] for key in result.gate_outcomes} == every_fit + stage1_fits = {SPI_DONOR_FIT_NAME, SPI_TRANSPORT_FIT_NAME} + for receipt in ("offset_levels", "level_fits"): + keys = result.gate_levels[receipt] + assert {key.split(":", 1)[0] for key in keys} == stage1_fits + assert result.pension_receipt_bridge is not None + + +# --------------------------------------------------------------------------- +# Lifetimes +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) +def test_each_fit_starts_after_the_models_it_replaces_are_dead( + scenario, tracked_run +) -> None: + run = tracked_run(scenario) + + assert run.lifetimes.violations == [] + fits = Counter(fit for fit, _, _ in run.lifetimes.fitted) + folds = len(run.result.stage1_transport["fold_receipts"]) + assert folds > 1 + assert fits[STAGE1_FIT] == len(SPI_INCOME_QRF_OUTPUT_COLUMNS) + assert fits[REFERENCE_FIT] == folds * len(analogue_targets()) + assert fits[STAGE2_FIT] > 1 + + +@pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) +def test_no_fitted_model_outlives_the_stage(scenario, tracked_run) -> None: + lifetimes = tracked_run(scenario).lifetimes + + for fit in (STAGE1_FIT, REFERENCE_FIT, STAGE2_FIT): + assert lifetimes.alive(fit) == [] + + +def _fitted_forest_target() -> object: + """One real fitted target with a sign classifier and a positive forest.""" + + generator = np.random.default_rng(1) + predictor = generator.random(200) + table = pd.DataFrame( + { + "predictor": predictor, + "target": np.where(predictor > 0.5, 1.0 + predictor, 0.0), + } + ) + fitted = RegimeGatedQRF(n_estimators=2, seed=SPI_FOREST_SEED).fit( + table, ["predictor"], ["target"], weights="none" + ) + return fitted._target_models["target"] + + +@pytest.mark.parametrize( + "kept_kind", + [ + "target model", + "sign classifier", + "sign classifier tree", + "positive forest", + "positive regressor", + "positive tree", + "positive leaf array", + ], +) +def test_the_lifetime_check_notices_one_kept_part(kept_kind) -> None: + lifetimes = SPIForestLifetimes(seed=SPI_FOREST_SEED) + model = _fitted_forest_target() + lifetimes.record(STAGE1_FIT, 0, "target", model) + kept = next(part for kind, part in fitted_target_parts(model) if kind == kept_kind) + del model + + with pytest.raises(AssertionError, match=kept_kind): + lifetimes.check_before_fit(STAGE2_FIT, 0, "next_target") + + assert lifetimes.violations + del kept + lifetimes.check_before_fit(STAGE2_FIT, 0, "next_target") + + +@pytest.mark.parametrize( + ("kept_seed_offset", "kept_fit", "failing_fit"), + [ + (0, STAGE1_FIT, STAGE2_FIT), + (SPI_TRANSPORT_SEED_OFFSET, REFERENCE_FIT, REFERENCE_FIT), + ], + ids=["stage_1_kept", "reference_kept"], +) +def test_the_lifetime_check_notices_a_model_the_stage_keeps( + kept_seed_offset, kept_fit, failing_fit, tmp_path, monkeypatch +) -> None: + """The check run on the stage itself fails when one fit is held on to.""" + + kept_fits: list[object] = [] + + class KeepsOneFit(RegimeGatedQRF): + def fit(self, *args, **kwargs): + fitted = super().fit(*args, **kwargs) + if self.seed == SPI_FOREST_SEED + kept_seed_offset: + kept_fits.append(fitted) + return fitted + + with ( + tracked_spi_forest_fits(monkeypatch) as lifetimes, + pytest.raises(AssertionError, match=f"the {failing_fit} fit of"), + ): + run_spi_forest_scenario( + "in_sample", tmp_path, monkeypatch, qrf_class=KeepsOneFit + ) + + assert kept_fits + assert f"('{kept_fit}'," in lifetimes.violations[0] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_spine.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_spine.py index 3e17aeb58f..6bf199ab36 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_spine.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_spine.py @@ -46,6 +46,7 @@ ) from microcosm.build.uk_runtime.terminal_gates import UKZeroWeightStratumDeclaration from microcosm.frame import WeightKind +from test_support.microcosm_build.uk_spi_income import SPIChainDouble def _base_frame(*, time_period: str = "2023") -> object: @@ -328,7 +329,7 @@ def _fake_fit_label(targets: tuple[str, ...]) -> str: ) -class _FakeQRF: +class _FakeQRF(SPIChainDouble): events: list[tuple[str, tuple[str, ...], list[float]]] = [] instances: list[_FakeQRF] = [] diff --git a/test_support/microcosm_build/uk_spi_forest_release.py b/test_support/microcosm_build/uk_spi_forest_release.py new file mode 100644 index 0000000000..5718d696ab --- /dev/null +++ b/test_support/microcosm_build/uk_spi_forest_release.py @@ -0,0 +1,594 @@ +"""A small real-forest fixture for the UK SPI income imputation's forest lifetimes. + +``impute_uk_spi_income_support`` fits three kinds of model: the stage-1 forests +on the SPI tape, one set of reference forests per cross-fitting fold on the FRS +rows, and the stage-2 forests. This module provides: + +- :func:`spi_forest_support` and :func:`write_spi_forest_donor`, synthetic + inputs on which every one of those models is a real ``RegimeGatedQRF``; +- :func:`run_spi_forest_scenario`, one run of the imputation on them; +- :func:`spi_result_digests`, SHA-256 digests of the person table and of every + receipt in the result; +- :func:`tracked_spi_forest_fits`, which holds weak references to each fitted + target and checks, when a later fit starts, that the models it replaces are + dead. +""" + +from __future__ import annotations + +import dataclasses +import gc +import hashlib +import json +import weakref +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field, replace +from pathlib import Path +from types import SimpleNamespace +from typing import ClassVar + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime import frs_disability, spi_income +from microcosm.build.uk_runtime.frs_hmrc_source import FRS_HMRC_RETAINED_LEAF_COLUMNS +from microcosm.build.uk_runtime.spi_income import ( + SPI_DONOR_FILENAME, + SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS, + UKSPIIncomeImputationResult, + impute_uk_spi_income_support, +) +from microcosm.build.uk_runtime.spi_rank_transport import ( + SPI_TRANSPORT_SEED_OFFSET, + analogue_targets, +) +from microcosm.build.uk_runtime.spi_support import ( + FRS_ONLY_SPI_FILL_PERSON_COLUMNS, + SPI_INCOME_IMPUTATION_COLUMNS, + UKSPISupportResult, + create_uk_spi_support_tables, + replace_uk_spi_support_tables, +) +from microcosm.fit import RegimeGatedQRF +from microcosm.fit.qrf import _draw_target_from_uniforms +from test_support.microcosm_build.uk_spi_income import _write_donor + +SPI_FOREST_SEED = 9 +SPI_FOREST_TREES = 3 +_HOUSEHOLDS = 200 +_HOUSEHOLDS_COPIED_TO_SPI = 40 +_DONOR_ROWS = 400 +_DONOR_AGE_BANDS = (2, 3, 4, 5) +_SUPPORT_SEED = 11 +_DONOR_RESAMPLE_SEED = 3 +_DONOR_VALUE_SEED = 5 +_STATE_PENSION_AGE = 66 +#: Donor columns that are codes or weights; every other column is an amount. +_DONOR_NON_AMOUNT_COLUMNS = frozenset( + {"SEX", "FACT", "GORCODE", "AGERANGE", "MAINSRCE", "SEINC_NUM", "SPA"} +) + +#: The runs the tests compare. ``in_sample`` is the stage's default gate; +#: ``cross_fitted_levels`` turns on every receipt read from the fitted models. +SPI_FOREST_SCENARIOS: dict[str, dict[str, object]] = { + "in_sample": {}, + "cross_fitted_levels": { + "stage1_gate_calibration": "cross_fitted", + "stage2_gate_calibration": "cross_fitted", + "stage1_gate_level_columns": ("spi_age_band", "has_pay", "main_source"), + "condition_on_state_pension_receipt": True, + }, +} + + +def _zero_inflated_amounts(generator: np.random.Generator, position: int) -> np.ndarray: + """One person column: zero for some people, a rounded positive amount else.""" + + carrier_share = 0.45 + 0.1 * (position % 3 == 0) + carriers = generator.random(_HOUSEHOLDS) < carrier_share + amounts = generator.lognormal(6.0 + position % 4, 1.0, _HOUSEHOLDS) + return np.where(carriers, np.round(amounts, 2), 0.0) + + +def spi_forest_support() -> UKSPISupportResult: + """FRS people in one-person households, half of them copied to the SPI channel.""" + + generator = np.random.default_rng(_SUPPORT_SEED) + household_ids = np.arange(1, _HOUSEHOLDS + 1, dtype="int64") + household = pd.DataFrame( + { + "household_id": household_ids, + "household_weight": np.round(generator.uniform(5, 50, _HOUSEHOLDS), 3), + "region": generator.choice(["LONDON", "WALES", "SCOTLAND"], _HOUSEHOLDS), + "clone_index": 0, + "household_is_capital_gains_clone": generator.random(_HOUSEHOLDS) < 0.3, + } + ) + columns: dict[str, object] = { + "person_id": np.arange(1001, 1001 + _HOUSEHOLDS, dtype="int64"), + "person_household_id": household_ids, + "person_benunit_id": np.arange(2001, 2001 + _HOUSEHOLDS, dtype="int64"), + "age": generator.integers(20, 85, _HOUSEHOLDS), + "gender": generator.choice(["MALE", "FEMALE"], _HOUSEHOLDS), + "is_uc_claimant": np.ones(_HOUSEHOLDS, dtype=bool), + "employment_status": generator.choice( + ["FT_EMPLOYED", "PT_EMPLOYED", "RETIRED"], _HOUSEHOLDS + ), + "miscellaneous_income": np.zeros(_HOUSEHOLDS, dtype=float), + } + amount_columns = ( + *SPI_INCOME_IMPUTATION_COLUMNS, + *FRS_HMRC_RETAINED_LEAF_COLUMNS, + *FRS_ONLY_SPI_FILL_PERSON_COLUMNS, + ) + for position, column in enumerate(amount_columns, start=1): + amounts = _zero_inflated_amounts(generator, position) + if column not in SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS: + columns[column] = amounts + owners = generator.random(_HOUSEHOLDS) < 0.3 + trades = owners & (generator.random(_HOUSEHOLDS) < 0.5) + lets_property = owners & (generator.random(_HOUSEHOLDS) < 0.5) + for column, values in { + "stands_as_sole_owner_or_partner_of_company": owners, + "is_engaged_in_owned_company_trade": owners, + "owned_company_is_main_employment": owners, + "owned_company_carries_on_trade": trades, + "owned_company_carries_on_property_business": lets_property, + "owned_company_income_share": np.where(owners, 0.5, 0.0), + }.items(): + if column in columns: + columns[column] = values + columns["individual_savings_account_interest_income"] = _zero_inflated_amounts( + generator, 2 + ) + person = pd.DataFrame(columns) + benunit = pd.DataFrame({"benunit_id": person["person_benunit_id"].to_numpy()}) + dead_channel = create_uk_spi_support_tables( + person=person, + benunit=benunit, + household=household, + selected_household_ids=tuple(household_ids[:_HOUSEHOLDS_COPIED_TO_SPI]), + source_year=2023, + ) + support = replace_uk_spi_support_tables( + person=dead_channel.person, + benunit=dead_channel.benunit, + household=dead_channel.household, + seed=7, + source_year=2023, + ) + return replace(support, household=support.household.drop(columns="clone_index")) + + +def write_spi_forest_donor(directory: Path) -> Path: + """Write the tape: the four-record test donor resampled and rescaled. + + Every amount of a record moves by that record's factor, so the tape's + leaf reconciliation and its main-source codes keep holding. Age bands are + dealt independently of the amounts, so each band holds every sign class + and the stage-1 gates have levels to offset. + """ + + path = directory / SPI_DONOR_FILENAME + _write_donor(path) + records = pd.read_csv(path, sep="\t") + donor = records.sample( + n=_DONOR_ROWS, replace=True, random_state=_DONOR_RESAMPLE_SEED + ).reset_index(drop=True) + amounts = [ + column for column in donor.columns if column not in _DONOR_NON_AMOUNT_COLUMNS + ] + generator = np.random.default_rng(_DONOR_VALUE_SEED) + factors = generator.uniform(0.5, 3.0, len(donor)) + donor[amounts] = donor[amounts].mul(factors, axis=0) + donor["AGERANGE"] = generator.choice(_DONOR_AGE_BANDS, len(donor)) + donor.to_csv(path, sep="\t", index=False) + return path + + +def use_fixture_disability_rates(monkeypatch: pytest.MonkeyPatch) -> None: + """Give the disability refresh fixed rates, so no country engine is needed.""" + + category_rates = frs_disability.UKDWPDisabilityCategoryRates( + aa_lower=10, + aa_higher=20, + dla_sc_lower=10, + dla_sc_middle=20, + dla_sc_higher=30, + dla_m_lower=10, + dla_m_higher=20, + pip_m_standard=10, + pip_m_enhanced=20, + pip_dl_standard=10, + pip_dl_enhanced=20, + instant="2024-01-01", + source="fixture", + ) + flag_rates = frs_disability.UKDWPDisabilityFlagRates( + aa_higher=20, + dla_sc_higher=30, + pip_dl_enhanced=20, + instant="2024-01-01", + source="fixture", + ) + monkeypatch.setattr( + frs_disability, + "uk_dwp_disability_category_rates", + lambda year: category_rates, + ) + monkeypatch.setattr( + frs_disability, "uk_dwp_disability_flag_rates", lambda year: flag_rates + ) + + +def run_spi_forest_scenario( + scenario: str, + directory: Path, + monkeypatch: pytest.MonkeyPatch, + *, + qrf_class: type[RegimeGatedQRF] = RegimeGatedQRF, +) -> UKSPIIncomeImputationResult: + """Run the imputation on the fixture with real forests.""" + + use_fixture_disability_rates(monkeypatch) + monkeypatch.setattr(spi_income, "QRF", qrf_class) + monkeypatch.setattr(spi_income, "_verify_spi_donor_identity", lambda path: None) + return impute_uk_spi_income_support( + spi_forest_support(), + write_spi_forest_donor(directory), + seed=SPI_FOREST_SEED, + n_estimators=SPI_FOREST_TREES, + donor_sample_size=None, + state_pension_age=_STATE_PENSION_AGE, + allow_in_sample_reference=True, + **SPI_FOREST_SCENARIOS[scenario], + ) + + +class FitEveryTargetFirstQRF(RegimeGatedQRF): + """The real QRF with the lifetimes and order the stage used to have. + + Every fitted model stays referenced in :attr:`kept_fits`. ``start_chain`` + fits all targets at once, as ``fit`` does, and each ``fit_draw_next`` only + draws its target from that fit, through the function + ``predict_from_uniforms`` draws each target with. A run with this class + computes what the stage computed when it fitted stage 2 whole and held + every model until it returned. + """ + + kept_fits: ClassVar[list[object]] = [] + + def fit(self, *args: object, **kwargs: object) -> object: + fitted = super().fit(*args, **kwargs) + self.kept_fits.append(fitted) + return fitted + + def start_chain( + self, + frame_or_df: object, + predictors: list[str], + targets: list[str], + *, + weights: object, + groups: object = None, + ) -> object: + self._every_target_fit = self.fit( + frame_or_df, predictors, targets, weights=weights, groups=groups + ) + return super().start_chain( + frame_or_df, predictors, targets, weights=weights, groups=groups + ) + + def fit_draw_next( + self, + frame_or_df: object, + recipient_predictors: pd.DataFrame, + raw_prior_draws: pd.DataFrame, + *, + state: object, + weights: object, + quantiles: np.ndarray, + sign_uniforms: np.ndarray, + groups: object = None, + ) -> SimpleNamespace: + target = state.next_target + fitted = self._every_target_fit + features = recipient_predictors.loc[:, list(state.predictors)].copy() + for prior in state.completed_targets: + features[prior] = raw_prior_draws[prior].to_numpy(dtype=np.float64) + target_outcome = fitted.gate_outcomes()[target] + return SimpleNamespace( + target=target, + raw_draw=_draw_target_from_uniforms( + features, fitted._target_models[target], quantiles, sign_uniforms + ), + state=replace(state, completed_targets=(*state.completed_targets, target)), + regime=fitted.regimes()[target], + weight_kind=fitted.weight_kind, + fitted=SimpleNamespace(gate_outcomes=lambda: {target: target_outcome}), + ) + + +# --------------------------------------------------------------------------- +# Exact digests of a result +# --------------------------------------------------------------------------- + + +def _update_with_values(digest, label: object, values: pd.Index | pd.Series) -> None: + digest.update(repr(label).encode("utf-8")) + digest.update(str(values.dtype).encode("utf-8")) + if isinstance(values.dtype, np.dtype) and values.dtype.kind in "biuf": + digest.update(np.ascontiguousarray(values.to_numpy()).tobytes()) + else: + digest.update(repr(list(values)).encode("utf-8")) + + +def table_digest(table: pd.DataFrame) -> str: + """SHA-256 of a table's index and columns: names, dtypes and exact values. + + Boolean and numeric columns contribute their raw bytes, so a float that + moves in its last bit, or a ``-0.0`` for a ``0.0``, changes the digest. + Every other column contributes the ``repr`` of its values. + """ + + digest = hashlib.sha256() + _update_with_values(digest, ("index", tuple(table.index.names)), table.index) + for column in table.columns: + _update_with_values(digest, column, table[column]) + return digest.hexdigest() + + +def _exact_receipt_value(value: object) -> object: + """A JSON form of a receipt value that keeps types, order and every float bit.""" + + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return { + "dataclass": type(value).__name__, + "fields": [ + [item.name, _exact_receipt_value(getattr(value, item.name))] + for item in dataclasses.fields(value) + ], + } + if isinstance(value, Mapping): + return { + "mapping": [ + [_exact_receipt_value(key), _exact_receipt_value(item)] + for key, item in value.items() + ] + } + if isinstance(value, list | tuple): + return { + type(value).__name__: [_exact_receipt_value(item) for item in value], + } + if isinstance(value, np.ndarray): + return { + "array": str(value.dtype), + "shape": list(value.shape), + "bytes": np.ascontiguousarray(value).tobytes().hex(), + } + if isinstance(value, np.generic): + return {"numpy": str(value.dtype), "bytes": value.tobytes().hex()} + if isinstance(value, float): + return {"float": value.hex()} + if value is None or isinstance(value, bool | int | str): + return value + return {"repr": type(value).__name__, "value": repr(value)} + + +def receipt_digest(value: object) -> str: + """SHA-256 of one receipt, sensitive to key order, types and float bits.""" + + text = json.dumps(_exact_receipt_value(value), separators=(",", ":")) + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def spi_result_digests(result: UKSPIIncomeImputationResult) -> dict[str, str]: + """A digest of the person table and of every other field of the result. + + ``donor_path`` is left out: it names the test's temporary directory. + """ + + digests = {"person": table_digest(result.person)} + for item in dataclasses.fields(result): + if item.name not in {"person", "donor_path"}: + digests[item.name] = receipt_digest(getattr(result, item.name)) + return digests + + +def spi_frozen_digests(result: UKSPIIncomeImputationResult) -> dict[str, str]: + """The person table's digest and one digest over every receipt's.""" + + digests = spi_result_digests(result) + person = digests.pop("person") + text = json.dumps(digests, separators=(",", ":")) + return { + "person": person, + "receipts": hashlib.sha256(text.encode("utf-8")).hexdigest(), + } + + +# --------------------------------------------------------------------------- +# Lifetimes of the fitted forests +# --------------------------------------------------------------------------- + +STAGE1_FIT = "stage 1" +REFERENCE_FIT = "reference" +STAGE2_FIT = "stage 2" + + +def _classifier_parts( + label: str, classifier: object +) -> list[tuple[str, object | None]]: + """A gradient-boosted sign classifier, its binning, its trees and their nodes.""" + + parts: list[tuple[str, object | None]] = [ + (label, classifier), + (f"{label} bins", getattr(classifier, "_bin_mapper", None)), + ] + for boosting_round in getattr(classifier, "_predictors", None) or (): + for tree in boosting_round: + parts.append((f"{label} tree", tree)) + parts.append((f"{label} tree nodes", getattr(tree, "nodes", None))) + return parts + + +def fitted_target_parts(model: object) -> list[tuple[str, object]]: + """The weakly referenceable objects one fitted target owns, with their kinds. + + A cross-fitted sign gate contributes each fold's classifier. Each forest + contributes its regressor, its trees and the numpy array of every leaf's + training-row positions (the large, zero-padded allocation). + """ + + gate = getattr(model, "gate", None) + parts: list[tuple[str, object | None]] = [ + ("target model", model), + *_classifier_parts("sign classifier", gate), + ] + for fold_classifier in getattr(gate, "folds", None) or (): + parts.extend(_classifier_parts("fold sign classifier", fold_classifier)) + for sign in ("positive", "negative"): + forest = getattr(model, sign, None) + regressor = getattr(forest, "model", None) + parts.append((f"{sign} forest", forest)) + parts.append((f"{sign} regressor", regressor)) + parts.extend( + (f"{sign} tree", tree) + for tree in getattr(regressor, "estimators_", None) or () + ) + leaves = getattr(getattr(regressor, "forest_", None), "y_train_leaves", None) + parts.append((f"{sign} leaf array", getattr(leaves, "base", None))) + return [(kind, part) for kind, part in parts if part is not None] + + +@dataclass +class SPIForestLifetimes: + """Weak references to what each ``RegimeGatedQRF._fit_target`` call built.""" + + seed: int + stop_at_first_violation: bool = True + fitted: list[tuple[str, int, str]] = field(default_factory=list) + violations: list[str] = field(default_factory=list) + _references: list[tuple[str, int, str, str, weakref.ref]] = field( + default_factory=list + ) + _reference_fold: int = -1 + + def fit_of(self, model_seed: int) -> str: + """Which of the stage's models a fit belongs to, from its seed.""" + + return { + self.seed: STAGE1_FIT, + self.seed + SPI_TRANSPORT_SEED_OFFSET: REFERENCE_FIT, + self.seed + 1: STAGE2_FIT, + }[model_seed] + + def fold_of(self, fit: str, target: str) -> int: + """The cross-fitting fold of a reference fit; zero for the other fits.""" + + if fit != REFERENCE_FIT: + return 0 + if target == analogue_targets()[0]: + self._reference_fold += 1 + return self._reference_fold + + def record(self, fit: str, fold: int, target: str, model: object) -> None: + self.fitted.append((fit, fold, target)) + for kind, part in fitted_target_parts(model): + self._references.append((fit, fold, target, kind, weakref.ref(part))) + + def alive(self, fit: str, *, before_fold: int | None = None) -> list[tuple]: + """What is still alive of ``fit``, optionally of its earlier folds only.""" + + return [ + (fit, fold, target, kind) + for recorded, fold, target, kind, reference in self._references + if recorded == fit + and reference() is not None + and (before_fold is None or fold < before_fold) + ] + + def require_dead(self, alive: list[tuple], *, before: str) -> None: + if alive: + message = ( + f"{before} started while {len(alive)} objects were alive, " + f"among them {alive[:5]}" + ) + self.violations.append(message) + if self.stop_at_first_violation: + raise AssertionError(message) + + def check_before_fit(self, fit: str, fold: int, target: str) -> None: + """Require the models this fit replaces to be dead. + + A stage-2 fit needs the stage-1 and reference models and every earlier + stage-2 target dead. A reference fit needs the earlier folds dead; the + stage-1 model stays, because it draws after the last fold. + """ + + before = f"the {fit} fit of {target!r}" + if fit == STAGE2_FIT: + self.require_dead( + [ + *self.alive(STAGE1_FIT), + *self.alive(REFERENCE_FIT), + *self.alive(STAGE2_FIT), + ], + before=before, + ) + elif fit == REFERENCE_FIT: + self.require_dead( + self.alive(REFERENCE_FIT, before_fold=fold), before=before + ) + + +@contextmanager +def tracked_spi_forest_fits( + monkeypatch: pytest.MonkeyPatch, + *, + seed: int = SPI_FOREST_SEED, + stop_at_first_violation: bool = True, +) -> Iterator[SPIForestLifetimes]: + """Check, as each target's fit starts, that the models it replaces are dead. + + The garbage collector is off inside the block, so an object counts as freed + only when nothing references it, which is when its memory goes back; a + reference cycle would keep it alive and fail the check. + + scikit-learn's compiled ``Tree`` node storage and quantile-forest's + ``QuantileForest`` cannot be weakly referenced. Each belongs to a tracked + object and is freed with it, unless something references it directly, + which this check cannot see. + + A violation raises at once, unless ``stop_at_first_violation`` is false: + then the run goes on and :attr:`SPIForestLifetimes.violations` lists them. + """ + + lifetimes = SPIForestLifetimes( + seed=seed, stop_at_first_violation=stop_at_first_violation + ) + original = RegimeGatedQRF._fit_target + + def fit_target(self: RegimeGatedQRF, *, target: str, **kwargs: object) -> object: + fit = lifetimes.fit_of(self.seed) + fold = lifetimes.fold_of(fit, target) + lifetimes.check_before_fit(fit, fold, target) + model = original(self, target=target, **kwargs) + lifetimes.record(fit, fold, target, model) + return model + + monkeypatch.setattr(RegimeGatedQRF, "_fit_target", fit_target) + gc.collect() + collector_was_enabled = gc.isenabled() + gc.disable() + try: + yield lifetimes + finally: + if collector_was_enabled: + gc.enable() + monkeypatch.setattr(RegimeGatedQRF, "_fit_target", original) + + +__all__ = [name for name in globals() if not name.startswith("__")] diff --git a/test_support/microcosm_build/uk_spi_income.py b/test_support/microcosm_build/uk_spi_income.py index 648d8ac2a6..23d65d5723 100644 --- a/test_support/microcosm_build/uk_spi_income.py +++ b/test_support/microcosm_build/uk_spi_income.py @@ -2,7 +2,8 @@ from __future__ import annotations import sys -from dataclasses import replace +from collections.abc import Mapping +from dataclasses import dataclass, field, replace from pathlib import Path from types import SimpleNamespace @@ -56,6 +57,90 @@ _PINNED_SPI_DONOR_PATH = _REPO_ROOT / "inputs" / "spi" / "put2223uk.tab" +@dataclass(frozen=True) +class SPIChainDoubleState: + """Chain state of an :class:`SPIChainDouble`, with the uniforms seen so far.""" + + fitted: object + targets: tuple[str, ...] + weight_kind: str + completed_targets: tuple[str, ...] = () + quantiles: Mapping[str, np.ndarray] = field(default_factory=dict) + sign_uniforms: Mapping[str, np.ndarray] = field(default_factory=dict) + + @property + def next_target(self) -> str | None: + if self.is_complete: + return None + return self.targets[len(self.completed_targets)] + + @property + def is_complete(self) -> bool: + return len(self.completed_targets) == len(self.targets) + + +class SPIChainDouble: + """``start_chain`` and ``fit_draw_next`` over a stand-in's whole-model calls. + + SPI stage 2 fits and draws one target at a time. ``start_chain`` calls the + stand-in's ``fit`` once, and every step calls the fitted stand-in's + ``predict_from_uniforms`` and keeps its target's column. That method takes + uniforms for every target: targets the chain has not reached get this + step's, so the last step's call holds each target's own. + """ + + def start_chain( + self, frame, predictors, targets, *, weights, groups=None + ) -> SPIChainDoubleState: + fitted = self.fit( + frame, list(predictors), list(targets), weights=weights, groups=groups + ) + return SPIChainDoubleState( + fitted=fitted, targets=tuple(targets), weight_kind=fitted.weight_kind + ) + + def fit_draw_next( + self, + frame, + recipients: pd.DataFrame, + prior_draws: pd.DataFrame, + *, + state: SPIChainDoubleState, + weights, + quantiles: np.ndarray, + sign_uniforms: np.ndarray, + groups=None, + ) -> SimpleNamespace: + target = state.next_target + assert list(prior_draws.columns) == list(state.completed_targets) + seen_quantiles = {**state.quantiles, target: quantiles} + seen_sign_uniforms = {**state.sign_uniforms, target: sign_uniforms} + drawn = state.fitted.predict_from_uniforms( + recipients, + quantiles={ + name: seen_quantiles.get(name, quantiles) for name in state.targets + }, + sign_uniforms={ + name: seen_sign_uniforms.get(name, sign_uniforms) + for name in state.targets + }, + ) + return SimpleNamespace( + target=target, + raw_draw=np.asarray(drawn[target], dtype=np.float64), + state=replace( + state, + completed_targets=(*state.completed_targets, target), + quantiles=seen_quantiles, + sign_uniforms=seen_sign_uniforms, + ), + weight_kind=state.weight_kind, + fitted=SimpleNamespace( + gate_outcomes=lambda: {target: state.fitted.gate_outcomes()[target]} + ), + ) + + class _FakeFittedQRF: def __init__( self, @@ -139,7 +224,7 @@ def predict(self, predictors: pd.DataFrame) -> pd.DataFrame: return pd.DataFrame(values, index=predictors.index) -class _FakeQRF: +class _FakeQRF(SPIChainDouble): fit_weight_kinds: list[str] = [] fit_weight_values: list[np.ndarray] = [] #: Each fit's weight kind, gate calibration and fold groups, in fit order. From f35e258494ce458d01d3066d8fb0a343fe9b5f19 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:47:24 +0400 Subject: [PATCH 2/8] Check the SPI stage-2 inputs and receipts in every test run The same-run comparison took its stage-2 inputs from the code under test, so it could not see a wrong salt, seed, group or prior draw, and the two stages' gate receipts shared one code path with their reference. The fit-everything- first model now records what the stage passes it, and the tests compare those inputs and the receipts with expressions written from the earlier code, also for runs whose two stages declare different gates. The lifetime check also covers compiled trees and the leaf sorter. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_spi_forest_release.py | 271 +++++++++++++++--- .../microcosm_build/uk_spi_forest_release.py | 151 ++++++++-- 2 files changed, 363 insertions(+), 59 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index bc2757cf98..8972bd1dd6 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -11,7 +11,9 @@ Two kinds of comparison: - In this process, against ``FitEveryTargetFirstQRF``: the real model with the - lifetimes and order the stage used to have. It runs on every platform. + lifetimes and order the stage used to have. The inputs the stage passes it + and the receipts it reports are checked against expressions written out here + from what the stage computed before. These run on every platform. - Against SHA-256 digests recorded by running origin/main 402c3587d's ``impute_uk_spi_income_support`` on the fixture. QRF draws are bitwise reproducible only within one platform (``docs/graph-qrf-cross-platform.md``), @@ -22,9 +24,10 @@ skip. A change that is meant to move these outputs records new digests from its own -code on each platform, says why the outputs move, and renames what here says -the digests come from origin/main 402c3587d. Any other change must leave them -passing. +code on each platform with +``python -m test_support.microcosm_build.uk_spi_forest_release``, says why the +outputs move, and renames what here says the digests come from origin/main +402c3587d. Any other change must leave them passing. """ from __future__ import annotations @@ -39,9 +42,27 @@ import pandas as pd import pytest +from microcosm.build.gates import FitWeightRecord +from microcosm.build.stochastic_assignment import ( + integer_record_keys, + stable_identity_uniforms, +) +from microcosm.build.uk_runtime.qrf_gates import ( + UK_DEFAULT_GATE_CALIBRATION, + gate_level_reports, + gate_level_settings_receipt, + gate_levels, + gate_outcomes, + pooled_gate_level_reports, + pooled_gate_levels, + pooled_gate_outcomes, +) from microcosm.build.uk_runtime.spi_income import ( + _STAGE2_SALT_NAMES, FRS_ONLY_FIT_NAME, SPI_DONOR_FIT_NAME, + SPI_MINIMUM_RECIPIENT_AGE, + SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS, UKSPIIncomeImputationResult, ) from microcosm.build.uk_runtime.spi_rank_transport import ( @@ -49,18 +70,28 @@ SPI_TRANSPORT_SEED_OFFSET, analogue_targets, ) -from microcosm.build.uk_runtime.spi_support import SPI_INCOME_QRF_OUTPUT_COLUMNS +from microcosm.build.uk_runtime.spi_support import ( + BASE_FRS_SUPPORT_CHANNEL, + FRS_ONLY_SPI_FILL_PERSON_COLUMNS, + SPI_INCOME_QRF_OUTPUT_COLUMNS, + SPI_SYNTHETIC_SUPPORT_CHANNEL, + support_channel_column, +) from microcosm.fit import RegimeGatedQRF from test_support.microcosm_build.uk_spi_forest_release import ( REFERENCE_FIT, + SPI_FOREST_ALL_SCENARIOS, SPI_FOREST_SCENARIOS, SPI_FOREST_SEED, STAGE1_FIT, STAGE2_FIT, FitEveryTargetFirstQRF, + RecordedStage2Step, SPIForestLifetimes, fitted_target_parts, + receipt_digest, run_spi_forest_scenario, + spi_forest_support, spi_frozen_digests, spi_result_digests, tracked_spi_forest_fits, @@ -111,13 +142,13 @@ def _origin_main_digests(scenario: str) -> dict[str, str]: if recorded is None: pytest.skip( f"origin/main's digests were recorded on {sorted(_ORIGIN_MAIN_DIGESTS)}, " - f"not {here}; the in-process comparison covers this platform." + f"not {here}; the same-run checks still run here." ) installed = {name: version(name) for name in _RECORDED_DEPENDENCIES} if installed != _RECORDED_DEPENDENCIES: pytest.skip( f"origin/main's digests were recorded with {_RECORDED_DEPENDENCIES}, " - f"not {installed}; the in-process comparison covers these versions." + f"not {installed}; the same-run checks still run here." ) return recorded[scenario] @@ -159,6 +190,45 @@ def run(scenario: str) -> _TrackedRun: return run +@dataclass(frozen=True) +class _ReferenceRun: + result: UKSPIIncomeImputationResult + kept_fits: list[object] + chain_targets: list[tuple[str, ...]] + chain_groups: list[np.ndarray] + steps: list[RecordedStage2Step] + + +@pytest.fixture(scope="module") +def reference_run(tmp_path_factory) -> Callable[[str], _ReferenceRun]: + """Each scenario's run with ``FitEveryTargetFirstQRF``, made once.""" + + runs: dict[str, _ReferenceRun] = {} + + def run(scenario: str) -> _ReferenceRun: + if scenario not in runs: + directory = tmp_path_factory.mktemp(f"reference_{scenario}") + FitEveryTargetFirstQRF.forget_recorded() + with pytest.MonkeyPatch.context() as monkeypatch: + result = run_spi_forest_scenario( + scenario, + directory, + monkeypatch, + qrf_class=FitEveryTargetFirstQRF, + ) + runs[scenario] = _ReferenceRun( + result, + list(FitEveryTargetFirstQRF.kept_fits), + list(FitEveryTargetFirstQRF.chain_targets), + list(FitEveryTargetFirstQRF.chain_groups), + list(FitEveryTargetFirstQRF.steps), + ) + FitEveryTargetFirstQRF.forget_recorded() + return runs[scenario] + + return run + + # --------------------------------------------------------------------------- # Output and receipts # --------------------------------------------------------------------------- @@ -173,22 +243,129 @@ def test_output_and_receipts_reproduce_origin_main_bytes(scenario, tracked_run) @pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) def test_output_and_receipts_match_fitting_every_target_first( - scenario, tracked_run, tmp_path, monkeypatch + scenario, tracked_run, reference_run ) -> None: """Freeing models and drawing per target moves no value and no receipt.""" - FitEveryTargetFirstQRF.kept_fits.clear() - reference = run_spi_forest_scenario( - scenario, tmp_path, monkeypatch, qrf_class=FitEveryTargetFirstQRF - ) - assert FitEveryTargetFirstQRF.kept_fits - FitEveryTargetFirstQRF.kept_fits.clear() - + reference = reference_run(scenario).result result = tracked_run(scenario).result + pd.testing.assert_frame_equal(result.person, reference.person, check_exact=True) assert spi_result_digests(result) == spi_result_digests(reference) +@pytest.mark.parametrize("scenario", SPI_FOREST_ALL_SCENARIOS) +def test_receipts_equal_what_the_kept_models_report(scenario, reference_run) -> None: + """The receipts, built as the stage built them from the models it held.""" + + run = reference_run(scenario) + options = SPI_FOREST_ALL_SCENARIOS[scenario] + stage1, *reference_folds, stage2 = run.kept_fits + stage1_gate = options.get("stage1_gate_calibration", UK_DEFAULT_GATE_CALIBRATION) + stage2_gate = options.get("stage2_gate_calibration", UK_DEFAULT_GATE_CALIBRATION) + level_columns = options.get("stage1_gate_level_columns", ()) + expected_outcomes = { + **( + {} + if stage1_gate == UK_DEFAULT_GATE_CALIBRATION + else { + **gate_outcomes(SPI_DONOR_FIT_NAME, stage1), + **pooled_gate_outcomes(SPI_TRANSPORT_FIT_NAME, reference_folds), + } + ), + **( + {} + if stage2_gate == UK_DEFAULT_GATE_CALIBRATION + else gate_outcomes(FRS_ONLY_FIT_NAME, stage2) + ), + } + expected_levels = ( + { + "declared": list(level_columns), + "settings": gate_level_settings_receipt(), + "offset_levels": { + **gate_levels(SPI_DONOR_FIT_NAME, stage1), + **pooled_gate_levels(SPI_TRANSPORT_FIT_NAME, reference_folds), + }, + "level_fits": { + **gate_level_reports(SPI_DONOR_FIT_NAME, stage1), + **pooled_gate_level_reports(SPI_TRANSPORT_FIT_NAME, reference_folds), + }, + } + if level_columns + else None + ) + expected_weight_records = ( + FitWeightRecord(SPI_DONOR_FIT_NAME, stage1.weight_kind), + FitWeightRecord(SPI_TRANSPORT_FIT_NAME, reference_folds[0].weight_kind), + FitWeightRecord(FRS_ONLY_FIT_NAME, stage2.weight_kind), + ) + + assert len(reference_folds) == len(run.result.stage1_transport["fold_receipts"]) + assert run.result.gate_outcomes == expected_outcomes + assert receipt_digest(run.result.gate_outcomes) == receipt_digest(expected_outcomes) + assert receipt_digest(run.result.gate_levels) == receipt_digest(expected_levels) + assert receipt_digest(run.result.fit_weight_records) == receipt_digest( + expected_weight_records + ) + + +@pytest.mark.parametrize("scenario", SPI_FOREST_ALL_SCENARIOS) +def test_stage2_steps_get_the_inputs_of_the_whole_fit_and_draw( + scenario, reference_run +) -> None: + """Targets, rows, uniforms, fold groups and prior draws, target by target.""" + + run = reference_run(scenario) + person = spi_forest_support().person + channel = person[support_channel_column("person")] + base_rows = channel == BASE_FRS_SUPPORT_CHANNEL + drawn_rows = (channel == SPI_SYNTHETIC_SUPPORT_CHANNEL) & person["age"].ge( + SPI_MINIMUM_RECIPIENT_AGE + ) + expected_targets = tuple( + column + for column in FRS_ONLY_SPI_FILL_PERSON_COLUMNS + if column not in SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS + ) + expected_groups = person.loc[base_rows, "person_household_id"].to_numpy() + record_keys = integer_record_keys( + person.loc[drawn_rows, "person_id"].to_numpy(), + label="SPI stage-2 person_id", + ) + stage2_seed = SPI_FOREST_SEED + 1 + + assert run.chain_targets == [expected_targets] + np.testing.assert_array_equal(run.chain_groups[0], expected_groups) + assert tuple(step.target for step in run.steps) == expected_targets + for position, step in enumerate(run.steps): + salt_name = _STAGE2_SALT_NAMES.get(step.target, step.target) + assert step.recipient_index.equals(person.index[drawn_rows]) + np.testing.assert_array_equal(step.groups, expected_groups) + np.testing.assert_array_equal( + step.quantiles, + stable_identity_uniforms( + record_keys, + seed=stage2_seed, + salt=f"{FRS_ONLY_FIT_NAME}:{salt_name}", + ), + ) + np.testing.assert_array_equal( + step.sign_uniforms, + stable_identity_uniforms( + record_keys, + seed=stage2_seed, + salt=f"{FRS_ONLY_FIT_NAME}:{salt_name}:sign", + ), + ) + assert list(step.prior_draws.columns) == list(expected_targets[:position]) + for earlier in run.steps[:position]: + assert ( + step.prior_draws[earlier.target].to_numpy().tobytes() + == earlier.raw_draw.tobytes() + ) + + def test_the_cross_fitted_scenario_fills_every_receipt_read_from_a_model( tracked_run, ) -> None: @@ -233,38 +410,60 @@ def test_no_fitted_model_outlives_the_stage(scenario, tracked_run) -> None: assert lifetimes.alive(fit) == [] -def _fitted_forest_target() -> object: - """One real fitted target with a sign classifier and a positive forest.""" +def _fitted_forest_target(gate_calibration: str) -> object: + """One real fitted target with a sign classifier and forests of both signs.""" generator = np.random.default_rng(1) - predictor = generator.random(200) - table = pd.DataFrame( - { - "predictor": predictor, - "target": np.where(predictor > 0.5, 1.0 + predictor, 0.0), - } - ) - fitted = RegimeGatedQRF(n_estimators=2, seed=SPI_FOREST_SEED).fit( - table, ["predictor"], ["target"], weights="none" + predictor = generator.random(300) + target = np.select( + [predictor < 1 / 3, predictor > 2 / 3], + [-1.0 - predictor, 1.0 + predictor], + default=0.0, ) + table = pd.DataFrame({"predictor": predictor, "target": target}) + fitted = RegimeGatedQRF( + n_estimators=2, seed=SPI_FOREST_SEED, gate_calibration=gate_calibration + ).fit(table, ["predictor"], ["target"], weights="none") return fitted._target_models["target"] +_IN_SAMPLE_GATE_PARTS = ( + "target model", + "sign classifier", + "sign classifier bins", + "sign classifier tree", + "sign classifier tree nodes", + *( + f"{sign} {part}" + for sign in ("positive", "negative") + for part in ( + "forest", + "regressor", + "tree", + "compiled tree", + "leaf sorter", + "leaf array", + ) + ), +) +_CROSS_FITTED_GATE_PARTS = ( + "fold sign classifier", + "fold sign classifier bins", + "fold sign classifier tree", + "fold sign classifier tree nodes", +) + + @pytest.mark.parametrize( - "kept_kind", + ("gate_calibration", "kept_kind"), [ - "target model", - "sign classifier", - "sign classifier tree", - "positive forest", - "positive regressor", - "positive tree", - "positive leaf array", + *(("in_sample", kind) for kind in _IN_SAMPLE_GATE_PARTS), + *(("cross_fitted", kind) for kind in _CROSS_FITTED_GATE_PARTS), ], ) -def test_the_lifetime_check_notices_one_kept_part(kept_kind) -> None: +def test_the_lifetime_check_notices_one_kept_part(gate_calibration, kept_kind) -> None: lifetimes = SPIForestLifetimes(seed=SPI_FOREST_SEED) - model = _fitted_forest_target() + model = _fitted_forest_target(gate_calibration) lifetimes.record(STAGE1_FIT, 0, "target", model) kept = next(part for kind, part in fitted_target_parts(model) if kind == kept_kind) del model diff --git a/test_support/microcosm_build/uk_spi_forest_release.py b/test_support/microcosm_build/uk_spi_forest_release.py index 5718d696ab..7b82388874 100644 --- a/test_support/microcosm_build/uk_spi_forest_release.py +++ b/test_support/microcosm_build/uk_spi_forest_release.py @@ -9,9 +9,13 @@ - :func:`run_spi_forest_scenario`, one run of the imputation on them; - :func:`spi_result_digests`, SHA-256 digests of the person table and of every receipt in the result; -- :func:`tracked_spi_forest_fits`, which holds weak references to each fitted - target and checks, when a later fit starts, that the models it replaces are - dead. +- :class:`FitEveryTargetFirstQRF`, the real model with the lifetimes and order + the stage used to have, which records what the stage passes it; +- :func:`tracked_spi_forest_fits`, which tracks what each fitted target owns + and checks, when a later fit starts, that the models it replaces are dead. + +``python -m test_support.microcosm_build.uk_spi_forest_release`` prints the +digests the byte tests freeze, for this platform and this checkout's code. """ from __future__ import annotations @@ -20,8 +24,11 @@ import gc import hashlib import json +import platform +import sys +import tempfile import weakref -from collections.abc import Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass, field, replace from pathlib import Path @@ -81,6 +88,16 @@ "condition_on_state_pension_receipt": True, }, } +#: Runs whose two stages declare different gates. No digests are frozen for +#: them: their receipts are checked against the models the run fitted. +SPI_FOREST_MIXED_GATE_SCENARIOS: dict[str, dict[str, object]] = { + "stage1_cross_fitted": {"stage1_gate_calibration": "cross_fitted"}, + "stage2_cross_fitted": {"stage2_gate_calibration": "cross_fitted"}, +} +SPI_FOREST_ALL_SCENARIOS: dict[str, dict[str, object]] = { + **SPI_FOREST_SCENARIOS, + **SPI_FOREST_MIXED_GATE_SCENARIOS, +} def _zero_inflated_amounts(generator: np.random.Generator, position: int) -> np.ndarray: @@ -243,10 +260,23 @@ def run_spi_forest_scenario( donor_sample_size=None, state_pension_age=_STATE_PENSION_AGE, allow_in_sample_reference=True, - **SPI_FOREST_SCENARIOS[scenario], + **SPI_FOREST_ALL_SCENARIOS[scenario], ) +@dataclass(frozen=True) +class RecordedStage2Step: + """What one ``fit_draw_next`` call received, and the draw it returned.""" + + target: str + recipient_index: pd.Index + prior_draws: pd.DataFrame + quantiles: np.ndarray + sign_uniforms: np.ndarray + groups: np.ndarray + raw_draw: np.ndarray + + class FitEveryTargetFirstQRF(RegimeGatedQRF): """The real QRF with the lifetimes and order the stage used to have. @@ -255,10 +285,20 @@ class FitEveryTargetFirstQRF(RegimeGatedQRF): draws its target from that fit, through the function ``predict_from_uniforms`` draws each target with. A run with this class computes what the stage computed when it fitted stage 2 whole and held - every model until it returned. + every model until it returned, given the inputs the stage passes here; + :attr:`chain_targets`, :attr:`chain_groups` and :attr:`steps` record those + inputs so a test can check them. """ kept_fits: ClassVar[list[object]] = [] + chain_targets: ClassVar[list[tuple[str, ...]]] = [] + chain_groups: ClassVar[list[np.ndarray]] = [] + steps: ClassVar[list[RecordedStage2Step]] = [] + + @classmethod + def forget_recorded(cls) -> None: + for recorded in (cls.kept_fits, cls.chain_targets, cls.chain_groups, cls.steps): + recorded.clear() def fit(self, *args: object, **kwargs: object) -> object: fitted = super().fit(*args, **kwargs) @@ -274,6 +314,8 @@ def start_chain( weights: object, groups: object = None, ) -> object: + self.chain_targets.append(tuple(targets)) + self.chain_groups.append(np.array(groups, copy=True)) self._every_target_fit = self.fit( frame_or_df, predictors, targets, weights=weights, groups=groups ) @@ -299,11 +341,23 @@ def fit_draw_next( for prior in state.completed_targets: features[prior] = raw_prior_draws[prior].to_numpy(dtype=np.float64) target_outcome = fitted.gate_outcomes()[target] + raw_draw = _draw_target_from_uniforms( + features, fitted._target_models[target], quantiles, sign_uniforms + ) + self.steps.append( + RecordedStage2Step( + target=target, + recipient_index=recipient_predictors.index.copy(), + prior_draws=raw_prior_draws.copy(deep=True), + quantiles=np.array(quantiles, copy=True), + sign_uniforms=np.array(sign_uniforms, copy=True), + groups=np.array(groups, copy=True), + raw_draw=np.array(raw_draw, copy=True), + ) + ) return SimpleNamespace( target=target, - raw_draw=_draw_target_from_uniforms( - features, fitted._target_models[target], quantiles, sign_uniforms - ), + raw_draw=raw_draw, state=replace(state, completed_targets=(*state.completed_targets, target)), regime=fitted.regimes()[target], weight_kind=fitted.weight_kind, @@ -435,11 +489,12 @@ def _classifier_parts( def fitted_target_parts(model: object) -> list[tuple[str, object]]: - """The weakly referenceable objects one fitted target owns, with their kinds. + """The objects one fitted target owns, with their kinds. A cross-fitted sign gate contributes each fold's classifier. Each forest - contributes its regressor, its trees and the numpy array of every leaf's - training-row positions (the large, zero-padded allocation). + contributes its regressor, its trees with their compiled node storage, the + regressor's leaf sorter and the numpy array of every leaf's training-row + positions (the large, zero-padded allocation). """ gate = getattr(model, "gate", None) @@ -454,24 +509,54 @@ def fitted_target_parts(model: object) -> list[tuple[str, object]]: regressor = getattr(forest, "model", None) parts.append((f"{sign} forest", forest)) parts.append((f"{sign} regressor", regressor)) - parts.extend( - (f"{sign} tree", tree) - for tree in getattr(regressor, "estimators_", None) or () - ) + for tree in getattr(regressor, "estimators_", None) or (): + parts.append((f"{sign} tree", tree)) + parts.append((f"{sign} compiled tree", getattr(tree, "tree_", None))) + parts.append((f"{sign} leaf sorter", getattr(regressor, "sorter_", None))) leaves = getattr(getattr(regressor, "forest_", None), "y_train_leaves", None) parts.append((f"{sign} leaf array", getattr(leaves, "base", None))) return [(kind, part) for kind, part in parts if part is not None] +class _HeldPart: + """A reference to a part that cannot be weakly referenced. + + Calling it returns the part while anything else references it too, and + ``None`` once this holder is the only reference left, as a dead weak + reference does. + """ + + def __init__(self, part: object) -> None: + self.part = part + + def reference_count(self) -> int: + return sys.getrefcount(self.part) + + def __call__(self) -> object | None: + if self.reference_count() > _SOLE_HOLDER_REFERENCE_COUNT: + return self.part + return None + + +_SOLE_HOLDER_REFERENCE_COUNT = _HeldPart(object()).reference_count() + + +def _lifetime_reference(part: object) -> Callable[[], object | None]: + try: + return weakref.ref(part) + except TypeError: + return _HeldPart(part) + + @dataclass class SPIForestLifetimes: - """Weak references to what each ``RegimeGatedQRF._fit_target`` call built.""" + """References to what each ``RegimeGatedQRF._fit_target`` call built.""" seed: int stop_at_first_violation: bool = True fitted: list[tuple[str, int, str]] = field(default_factory=list) violations: list[str] = field(default_factory=list) - _references: list[tuple[str, int, str, str, weakref.ref]] = field( + _references: list[tuple[str, int, str, str, Callable[[], object | None]]] = field( default_factory=list ) _reference_fold: int = -1 @@ -497,7 +582,9 @@ def fold_of(self, fit: str, target: str) -> int: def record(self, fit: str, fold: int, target: str, model: object) -> None: self.fitted.append((fit, fold, target)) for kind, part in fitted_target_parts(model): - self._references.append((fit, fold, target, kind, weakref.ref(part))) + self._references.append( + (fit, fold, target, kind, _lifetime_reference(part)) + ) def alive(self, fit: str, *, before_fold: int | None = None) -> list[tuple]: """What is still alive of ``fit``, optionally of its earlier folds only.""" @@ -557,10 +644,10 @@ def tracked_spi_forest_fits( only when nothing references it, which is when its memory goes back; a reference cycle would keep it alive and fail the check. - scikit-learn's compiled ``Tree`` node storage and quantile-forest's - ``QuantileForest`` cannot be weakly referenced. Each belongs to a tracked - object and is freed with it, unless something references it directly, - which this check cannot see. + scikit-learn's compiled ``Tree`` cannot be weakly referenced, so the check + holds each one and counts its other references. quantile-forest's + ``QuantileForest`` cannot be weakly referenced either, and holding it would + keep its leaf array alive; a reference to it shows up through that array. A violation raises at once, unless ``stop_at_first_violation`` is false: then the run goes on and :attr:`SPIForestLifetimes.violations` lists them. @@ -591,4 +678,22 @@ def fit_target(self: RegimeGatedQRF, *, target: str, **kwargs: object) -> object monkeypatch.setattr(RegimeGatedQRF, "_fit_target", original) +def print_spi_forest_digests() -> None: + """Print each frozen scenario's digests for this platform and checkout.""" + + digests: dict[str, dict[str, str]] = {} + for scenario in SPI_FOREST_SCENARIOS: + with ( + pytest.MonkeyPatch.context() as monkeypatch, + tempfile.TemporaryDirectory() as directory, + ): + result = run_spi_forest_scenario(scenario, Path(directory), monkeypatch) + digests[scenario] = spi_frozen_digests(result) + here = [platform.system(), platform.machine()] + print(json.dumps({"platform": here, "digests": digests}, indent=1)) + + __all__ = [name for name in globals() if not name.startswith("__")] + +if __name__ == "__main__": + print_spi_forest_digests() From 8dc2753a5c2464b73ba23a6786fb6fd159499159 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:38:39 +0400 Subject: [PATCH 3/8] Pin the SPI stage-2 settings, predictors and salts in the tests The stage-2 checks now also cover the chain's seed, tree count, gate calibration, predictor names and the recipient predictors stage 1 does not write, and spell out the released uniform salts. The digest command prints the library versions the digests depend on. A comment now says a reference fold without recipients adds no receipt entry. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/uk_runtime/spi_income.py | 4 +- .../uk/test_uk_spi_forest_release.py | 86 +++++++++++++++---- .../microcosm_build/uk_spi_forest_release.py | 56 +++++++++--- 3 files changed, 116 insertions(+), 30 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py index ab433a1647..cfdc104bea 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/spi_income.py @@ -1692,8 +1692,8 @@ def impute_uk_spi_income_support( assert_analogue_map_covers(SPI_INCOME_QRF_OUTPUT_COLUMNS) reference_weights = training_weights.loc[reference_people] reference_targets = list(analogue_targets(SPI_INCOME_QRF_OUTPUT_COLUMNS)) - # One entry per fold; the fold's forests are freed once it has located its - # recipients. + # One entry per fold that has recipients; the fold's forests are freed once + # it has located them. reference_evidence: list[_FitGateEvidence] = [] def fit_reference(encoded: pd.DataFrame, observed: pd.DataFrame): diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index 8972bd1dd6..b26130af57 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -58,7 +58,6 @@ pooled_gate_outcomes, ) from microcosm.build.uk_runtime.spi_income import ( - _STAGE2_SALT_NAMES, FRS_ONLY_FIT_NAME, SPI_DONOR_FIT_NAME, SPI_MINIMUM_RECIPIENT_AGE, @@ -72,6 +71,7 @@ ) from microcosm.build.uk_runtime.spi_support import ( BASE_FRS_SUPPORT_CHANNEL, + FRS_ONLY_SPI_FILL_INCOME_PREDICTOR_COLUMNS, FRS_ONLY_SPI_FILL_PERSON_COLUMNS, SPI_INCOME_QRF_OUTPUT_COLUMNS, SPI_SYNTHETIC_SUPPORT_CHANNEL, @@ -83,9 +83,11 @@ SPI_FOREST_ALL_SCENARIOS, SPI_FOREST_SCENARIOS, SPI_FOREST_SEED, + SPI_FOREST_TREES, STAGE1_FIT, STAGE2_FIT, FitEveryTargetFirstQRF, + RecordedStage2Start, RecordedStage2Step, SPIForestLifetimes, fitted_target_parts, @@ -124,6 +126,13 @@ }, } +#: The stage-2 uniform salts as released, written out so that a change to the +#: stage's constants, which would redraw every row, fails here. +_STAGE2_FIT_NAME_AS_RELEASED = "uk_frs_only_spi_fill" +_STAGE2_SALT_NAMES_AS_RELEASED = { + "individual_savings_account_interest_income": "tax_free_savings_income" +} + #: Versions of the libraries that compute the draws, on both recordings. _RECORDED_DEPENDENCIES = { "numpy": "2.4.6", @@ -194,8 +203,7 @@ def run(scenario: str) -> _TrackedRun: class _ReferenceRun: result: UKSPIIncomeImputationResult kept_fits: list[object] - chain_targets: list[tuple[str, ...]] - chain_groups: list[np.ndarray] + chain_starts: list[RecordedStage2Start] steps: list[RecordedStage2Step] @@ -219,8 +227,7 @@ def run(scenario: str) -> _ReferenceRun: runs[scenario] = _ReferenceRun( result, list(FitEveryTargetFirstQRF.kept_fits), - list(FitEveryTargetFirstQRF.chain_targets), - list(FitEveryTargetFirstQRF.chain_groups), + list(FitEveryTargetFirstQRF.chain_starts), list(FitEveryTargetFirstQRF.steps), ) FitEveryTargetFirstQRF.forget_recorded() @@ -311,43 +318,90 @@ def test_receipts_equal_what_the_kept_models_report(scenario, reference_run) -> @pytest.mark.parametrize("scenario", SPI_FOREST_ALL_SCENARIOS) -def test_stage2_steps_get_the_inputs_of_the_whole_fit_and_draw( +def test_stage2_chain_gets_the_settings_and_inputs_of_the_whole_fit_and_draw( scenario, reference_run ) -> None: - """Targets, rows, uniforms, fold groups and prior draws, target by target.""" + """Model settings, targets, rows, predictors, uniforms, groups and prior draws. + + The expected values are written out from what the stage passed to one fit + over every target and one ``predict_from_uniforms``. The income predictors + of the drawn rows hold stage-1 draws, which vary by platform, so only the + byte tests cover their values. + """ run = reference_run(scenario) - person = spi_forest_support().person + options = SPI_FOREST_ALL_SCENARIOS[scenario] + support = spi_forest_support() + person = support.person channel = person[support_channel_column("person")] base_rows = channel == BASE_FRS_SUPPORT_CHANNEL drawn_rows = (channel == SPI_SYNTHETIC_SUPPORT_CHANNEL) & person["age"].ge( SPI_MINIMUM_RECIPIENT_AGE ) + drawn_people = person.loc[drawn_rows] + drawn_regions = drawn_people["person_household_id"].map( + support.household.set_index("household_id")["region"] + ) + genders = sorted(person["gender"].unique()) + regions = sorted(support.household["region"].unique()) expected_targets = tuple( column for column in FRS_ONLY_SPI_FILL_PERSON_COLUMNS if column not in SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS ) + expected_predictors = tuple( + sorted( + [ + "age", + *FRS_ONLY_SPI_FILL_INCOME_PREDICTOR_COLUMNS, + *(f"gender_{gender}" for gender in genders), + *(f"region_{region}" for region in regions), + *( + ["state_pension_receipt"] + if options.get("condition_on_state_pension_receipt") + else [] + ), + ] + ) + ) expected_groups = person.loc[base_rows, "person_household_id"].to_numpy() record_keys = integer_record_keys( - person.loc[drawn_rows, "person_id"].to_numpy(), - label="SPI stage-2 person_id", + drawn_people["person_id"].to_numpy(), label="SPI stage-2 person_id" ) stage2_seed = SPI_FOREST_SEED + 1 - assert run.chain_targets == [expected_targets] - np.testing.assert_array_equal(run.chain_groups[0], expected_groups) + assert len(run.chain_starts) == 1 + start = run.chain_starts[0] + assert start.seed == stage2_seed + assert start.n_estimators == SPI_FOREST_TREES + assert start.gate_calibration == options.get( + "stage2_gate_calibration", UK_DEFAULT_GATE_CALIBRATION + ) + assert start.predictors == expected_predictors + assert start.targets == expected_targets + np.testing.assert_array_equal(start.groups, expected_groups) assert tuple(step.target for step in run.steps) == expected_targets for position, step in enumerate(run.steps): - salt_name = _STAGE2_SALT_NAMES.get(step.target, step.target) - assert step.recipient_index.equals(person.index[drawn_rows]) + salt_name = _STAGE2_SALT_NAMES_AS_RELEASED.get(step.target, step.target) + recipients = step.recipient_predictors + assert recipients.index.equals(drawn_people.index) + assert tuple(recipients.columns) == expected_predictors + np.testing.assert_array_equal(recipients["age"], drawn_people["age"]) + for gender in genders: + np.testing.assert_array_equal( + recipients[f"gender_{gender}"], drawn_people["gender"].eq(gender) + ) + for region in regions: + np.testing.assert_array_equal( + recipients[f"region_{region}"], drawn_regions.eq(region) + ) np.testing.assert_array_equal(step.groups, expected_groups) np.testing.assert_array_equal( step.quantiles, stable_identity_uniforms( record_keys, seed=stage2_seed, - salt=f"{FRS_ONLY_FIT_NAME}:{salt_name}", + salt=f"{_STAGE2_FIT_NAME_AS_RELEASED}:{salt_name}", ), ) np.testing.assert_array_equal( @@ -355,7 +409,7 @@ def test_stage2_steps_get_the_inputs_of_the_whole_fit_and_draw( stable_identity_uniforms( record_keys, seed=stage2_seed, - salt=f"{FRS_ONLY_FIT_NAME}:{salt_name}:sign", + salt=f"{_STAGE2_FIT_NAME_AS_RELEASED}:{salt_name}:sign", ), ) assert list(step.prior_draws.columns) == list(expected_targets[:position]) diff --git a/test_support/microcosm_build/uk_spi_forest_release.py b/test_support/microcosm_build/uk_spi_forest_release.py index 7b82388874..3a0cd2b9fc 100644 --- a/test_support/microcosm_build/uk_spi_forest_release.py +++ b/test_support/microcosm_build/uk_spi_forest_release.py @@ -31,6 +31,7 @@ from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass, field, replace +from importlib.metadata import version from pathlib import Path from types import SimpleNamespace from typing import ClassVar @@ -64,6 +65,14 @@ SPI_FOREST_SEED = 9 SPI_FOREST_TREES = 3 +#: The libraries that compute the draws, whose versions the digests depend on. +SPI_FOREST_DRAW_LIBRARIES = ( + "numpy", + "pandas", + "scipy", + "scikit-learn", + "quantile-forest", +) _HOUSEHOLDS = 200 _HOUSEHOLDS_COPIED_TO_SPI = 40 _DONOR_ROWS = 400 @@ -264,12 +273,24 @@ def run_spi_forest_scenario( ) +@dataclass(frozen=True) +class RecordedStage2Start: + """The model settings and inputs one ``start_chain`` call received.""" + + seed: int + n_estimators: int + gate_calibration: str + predictors: tuple[str, ...] + targets: tuple[str, ...] + groups: np.ndarray + + @dataclass(frozen=True) class RecordedStage2Step: """What one ``fit_draw_next`` call received, and the draw it returned.""" target: str - recipient_index: pd.Index + recipient_predictors: pd.DataFrame prior_draws: pd.DataFrame quantiles: np.ndarray sign_uniforms: np.ndarray @@ -285,19 +306,18 @@ class FitEveryTargetFirstQRF(RegimeGatedQRF): draws its target from that fit, through the function ``predict_from_uniforms`` draws each target with. A run with this class computes what the stage computed when it fitted stage 2 whole and held - every model until it returned, given the inputs the stage passes here; - :attr:`chain_targets`, :attr:`chain_groups` and :attr:`steps` record those - inputs so a test can check them. + every model until it returned, given the settings and inputs the stage + passes here; :attr:`chain_starts` and :attr:`steps` record those so a test + can check them. """ kept_fits: ClassVar[list[object]] = [] - chain_targets: ClassVar[list[tuple[str, ...]]] = [] - chain_groups: ClassVar[list[np.ndarray]] = [] + chain_starts: ClassVar[list[RecordedStage2Start]] = [] steps: ClassVar[list[RecordedStage2Step]] = [] @classmethod def forget_recorded(cls) -> None: - for recorded in (cls.kept_fits, cls.chain_targets, cls.chain_groups, cls.steps): + for recorded in (cls.kept_fits, cls.chain_starts, cls.steps): recorded.clear() def fit(self, *args: object, **kwargs: object) -> object: @@ -314,8 +334,16 @@ def start_chain( weights: object, groups: object = None, ) -> object: - self.chain_targets.append(tuple(targets)) - self.chain_groups.append(np.array(groups, copy=True)) + self.chain_starts.append( + RecordedStage2Start( + seed=self.seed, + n_estimators=self.n_estimators, + gate_calibration=self.gate_calibration, + predictors=tuple(predictors), + targets=tuple(targets), + groups=np.array(groups, copy=True), + ) + ) self._every_target_fit = self.fit( frame_or_df, predictors, targets, weights=weights, groups=groups ) @@ -347,7 +375,7 @@ def fit_draw_next( self.steps.append( RecordedStage2Step( target=target, - recipient_index=recipient_predictors.index.copy(), + recipient_predictors=recipient_predictors.copy(deep=True), prior_draws=raw_prior_draws.copy(deep=True), quantiles=np.array(quantiles, copy=True), sign_uniforms=np.array(sign_uniforms, copy=True), @@ -689,8 +717,12 @@ def print_spi_forest_digests() -> None: ): result = run_spi_forest_scenario(scenario, Path(directory), monkeypatch) digests[scenario] = spi_frozen_digests(result) - here = [platform.system(), platform.machine()] - print(json.dumps({"platform": here, "digests": digests}, indent=1)) + recording = { + "platform": [platform.system(), platform.machine()], + "versions": {name: version(name) for name in SPI_FOREST_DRAW_LIBRARIES}, + "digests": digests, + } + print(json.dumps(recording, indent=1)) __all__ = [name for name in globals() if not name.startswith("__")] From 238b927e0ab625ae1cab5473520cedd2b99d3c20 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:15:10 +0400 Subject: [PATCH 4/8] Compare the cross-fitted SPI digests at ten significant digits The cross-fitted gates are calibrated through BLAS, and the kernel BLAS loads on a given CPU moves the last bits of the transport receipt's statistics, so an exact digest would fail on machines other than the recording one. Digests for that scenario now round floats to ten significant digits and were recorded again from origin/main's code; they match under four OpenBLAS kernels. The in-sample digests and every same-run comparison stay exact. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_spi_forest_release.py | 15 ++- .../microcosm_build/uk_spi_forest_release.py | 107 +++++++++++++----- 2 files changed, 89 insertions(+), 33 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index b26130af57..955b05dfdd 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -21,7 +21,10 @@ natively, and Linux x86_64 (CI's platform) under Docker emulation on Apple silicon. They are checked only where the platform and the versions of the libraries that compute the draws match the recording; elsewhere those tests - skip. + skip. The in-sample scenario's digests are exact to the bit. The cross-fitted + scenario's compare floats at ten significant digits, because its gates are + calibrated through BLAS and the kernel BLAS loads on a given CPU moves the + last bits of the transport receipt; the same-run comparison stays exact. A change that is meant to move these outputs records new digests from its own code on each platform with @@ -110,8 +113,8 @@ "receipts": "1250371e2c3c3fe425c9497dbeedc09fd6046ffcf532d7f05e7f9a3e950d2280", }, "cross_fitted_levels": { - "person": "e938490d187e48bfc2b5f676598d58f898d6d97c71c5f439303a2ca8e64e9760", - "receipts": "aca65550fc5502afb03d78a784018f62dce6d41aa2ed0e5b676e576630caaf3b", + "person": "af8c58d7b9aa6492ecdb263562a49211fb275bcd77deee5dec43a60875317478", + "receipts": "d2e66e45974308791d55de6b2223f4505151c1a4ad00efe526b475ac12c10337", }, }, ("Linux", "x86_64"): { @@ -120,8 +123,8 @@ "receipts": "a6e3f464f10b7c037b908d75a39274f94e253df612b8a99eaa11bf6746cb547e", }, "cross_fitted_levels": { - "person": "db4b50143da3dc3927f6de08d6efe51f57dfa9ad2e87c8c65b47d07abfb448be", - "receipts": "d1103a63326a13d88981e9188b48162b62c7ad75cea2be459ef93a837bf6777c", + "person": "995653c540826dceec157eb1c2fa618e1d29b75ae7856965fe1e957d200331ec", + "receipts": "b801ed247ea3c15c53fb8690c7ac1beb7b2437ea27a3c749bf0f79be1f04a61a", }, }, } @@ -245,7 +248,7 @@ def run(scenario: str) -> _ReferenceRun: def test_output_and_receipts_reproduce_origin_main_bytes(scenario, tracked_run) -> None: expected = _origin_main_digests(scenario) - assert spi_frozen_digests(tracked_run(scenario).result) == expected + assert spi_frozen_digests(scenario, tracked_run(scenario).result) == expected @pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) diff --git a/test_support/microcosm_build/uk_spi_forest_release.py b/test_support/microcosm_build/uk_spi_forest_release.py index 3a0cd2b9fc..4517902a0a 100644 --- a/test_support/microcosm_build/uk_spi_forest_release.py +++ b/test_support/microcosm_build/uk_spi_forest_release.py @@ -107,6 +107,10 @@ **SPI_FOREST_SCENARIOS, **SPI_FOREST_MIXED_GATE_SCENARIOS, } +#: Frozen scenarios whose floats are compared at ten significant digits. Their +#: cross-fitted gates are calibrated through BLAS, and which kernel BLAS loads +#: on a given CPU moves the last bits of the transport receipt's statistics. +SPI_FOREST_ROUNDED_DIGEST_SCENARIOS = frozenset({"cross_fitted_levels"}) def _zero_inflated_amounts(generator: np.random.Generator, position: int) -> np.ndarray: @@ -119,7 +123,7 @@ def _zero_inflated_amounts(generator: np.random.Generator, position: int) -> np. def spi_forest_support() -> UKSPISupportResult: - """FRS people in one-person households, half of them copied to the SPI channel.""" + """FRS people in one-person households, a fifth copied to the SPI channel.""" generator = np.random.default_rng(_SUPPORT_SEED) household_ids = np.arange(1, _HOUSEHOLDS + 1, dtype="int64") @@ -398,91 +402,140 @@ def fit_draw_next( # --------------------------------------------------------------------------- -def _update_with_values(digest, label: object, values: pd.Index | pd.Series) -> None: +def _ten_significant_digits(value: float) -> str: + return format(value, ".9e") + + +def _update_with_values( + digest, + label: object, + values: pd.Index | pd.Series, + *, + float_text: Callable[[float], str] | None, +) -> None: digest.update(repr(label).encode("utf-8")) digest.update(str(values.dtype).encode("utf-8")) - if isinstance(values.dtype, np.dtype) and values.dtype.kind in "biuf": + is_numpy = isinstance(values.dtype, np.dtype) + if float_text is not None and is_numpy and values.dtype.kind == "f": + texts = [float_text(value) for value in values.to_numpy().tolist()] + digest.update(repr(texts).encode("utf-8")) + elif is_numpy and values.dtype.kind in "biuf": digest.update(np.ascontiguousarray(values.to_numpy()).tobytes()) else: digest.update(repr(list(values)).encode("utf-8")) -def table_digest(table: pd.DataFrame) -> str: - """SHA-256 of a table's index and columns: names, dtypes and exact values. +def table_digest( + table: pd.DataFrame, *, float_text: Callable[[float], str] | None = None +) -> str: + """SHA-256 of a table's index and columns: names, dtypes and values. Boolean and numeric columns contribute their raw bytes, so a float that moves in its last bit, or a ``-0.0`` for a ``0.0``, changes the digest. - Every other column contributes the ``repr`` of its values. + With ``float_text``, float columns contribute that text of each value + instead. Every other column contributes the ``repr`` of its values. """ digest = hashlib.sha256() - _update_with_values(digest, ("index", tuple(table.index.names)), table.index) + _update_with_values( + digest, + ("index", tuple(table.index.names)), + table.index, + float_text=float_text, + ) for column in table.columns: - _update_with_values(digest, column, table[column]) + _update_with_values(digest, column, table[column], float_text=float_text) return digest.hexdigest() -def _exact_receipt_value(value: object) -> object: - """A JSON form of a receipt value that keeps types, order and every float bit.""" +def _receipt_value(value: object, float_text: Callable[[float], str]) -> object: + """A JSON form of a receipt value that keeps types and order. + + Each float is written by ``float_text``. + """ if dataclasses.is_dataclass(value) and not isinstance(value, type): return { "dataclass": type(value).__name__, "fields": [ - [item.name, _exact_receipt_value(getattr(value, item.name))] + [item.name, _receipt_value(getattr(value, item.name), float_text)] for item in dataclasses.fields(value) ], } if isinstance(value, Mapping): return { "mapping": [ - [_exact_receipt_value(key), _exact_receipt_value(item)] + [_receipt_value(key, float_text), _receipt_value(item, float_text)] for key, item in value.items() ] } if isinstance(value, list | tuple): return { - type(value).__name__: [_exact_receipt_value(item) for item in value], + type(value).__name__: [_receipt_value(item, float_text) for item in value], } if isinstance(value, np.ndarray): return { "array": str(value.dtype), - "shape": list(value.shape), - "bytes": np.ascontiguousarray(value).tobytes().hex(), + "values": _receipt_value(value.tolist(), float_text), } if isinstance(value, np.generic): - return {"numpy": str(value.dtype), "bytes": value.tobytes().hex()} + return { + "numpy": str(value.dtype), + "value": _receipt_value(value.item(), float_text), + } if isinstance(value, float): - return {"float": value.hex()} + return {"float": float_text(value)} if value is None or isinstance(value, bool | int | str): return value return {"repr": type(value).__name__, "value": repr(value)} -def receipt_digest(value: object) -> str: - """SHA-256 of one receipt, sensitive to key order, types and float bits.""" +def receipt_digest( + value: object, *, float_text: Callable[[float], str] = float.hex +) -> str: + """SHA-256 of one receipt, sensitive to key order, types and float text. - text = json.dumps(_exact_receipt_value(value), separators=(",", ":")) + The default text is the float's exact hexadecimal form. + """ + + text = json.dumps(_receipt_value(value, float_text), separators=(",", ":")) return hashlib.sha256(text.encode("utf-8")).hexdigest() -def spi_result_digests(result: UKSPIIncomeImputationResult) -> dict[str, str]: +def spi_result_digests( + result: UKSPIIncomeImputationResult, + *, + rounded: bool = False, +) -> dict[str, str]: """A digest of the person table and of every other field of the result. + Floats count to the bit, or to ten significant digits when ``rounded``. ``donor_path`` is left out: it names the test's temporary directory. """ - digests = {"person": table_digest(result.person)} + table_float_text = _ten_significant_digits if rounded else None + receipt_float_text = _ten_significant_digits if rounded else float.hex + digests = {"person": table_digest(result.person, float_text=table_float_text)} for item in dataclasses.fields(result): if item.name not in {"person", "donor_path"}: - digests[item.name] = receipt_digest(getattr(result, item.name)) + digests[item.name] = receipt_digest( + getattr(result, item.name), float_text=receipt_float_text + ) return digests -def spi_frozen_digests(result: UKSPIIncomeImputationResult) -> dict[str, str]: - """The person table's digest and one digest over every receipt's.""" +def spi_frozen_digests( + scenario: str, result: UKSPIIncomeImputationResult +) -> dict[str, str]: + """The digests a scenario freezes: the person table's and all receipts' together. - digests = spi_result_digests(result) + A scenario in :data:`SPI_FOREST_ROUNDED_DIGEST_SCENARIOS` compares floats + at ten significant digits, every other scenario to the bit. + """ + + digests = spi_result_digests( + result, rounded=scenario in SPI_FOREST_ROUNDED_DIGEST_SCENARIOS + ) person = digests.pop("person") text = json.dumps(digests, separators=(",", ":")) return { @@ -716,7 +769,7 @@ def print_spi_forest_digests() -> None: tempfile.TemporaryDirectory() as directory, ): result = run_spi_forest_scenario(scenario, Path(directory), monkeypatch) - digests[scenario] = spi_frozen_digests(result) + digests[scenario] = spi_frozen_digests(scenario, result) recording = { "platform": [platform.system(), platform.machine()], "versions": {name: version(name) for name in SPI_FOREST_DRAW_LIBRARIES}, From c4e9425474cc1602eecb8c1255b73bd65269f5e0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:44:46 +0400 Subject: [PATCH 5/8] Check the SPI stage-2 training data and stored draws on every platform The tests now compare the chain's weights, training table and training weights with the FRS rows, the recipients' stage-1 incomes and the stored draws with the returned person table, so these no longer rest on the frozen digests alone. The cross-fitted digests round floats to eight significant digits, which leaves more room for BLAS rounding on CPUs that were not recorded; they were recorded again from origin/main's code and match under four OpenBLAS kernels. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_spi_forest_release.py | 109 ++++++++++++++++-- .../microcosm_build/uk_spi_forest_release.py | 25 ++-- 2 files changed, 119 insertions(+), 15 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index 955b05dfdd..e56e123637 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -5,8 +5,8 @@ stage-2 forests. These tests pin that the stage-1 and reference forests are dead when stage 2 starts, that each reference fold's forests are dead before the next fold is fitted, that each stage-2 target's forests are dead before the -next target is fitted, and that the person table and every receipt stay -byte-identical. +next target is fitted, and that the person table and every receipt do not +change. Two kinds of comparison: @@ -22,7 +22,7 @@ silicon. They are checked only where the platform and the versions of the libraries that compute the draws match the recording; elsewhere those tests skip. The in-sample scenario's digests are exact to the bit. The cross-fitted - scenario's compare floats at ten significant digits, because its gates are + scenario's compare floats at eight significant digits, because its gates are calibrated through BLAS and the kernel BLAS loads on a given CPU moves the last bits of the transport receipt; the same-run comparison stays exact. @@ -63,6 +63,7 @@ from microcosm.build.uk_runtime.spi_income import ( FRS_ONLY_FIT_NAME, SPI_DONOR_FIT_NAME, + SPI_INCOME_RECIPIENT_COLUMN, SPI_MINIMUM_RECIPIENT_AGE, SPI_STAGE2_REVIEWED_ABSENT_OUTPUTS, UKSPIIncomeImputationResult, @@ -113,8 +114,8 @@ "receipts": "1250371e2c3c3fe425c9497dbeedc09fd6046ffcf532d7f05e7f9a3e950d2280", }, "cross_fitted_levels": { - "person": "af8c58d7b9aa6492ecdb263562a49211fb275bcd77deee5dec43a60875317478", - "receipts": "d2e66e45974308791d55de6b2223f4505151c1a4ad00efe526b475ac12c10337", + "person": "52edfe4d85b27b421c14ed5ab3b8f7033ebf518c22a3ebee66fec80d3f8fb4e5", + "receipts": "8704bc3db1560d92f59da45f9482b20d82a21c300f97d4f8313b925842371264", }, }, ("Linux", "x86_64"): { @@ -123,8 +124,8 @@ "receipts": "a6e3f464f10b7c037b908d75a39274f94e253df612b8a99eaa11bf6746cb547e", }, "cross_fitted_levels": { - "person": "995653c540826dceec157eb1c2fa618e1d29b75ae7856965fe1e957d200331ec", - "receipts": "b801ed247ea3c15c53fb8690c7ac1beb7b2437ea27a3c749bf0f79be1f04a61a", + "person": "5c6f5ef054efa03ca36bf4166bb23a36448604b52cfe4adc4dd637496406816b", + "receipts": "72c45abb895e0014fadc8fc6d4a3a8252cb34f5c16563ae5e91711c50df366eb", }, }, } @@ -136,6 +137,18 @@ "individual_savings_account_interest_income": "tax_free_savings_income" } +#: Steps after stage 2 rewrite these on drawn rows, so the person table does not +#: show the value stage 2 read or drew. +_INCOMES_REWRITTEN_AFTER_STAGE2 = frozenset({"self_employment_income"}) +_STAGE2_TARGETS_REWRITTEN_AFTER_THE_DRAW = frozenset( + { + "employee_pension_contributions", + "employer_pension_contributions", + "trading_loss", + "owned_company_carries_on_trade", + } +) + #: Versions of the libraries that compute the draws, on both recordings. _RECORDED_DEPENDENCIES = { "numpy": "2.4.6", @@ -245,7 +258,7 @@ def run(scenario: str) -> _ReferenceRun: @pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) -def test_output_and_receipts_reproduce_origin_main_bytes(scenario, tracked_run) -> None: +def test_output_and_receipts_reproduce_origin_main(scenario, tracked_run) -> None: expected = _origin_main_digests(scenario) assert spi_frozen_digests(scenario, tracked_run(scenario).result) == expected @@ -423,6 +436,86 @@ def test_stage2_chain_gets_the_settings_and_inputs_of_the_whole_fit_and_draw( ) +def _float_values(values: object) -> np.ndarray: + return np.asarray(values, dtype=np.float64) + + +@pytest.mark.parametrize("scenario", SPI_FOREST_ALL_SCENARIOS) +def test_stage2_fits_on_the_frs_rows_and_their_weights(scenario, reference_run) -> None: + """The training table and weights are the FRS rows', as the whole fit had them.""" + + run = reference_run(scenario) + support = spi_forest_support() + person = support.person + base = person.loc[ + person[support_channel_column("person")].eq(BASE_FRS_SUPPORT_CHANNEL) + ] + households = support.household.set_index("household_id") + regions = base["person_household_id"].map(households["region"]) + start = run.chain_starts[0] + table = start.training_table + + assert start.weights == "importance" + assert start.weight_kind == "importance" + assert {step.weights for step in run.steps} == {"importance"} + np.testing.assert_array_equal( + start.training_weights, + _float_values(base["person_household_id"].map(households["household_weight"])), + ) + for target in start.targets: + np.testing.assert_array_equal( + _float_values(table[target]), _float_values(base[target]) + ) + np.testing.assert_array_equal( + _float_values(table["age"]), _float_values(base["age"]) + ) + for column in FRS_ONLY_SPI_FILL_INCOME_PREDICTOR_COLUMNS: + expected = _float_values(base[column]) + if column == "savings_interest_income": + # Training rows condition on gross interest, ISA interest included. + expected = expected + _float_values( + base["individual_savings_account_interest_income"] + ) + np.testing.assert_array_equal(_float_values(table[column]), expected) + for gender in person["gender"].unique(): + np.testing.assert_array_equal( + table[f"gender_{gender}"], base["gender"].eq(gender) + ) + for region in support.household["region"].unique(): + np.testing.assert_array_equal(table[f"region_{region}"], regions.eq(region)) + if "state_pension_receipt" in start.predictors: + np.testing.assert_array_equal( + table["state_pension_receipt"], base["state_pension_reported"].gt(0) + ) + + +@pytest.mark.parametrize("scenario", SPI_FOREST_ALL_SCENARIOS) +def test_stage2_reads_stage1_incomes_and_its_draws_reach_the_person_table( + scenario, reference_run +) -> None: + run = reference_run(scenario) + recipients = run.steps[0].recipient_predictors + person = run.result.person.loc[recipients.index] + drawn = person[SPI_INCOME_RECIPIENT_COLUMN].to_numpy(dtype=bool) + + assert drawn.any() + for column in FRS_ONLY_SPI_FILL_INCOME_PREDICTOR_COLUMNS: + if column not in _INCOMES_REWRITTEN_AFTER_STAGE2: + np.testing.assert_array_equal( + _float_values(recipients[column]), _float_values(person[column]) + ) + if "state_pension_receipt" in recipients: + np.testing.assert_array_equal( + recipients["state_pension_receipt"], + person["hmrc_spi_state_pension_income"].gt(0), + ) + for step in run.steps: + if step.target not in _STAGE2_TARGETS_REWRITTEN_AFTER_THE_DRAW: + np.testing.assert_array_equal( + step.raw_draw[drawn], _float_values(person[step.target])[drawn] + ) + + def test_the_cross_fitted_scenario_fills_every_receipt_read_from_a_model( tracked_run, ) -> None: diff --git a/test_support/microcosm_build/uk_spi_forest_release.py b/test_support/microcosm_build/uk_spi_forest_release.py index 4517902a0a..8f39fa80f5 100644 --- a/test_support/microcosm_build/uk_spi_forest_release.py +++ b/test_support/microcosm_build/uk_spi_forest_release.py @@ -107,7 +107,7 @@ **SPI_FOREST_SCENARIOS, **SPI_FOREST_MIXED_GATE_SCENARIOS, } -#: Frozen scenarios whose floats are compared at ten significant digits. Their +#: Frozen scenarios whose floats are compared at eight significant digits. Their #: cross-fitted gates are calibrated through BLAS, and which kernel BLAS loads #: on a given CPU moves the last bits of the transport receipt's statistics. SPI_FOREST_ROUNDED_DIGEST_SCENARIOS = frozenset({"cross_fitted_levels"}) @@ -287,6 +287,10 @@ class RecordedStage2Start: predictors: tuple[str, ...] targets: tuple[str, ...] groups: np.ndarray + weights: object + weight_kind: str + training_table: pd.DataFrame + training_weights: np.ndarray @dataclass(frozen=True) @@ -294,6 +298,7 @@ class RecordedStage2Step: """What one ``fit_draw_next`` call received, and the draw it returned.""" target: str + weights: object recipient_predictors: pd.DataFrame prior_draws: pd.DataFrame quantiles: np.ndarray @@ -338,6 +343,7 @@ def start_chain( weights: object, groups: object = None, ) -> object: + resolved_weights = frame_or_df.resolve_weights("person") self.chain_starts.append( RecordedStage2Start( seed=self.seed, @@ -346,6 +352,10 @@ def start_chain( predictors=tuple(predictors), targets=tuple(targets), groups=np.array(groups, copy=True), + weights=weights, + weight_kind=resolved_weights.kind.value, + training_table=frame_or_df.table("person").copy(deep=True), + training_weights=np.array(resolved_weights.values, copy=True), ) ) self._every_target_fit = self.fit( @@ -379,6 +389,7 @@ def fit_draw_next( self.steps.append( RecordedStage2Step( target=target, + weights=weights, recipient_predictors=recipient_predictors.copy(deep=True), prior_draws=raw_prior_draws.copy(deep=True), quantiles=np.array(quantiles, copy=True), @@ -402,8 +413,8 @@ def fit_draw_next( # --------------------------------------------------------------------------- -def _ten_significant_digits(value: float) -> str: - return format(value, ".9e") +def _eight_significant_digits(value: float) -> str: + return format(value, ".7e") def _update_with_values( @@ -509,12 +520,12 @@ def spi_result_digests( ) -> dict[str, str]: """A digest of the person table and of every other field of the result. - Floats count to the bit, or to ten significant digits when ``rounded``. + Floats count to the bit, or to eight significant digits when ``rounded``. ``donor_path`` is left out: it names the test's temporary directory. """ - table_float_text = _ten_significant_digits if rounded else None - receipt_float_text = _ten_significant_digits if rounded else float.hex + table_float_text = _eight_significant_digits if rounded else None + receipt_float_text = _eight_significant_digits if rounded else float.hex digests = {"person": table_digest(result.person, float_text=table_float_text)} for item in dataclasses.fields(result): if item.name not in {"person", "donor_path"}: @@ -530,7 +541,7 @@ def spi_frozen_digests( """The digests a scenario freezes: the person table's and all receipts' together. A scenario in :data:`SPI_FOREST_ROUNDED_DIGEST_SCENARIOS` compares floats - at ten significant digits, every other scenario to the bit. + at eight significant digits, every other scenario to the bit. """ digests = spi_result_digests( From b4445e2c5da04848028de5686733c9c8b10f0d9e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:31:16 +0400 Subject: [PATCH 6/8] Describe the SPI forest release in a changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/uk-spi-free-stage1-reference-forests.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/uk-spi-free-stage1-reference-forests.changed.md diff --git a/changelog.d/uk-spi-free-stage1-reference-forests.changed.md b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md new file mode 100644 index 0000000000..adab0b32ee --- /dev/null +++ b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md @@ -0,0 +1 @@ +The UK SPI income imputation (`impute_uk_spi_income_support`, build stage `hmrc_spi_income_spine`) frees each fitted QRF once it has finished drawing from it. The stage-1 model is freed before stage 2 is fitted. Each cross-fitting fold's reference model is freed in `cross_fit_transport` before the next fold is fitted. Stage 2 fits and draws one target at a time, through `RegimeGatedQRF.start_chain` and `fit_draw_next`, with the same per-person uniforms, so only one stage-2 target's forests are in memory at once. Before, the stage-1 model and every fold's reference model stayed referenced until the stage returned, and all of stage 2's targets were fitted before any was drawn. Each receipt the stage reports reads its values from a model before the model is freed: the weight kinds, the sign-classifier outcomes, the level offsets and the level-fit reports. The person table and the receipts are unchanged. From 2d91bd4b11e37ad6e44fadd22c967a689a25791c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:54:34 +0400 Subject: [PATCH 7/8] Say which test checks the SPI stage-2 income predictors and where stage 2's weight kind comes from Co-Authored-By: Claude Opus 5.5 --- .../uk-spi-free-stage1-reference-forests.changed.md | 2 +- .../tests/engine_free/uk/test_uk_spi_forest_release.py | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/changelog.d/uk-spi-free-stage1-reference-forests.changed.md b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md index adab0b32ee..4687d27efd 100644 --- a/changelog.d/uk-spi-free-stage1-reference-forests.changed.md +++ b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md @@ -1 +1 @@ -The UK SPI income imputation (`impute_uk_spi_income_support`, build stage `hmrc_spi_income_spine`) frees each fitted QRF once it has finished drawing from it. The stage-1 model is freed before stage 2 is fitted. Each cross-fitting fold's reference model is freed in `cross_fit_transport` before the next fold is fitted. Stage 2 fits and draws one target at a time, through `RegimeGatedQRF.start_chain` and `fit_draw_next`, with the same per-person uniforms, so only one stage-2 target's forests are in memory at once. Before, the stage-1 model and every fold's reference model stayed referenced until the stage returned, and all of stage 2's targets were fitted before any was drawn. Each receipt the stage reports reads its values from a model before the model is freed: the weight kinds, the sign-classifier outcomes, the level offsets and the level-fit reports. The person table and the receipts are unchanged. +The UK SPI income imputation (`impute_uk_spi_income_support`, build stage `hmrc_spi_income_spine`) frees each fitted QRF once it has finished drawing from it. The stage-1 model is freed before stage 2 is fitted. Each cross-fitting fold's reference model is freed in `cross_fit_transport` before the next fold is fitted. Stage 2 fits and draws one target at a time, through `RegimeGatedQRF.start_chain` and `fit_draw_next`, with the same per-person uniforms, so only one stage-2 target's forests are in memory at once. Before, the stage-1 model and every fold's reference model stayed referenced until the stage returned, and all of stage 2's targets were fitted before any was drawn. The receipts that read a fitted model read it before the model is freed: the stage-1 and reference weight kinds, the sign-classifier outcomes, the level offsets and the level-fit reports. Stage 2's weight kind is read from the chain state `start_chain` returns. The person table and the receipts are unchanged. diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index e56e123637..32b2099573 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -341,8 +341,11 @@ def test_stage2_chain_gets_the_settings_and_inputs_of_the_whole_fit_and_draw( The expected values are written out from what the stage passed to one fit over every target and one ``predict_from_uniforms``. The income predictors - of the drawn rows hold stage-1 draws, which vary by platform, so only the - byte tests cover their values. + of the drawn rows hold stage-1 draws, which vary by platform, so + ``test_stage2_reads_stage1_incomes_and_its_draws_reach_the_person_table`` + checks their values against the returned person table instead. The one + the stage rewrites after stage 2, ``self_employment_income``, is covered + only by the byte tests. """ run = reference_run(scenario) From 754d17f28f21f1ccc22471cfd5e096b4ebab2ff6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:11:56 +0400 Subject: [PATCH 8/8] Read what outlives the SPI stage while the garbage collector is still off The check that no fitted model outlives the stage read its weak references after the tracking block had turned the collector back on, so a model held only by a reference cycle could be collected first and go unnoticed. The tracked run now records what is alive before leaving the block. The changelog and a test docstring also say more exactly what is freed and what is covered. Co-Authored-By: Claude Opus 5.5 --- ...pi-free-stage1-reference-forests.changed.md | 2 +- .../uk/test_uk_spi_forest_release.py | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/changelog.d/uk-spi-free-stage1-reference-forests.changed.md b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md index 4687d27efd..449eb897f6 100644 --- a/changelog.d/uk-spi-free-stage1-reference-forests.changed.md +++ b/changelog.d/uk-spi-free-stage1-reference-forests.changed.md @@ -1 +1 @@ -The UK SPI income imputation (`impute_uk_spi_income_support`, build stage `hmrc_spi_income_spine`) frees each fitted QRF once it has finished drawing from it. The stage-1 model is freed before stage 2 is fitted. Each cross-fitting fold's reference model is freed in `cross_fit_transport` before the next fold is fitted. Stage 2 fits and draws one target at a time, through `RegimeGatedQRF.start_chain` and `fit_draw_next`, with the same per-person uniforms, so only one stage-2 target's forests are in memory at once. Before, the stage-1 model and every fold's reference model stayed referenced until the stage returned, and all of stage 2's targets were fitted before any was drawn. The receipts that read a fitted model read it before the model is freed: the stage-1 and reference weight kinds, the sign-classifier outcomes, the level offsets and the level-fit reports. Stage 2's weight kind is read from the chain state `start_chain` returns. The person table and the receipts are unchanged. +The UK SPI income imputation (`impute_uk_spi_income_support`, build stage `hmrc_spi_income_spine`) frees each fitted QRF as soon as it has finished using it. The stage-1 model is freed before stage 2 is fitted. Each cross-fitting fold's reference model is freed in `cross_fit_transport` before the next fold is fitted. Stage 2 fits and draws one target at a time, through `RegimeGatedQRF.start_chain` and `fit_draw_next`, with the same per-person uniforms, so only one stage-2 target's forests are in memory at once. Before, the stage-1 model and every fold's reference model stayed referenced until the stage returned, and all of stage 2's targets were fitted before any was drawn. The receipts that read a fitted model read it before the model is freed: the stage-1 and reference weight kinds, the sign-classifier outcomes, the level offsets and the level-fit reports. Stage 2's weight kind is read from the chain state `start_chain` returns. The person table and the receipts are unchanged. diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py index 32b2099573..467735c7e2 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_spi_forest_release.py @@ -187,6 +187,10 @@ def _origin_main_digests(scenario: str) -> dict[str, str]: class _TrackedRun: result: UKSPIIncomeImputationResult lifetimes: SPIForestLifetimes + #: What was alive of each fit once the stage returned, read while the + #: garbage collector was still off, so a model held only by a reference + #: cycle counts as alive. + alive_after_stage: tuple[tuple, ...] @pytest.fixture(scope="module") @@ -209,7 +213,12 @@ def run(scenario: str) -> _TrackedRun: ) as lifetimes, ): result = run_spi_forest_scenario(scenario, directory, monkeypatch) - runs[scenario] = _TrackedRun(result, lifetimes) + alive_after_stage = tuple( + alive + for fit in (STAGE1_FIT, REFERENCE_FIT, STAGE2_FIT) + for alive in lifetimes.alive(fit) + ) + runs[scenario] = _TrackedRun(result, lifetimes, alive_after_stage) return runs[scenario] return run @@ -345,7 +354,7 @@ def test_stage2_chain_gets_the_settings_and_inputs_of_the_whole_fit_and_draw( ``test_stage2_reads_stage1_incomes_and_its_draws_reach_the_person_table`` checks their values against the returned person table instead. The one the stage rewrites after stage 2, ``self_employment_income``, is covered - only by the byte tests. + only by the frozen-digest tests, where they run. """ run = reference_run(scenario) @@ -557,10 +566,9 @@ def test_each_fit_starts_after_the_models_it_replaces_are_dead( @pytest.mark.parametrize("scenario", SPI_FOREST_SCENARIOS) def test_no_fitted_model_outlives_the_stage(scenario, tracked_run) -> None: - lifetimes = tracked_run(scenario).lifetimes + """Nothing of any fit is alive once the stage returns, cycles included.""" - for fit in (STAGE1_FIT, REFERENCE_FIT, STAGE2_FIT): - assert lifetimes.alive(fit) == [] + assert tracked_run(scenario).alive_after_stage == () def _fitted_forest_target(gate_calibration: str) -> object: