From e26fef5ce1c40deb0361810ad0df220bfdf0145a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:48:08 +0400 Subject: [PATCH 01/15] Test that QRF leaf arrays match quantile-forest's byte for byte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Failing tests for an in-place leaf array (task 1.2 ยท 1). After growing its trees, quantile-forest 1.4.2 maps every leaf to its training rows in one zero-padded int64 array (trees x nodes x outputs x width). It builds one array per tree and copies the list with np.array(list), which writes every padding byte. The tests expect microcosm.fit.qrf._InPlaceLeafQRF to build the same array in one preallocated buffer: - the array equals the library class's in dtype, shape, C order and tobytes() for a continuous uncapped target, a near-discrete target whose leaves exceed the cap (so the shuffle and truncation run), three outputs, weighted samples with zero weights, and other forest settings; - Python's global random state ends where the library leaves it; - _fit_forest builds the subclass, and its 203-quantile grid predictions and draws equal the library class's, including a leaf over the 4,096 cap; - a chained, regime-gated public fit draws the same values; - the subclass pickles and clones; - quantile-forest is pinned to exactly 1.4.2 in pyproject.toml and uv.lock, and a fit refuses any other installed release before growing a tree. All 25 cases fail: the subclass and the version constant do not exist yet. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_qrf_leaf_array.py | 528 ++++++++++++++++++ 1 file changed, 528 insertions(+) create mode 100644 packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py new file mode 100644 index 0000000000..e86a0bcf7f --- /dev/null +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -0,0 +1,528 @@ +"""The in-place leaf array: byte-identical to quantile-forest's own. + +After growing its trees, quantile-forest 1.4.2 maps every leaf to the training +rows it holds in one zero-padded int64 array of shape (trees x nodes x outputs +x width). The library builds one array per tree and then copies the list into +the final array with ``np.array(list)``; the copy writes every byte, padding +included, so all of it becomes resident memory, and the two copies coexist. +``microcosm.fit.qrf._InPlaceLeafQRF`` allocates the final array once and fills +each tree's slice directly. + +These tests pin that the subclass's array equals the library's byte for byte +(dtype, shape, C order and ``tobytes()``), that it leaves Python's global +``random`` state where the library leaves it, that every prediction and draw is +the same, and that the override refuses any quantile-forest version other than +the one it mirrors. +""" + +from __future__ import annotations + +import importlib.metadata +import pickle +import random +import tomllib + +import numpy as np +import pandas as pd +import pytest +import quantile_forest +from quantile_forest import RandomForestQuantileRegressor +from sklearn.base import clone + +from microcosm.fit import fit, qrf +from test_support.paths import paths_for + +# ---------------------------------------------------------------------------- +# Synthetic donors +# ---------------------------------------------------------------------------- + + +def _continuous_donors(seed: int, rows: int = 600) -> tuple[np.ndarray, np.ndarray]: + """Positive continuous target over coarse predictors. + + The predictors take a few integer values each, so many donor rows share a + predictor vector; a tree cannot split them apart, and leaves hold several + distinct target values. That makes the uncapped width larger than one. + """ + generator = np.random.default_rng(seed) + predictors = generator.integers(0, 8, size=(rows, 3)).astype(np.float64) + target = np.exp(generator.normal(2.5, 0.6, rows)) + predictors[:, 0] + return predictors, target + + +def _near_discrete_donors( + seed: int, rows: int = 3000, predictor_levels: int = 4 +) -> tuple[np.ndarray, np.ndarray]: + """Target with four distinct values, dominated by zero. + + Two predictors with ``predictor_levels`` values each give at most + ``predictor_levels**2`` distinct predictor vectors, so leaves hold hundreds + of rows: far more than the small caps the tests set. + """ + generator = np.random.default_rng(seed) + predictors = generator.integers(0, predictor_levels, size=(rows, 2)).astype( + np.float64 + ) + target = generator.choice( + [0.0, 0.25, 0.5, 1.0], size=rows, p=[0.85, 0.05, 0.05, 0.05] + ) + return predictors, target + + +def _sample_weights(seed: int, rows: int) -> np.ndarray: + """Positive weights with a fifth of the rows at exactly zero. + + The library drops zero-weight rows from each leaf, and refills a leaf + that empties with a placeholder, so both branches run. + """ + generator = np.random.default_rng(seed) + weights = generator.uniform(0.1, 3.0, rows) + weights[generator.random(rows) < 0.2] = 0.0 + return weights + + +# ---------------------------------------------------------------------------- +# Capturing the leaf array each class builds +# ---------------------------------------------------------------------------- + + +def _fit_capturing_leaf_array( + model_class: type[RandomForestQuantileRegressor], + predictors: np.ndarray, + target: np.ndarray, + *, + sample_weight: np.ndarray | None = None, + **parameters, +) -> tuple[RandomForestQuantileRegressor, np.ndarray, object]: + """Fit ``model_class`` and return the array its ``_get_y_train_leaves`` built. + + Also returns Python's global ``random`` state after the fit. The global + state is seeded to the same value before every fit, so two fits that make + the same ``random.seed``/``random.shuffle`` calls end in the same state. + """ + captured: dict[str, np.ndarray] = {} + + class _Capturing(model_class): + def _get_y_train_leaves(self, *args, **kwargs): + leaves = super()._get_y_train_leaves(*args, **kwargs) + captured["leaves"] = leaves + return leaves + + random.seed(20261117) + model = _Capturing(**parameters) + model.fit(predictors, target, sample_weight=sample_weight) + return model, captured["leaves"], random.getstate() + + +def _assert_byte_identical(in_place: np.ndarray, library: np.ndarray) -> None: + assert isinstance(in_place, np.ndarray) + assert in_place.dtype == library.dtype == np.int64 + assert in_place.shape == library.shape + assert in_place.flags.c_contiguous and library.flags.c_contiguous + assert in_place.tobytes() == library.tobytes() + + +def _assert_same_fit( + predictors: np.ndarray, + target: np.ndarray, + *, + sample_weight: np.ndarray | None = None, + **parameters, +) -> np.ndarray: + """Fit both classes on the same inputs and compare everything they store.""" + parameters = {"n_estimators": 6, "random_state": 11, "n_jobs": 1, **parameters} + library_model, library_leaves, library_random_state = _fit_capturing_leaf_array( + RandomForestQuantileRegressor, + predictors, + target, + sample_weight=sample_weight, + **parameters, + ) + in_place_model, in_place_leaves, in_place_random_state = _fit_capturing_leaf_array( + qrf._InPlaceLeafQRF, + predictors, + target, + sample_weight=sample_weight, + **parameters, + ) + _assert_byte_identical(in_place_leaves, library_leaves) + # The forest object keeps the array without copying it. + assert np.shares_memory( + np.asarray(in_place_model.forest_.y_train_leaves), in_place_leaves + ) + _assert_byte_identical( + np.asarray(in_place_model.forest_.y_train_leaves), + np.asarray(library_model.forest_.y_train_leaves), + ) + assert ( + np.asarray(in_place_model.forest_.y_train).tobytes() + == np.asarray(library_model.forest_.y_train).tobytes() + ) + assert in_place_random_state == library_random_state + quantiles = list(qrf._QUANTILE_GRID) + in_place_predictions = np.asarray( + in_place_model.predict(predictors[:200], quantiles=quantiles) + ) + library_predictions = np.asarray( + library_model.predict(predictors[:200], quantiles=quantiles) + ) + assert in_place_predictions.tobytes() == library_predictions.tobytes() + return in_place_leaves + + +# ---------------------------------------------------------------------------- +# Byte identity of the leaf array +# ---------------------------------------------------------------------------- + + +def test_continuous_target_without_a_cap_matches_the_library() -> None: + predictors, target = _continuous_donors(seed=1) + leaves = _assert_same_fit(predictors, target, max_samples_leaf=None) + # The uncapped width is the widest leaf, so it exceeds one here. + assert leaves.shape[-1] > 1 + + +def test_near_discrete_target_over_the_cap_matches_the_library(monkeypatch) -> None: + """Leaves larger than the cap are shuffled and truncated identically.""" + shuffle_calls: list[int] = [] + original_shuffle = random.shuffle + + def counting_shuffle(sequence): + shuffle_calls.append(len(sequence)) + return original_shuffle(sequence) + + monkeypatch.setattr(random, "shuffle", counting_shuffle) + cap = 16 + predictors, target = _near_discrete_donors(seed=2) + leaves = _assert_same_fit(predictors, target, max_samples_leaf=cap) + assert leaves.shape[-1] == cap + # Both fits shuffled the same leaves, each larger than the cap, before + # truncating them; the library fit ran first. + half = len(shuffle_calls) // 2 + assert half > 0 + assert shuffle_calls[:half] == shuffle_calls[half:] + assert min(shuffle_calls) > cap + + +@pytest.mark.parametrize("max_samples_leaf", [None, 5]) +def test_several_outputs_match_the_library(max_samples_leaf) -> None: + predictors, first = _continuous_donors(seed=3) + generator = np.random.default_rng(3) + target = np.column_stack( + [first, first * generator.uniform(0.5, 2.0, len(first)), predictors[:, 1]] + ) + leaves = _assert_same_fit(predictors, target, max_samples_leaf=max_samples_leaf) + assert leaves.shape[2] == 3 + + +@pytest.mark.parametrize("max_samples_leaf", [None, 7, 1]) +def test_weighted_samples_match_the_library(max_samples_leaf) -> None: + predictors, target = _near_discrete_donors(seed=4, rows=800, predictor_levels=6) + target = target + predictors[:, 0] + weights = _sample_weights(seed=4, rows=len(target)) + _assert_same_fit( + predictors, + target, + sample_weight=weights, + max_samples_leaf=max_samples_leaf, + ) + + +@pytest.mark.parametrize( + "parameters", + [ + pytest.param({}, id="library-default-one-sample-per-leaf"), + pytest.param({"max_samples_leaf": 0.02}, id="fractional-cap"), + pytest.param({"max_samples_leaf": None, "bootstrap": False}, id="no-bootstrap"), + pytest.param({"max_samples_leaf": 9, "max_samples": 0.5}, id="half-bootstrap"), + pytest.param( + {"max_samples_leaf": None, "max_samples": 150}, id="row-bootstrap" + ), + ], +) +def test_other_forest_settings_match_the_library(parameters) -> None: + """Settings microcosm does not use still give the library's array.""" + predictors, target = _continuous_donors(seed=5, rows=400) + _assert_same_fit(predictors, target, **parameters) + + +def test_parallel_tree_fitting_matches_the_library() -> None: + predictors, target = _continuous_donors(seed=6) + _assert_same_fit(predictors, target, max_samples_leaf=None, n_jobs=-1) + + +# ---------------------------------------------------------------------------- +# microcosm's forest construction uses the subclass +# ---------------------------------------------------------------------------- + + +def _fit_forest_with( + model_class: type[RandomForestQuantileRegressor], + predictors: np.ndarray, + target: np.ndarray, + weights: np.ndarray | None, + *, + seed: int, + n_estimators: int, + max_samples_leaf: int | float | None, +) -> qrf._Forest: + """Run microcosm's ``_fit_forest`` with ``model_class`` as its forest.""" + with pytest.MonkeyPatch.context() as patch: + patch.setattr(qrf, "_InPlaceLeafQRF", model_class) + return qrf._fit_forest( + predictors, + target, + tuple(f"x{index}" for index in range(predictors.shape[1])), + weights, + seed=seed, + n_estimators=n_estimators, + max_samples_leaf=max_samples_leaf, + rng=np.random.default_rng(seed), + ) + + +@pytest.mark.parametrize( + ("donors", "weighted"), + [ + pytest.param("continuous", True, id="continuous-weighted"), + pytest.param("near_discrete", False, id="near-discrete-capped"), + ], +) +def test_fit_forest_draws_match_the_library(donors, weighted) -> None: + """``_fit_forest`` builds the subclass, and its grid and draws are unchanged.""" + if donors == "continuous": + predictors, target = _continuous_donors(seed=7, rows=900) + else: + predictors, target = _near_discrete_donors(seed=7, rows=1500) + weights = _sample_weights(seed=7, rows=len(target)) + 0.05 if weighted else None + arguments = {"seed": 13, "n_estimators": 8, "max_samples_leaf": None} + in_place = _fit_forest_with( + qrf._InPlaceLeafQRF, predictors, target, weights, **arguments + ) + library = _fit_forest_with( + RandomForestQuantileRegressor, predictors, target, weights, **arguments + ) + assert type(in_place.model) is qrf._InPlaceLeafQRF + assert type(library.model) is RandomForestQuantileRegressor + if donors == "near_discrete": + assert in_place.model.max_samples_leaf == qrf._DISCRETE_Y_LEAF_BOUND + _assert_byte_identical( + np.asarray(in_place.model.forest_.y_train_leaves), + np.asarray(library.model.forest_.y_train_leaves), + ) + recipients = pd.DataFrame(predictors[:400], columns=list(in_place.columns)) + grid = list(qrf._QUANTILE_GRID) + assert ( + np.asarray( + in_place.model.predict(recipients.to_numpy(), quantiles=grid) + ).tobytes() + == np.asarray( + library.model.predict(recipients.to_numpy(), quantiles=grid) + ).tobytes() + ) + uniforms = np.random.default_rng(99).random(len(recipients)) + assert ( + in_place.draw(recipients, uniforms).tobytes() + == library.draw(recipients, uniforms).tobytes() + ) + + +def test_fit_forest_truncates_leaves_over_the_production_cap(monkeypatch) -> None: + """A near-discrete target whose leaves exceed the 4,096 cap is unchanged. + + One binary predictor leaves two predictor vectors, so each leaf keeps about + half of the 12,000 bootstrap rows, well over :data:`_DISCRETE_Y_LEAF_BOUND`. + """ + generator = np.random.default_rng(8) + rows = 12_000 + predictors = generator.integers(0, 2, size=(rows, 1)).astype(np.float64) + target = generator.choice([0.0, 1.0, 2.0], size=rows, p=[0.9, 0.05, 0.05]) + shuffled: list[int] = [] + original_shuffle = random.shuffle + + def counting_shuffle(sequence): + shuffled.append(len(sequence)) + return original_shuffle(sequence) + + arguments = {"seed": 17, "n_estimators": 3, "max_samples_leaf": None} + monkeypatch.setattr(random, "shuffle", counting_shuffle) + random.seed(20261117) + library = _fit_forest_with( + RandomForestQuantileRegressor, predictors, target, None, **arguments + ) + library_random_state = random.getstate() + library_shuffles = list(shuffled) + shuffled.clear() + random.seed(20261117) + in_place = _fit_forest_with( + qrf._InPlaceLeafQRF, predictors, target, None, **arguments + ) + assert type(in_place.model) is qrf._InPlaceLeafQRF + assert shuffled == library_shuffles + assert min(shuffled) > qrf._DISCRETE_Y_LEAF_BOUND + assert random.getstate() == library_random_state + in_place_leaves = np.asarray(in_place.model.forest_.y_train_leaves) + assert in_place_leaves.shape[-1] == qrf._DISCRETE_Y_LEAF_BOUND + _assert_byte_identical( + in_place_leaves, np.asarray(library.model.forest_.y_train_leaves) + ) + recipients = pd.DataFrame(predictors[:50], columns=list(in_place.columns)) + uniforms = np.random.default_rng(5).random(len(recipients)) + assert ( + in_place.draw(recipients, uniforms).tobytes() + == library.draw(recipients, uniforms).tobytes() + ) + + +def test_public_fit_and_predict_match_the_library(monkeypatch) -> None: + """A chained, regime-gated fit draws the same values with either class. + + The targets cover a positive continuous amount, a sign-mixed amount (one + positive and one negative forest behind a gate) and a near-discrete ratio + (the 4,096 cap), each chained on the ones before it. + """ + generator = np.random.default_rng(9) + rows = 1200 + age = generator.integers(18, 80, rows).astype(np.float64) + region = generator.integers(0, 5, rows).astype(np.float64) + donor = pd.DataFrame( + { + "age": age, + "region": region, + "wage": np.round(np.exp(generator.normal(3.0, 0.5, rows)), 2), + "gain": np.where( + generator.random(rows) < 0.5, + -np.exp(generator.normal(5.0, 1.0, rows)), + np.exp(generator.normal(6.0, 1.0, rows)), + ), + "ratio": generator.choice([0.0, 0.2, 0.5, 1.0], rows), + } + ) + weights = generator.uniform(0.5, 4.0, rows) + recipient = pd.DataFrame( + { + "age": generator.integers(18, 80, 500).astype(np.float64), + "region": generator.integers(0, 5, 500).astype(np.float64), + } + ) + targets = ["wage", "gain", "ratio"] + + def fit_and_draw() -> pd.DataFrame: + model = fit( + donor, + ["age", "region"], + targets, + weights=weights, + n_estimators=6, + seed=21, + ) + return model.predict(recipient) + + in_place_draws = fit_and_draw() + monkeypatch.setattr(qrf, "_InPlaceLeafQRF", RandomForestQuantileRegressor) + library_draws = fit_and_draw() + pd.testing.assert_frame_equal(in_place_draws, library_draws, check_exact=True) + for target in targets: + assert ( + in_place_draws[target].to_numpy().tobytes() + == library_draws[target].to_numpy().tobytes() + ) + + +# ---------------------------------------------------------------------------- +# The subclass behaves as an ordinary estimator +# ---------------------------------------------------------------------------- + + +def test_subclass_pickles_and_clones_like_the_library_class() -> None: + predictors, target = _continuous_donors(seed=10, rows=300) + model = qrf._InPlaceLeafQRF( + n_estimators=4, max_samples_leaf=None, random_state=3, n_jobs=1 + ) + model.fit(predictors, target) + forest = qrf._Forest(model=model, columns=("a", "b", "c")) + restored = pickle.loads(pickle.dumps(forest)) + assert type(restored.model) is qrf._InPlaceLeafQRF + _assert_byte_identical( + np.asarray(restored.model.forest_.y_train_leaves), + np.asarray(model.forest_.y_train_leaves), + ) + recipients = pd.DataFrame(predictors[:40], columns=["a", "b", "c"]) + uniforms = np.linspace(0.0, 1.0, len(recipients)) + assert ( + restored.draw(recipients, uniforms).tobytes() + == forest.draw(recipients, uniforms).tobytes() + ) + cloned = clone(model) + assert type(cloned) is qrf._InPlaceLeafQRF + assert cloned.get_params() == model.get_params() + + +# ---------------------------------------------------------------------------- +# The exact quantile-forest version the override mirrors +# ---------------------------------------------------------------------------- + + +def test_installed_quantile_forest_is_the_version_the_override_mirrors() -> None: + supported = qrf._SUPPORTED_QUANTILE_FOREST_VERSION + assert quantile_forest.__version__ == supported + assert importlib.metadata.version("quantile-forest") == supported + + +def test_dependency_and_lock_pin_the_mirrored_version_exactly() -> None: + supported = qrf._SUPPORTED_QUANTILE_FOREST_VERSION + paths = paths_for("microcosm-fit") + project = tomllib.loads((paths.package / "pyproject.toml").read_text()) + declared = [ + requirement.replace(" ", "") + for requirement in project["project"]["dependencies"] + if requirement.replace(" ", "").startswith("quantile-forest") + ] + assert declared == [f"quantile-forest=={supported}"] + + lock = tomllib.loads((paths.repository / "uv.lock").read_text()) + locked = [ + package["version"] + for package in lock["package"] + if package["name"] == "quantile-forest" + ] + assert locked == [supported] + (microcosm_fit,) = [ + package for package in lock["package"] if package["name"] == "microcosm-fit" + ] + locked_specifiers = [ + requirement["specifier"] + for requirement in microcosm_fit["metadata"]["requires-dist"] + if requirement["name"] == "quantile-forest" + ] + assert locked_specifiers == [f"=={supported}"] + + +@pytest.mark.parametrize("installed", ["1.4.3", "1.4.1", "1.5.0", "1.4.2.post1"]) +def test_fit_refuses_another_quantile_forest_version(monkeypatch, installed) -> None: + monkeypatch.setattr(quantile_forest, "__version__", installed) + predictors, target = _continuous_donors(seed=12, rows=60) + model = qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=0) + with pytest.raises(RuntimeError) as refusal: + model.fit(predictors, target) + message = str(refusal.value) + assert installed in message + assert qrf._SUPPORTED_QUANTILE_FOREST_VERSION in message + # The refusal comes before any tree is grown. + assert not hasattr(model, "estimators_") + + +def test_fit_forest_refuses_another_quantile_forest_version(monkeypatch) -> None: + monkeypatch.setattr(quantile_forest, "__version__", "1.4.3") + predictors, target = _continuous_donors(seed=13, rows=60) + with pytest.raises(RuntimeError, match="1.4.3"): + qrf._fit_forest( + predictors, + target, + ("a", "b", "c"), + None, + seed=1, + n_estimators=2, + max_samples_leaf=None, + rng=np.random.default_rng(1), + ) From 3c313b79355802aabfc33bee19b001100ac90396 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:48:08 +0400 Subject: [PATCH 02/15] Fill the QRF leaf array in place and pin quantile-forest 1.4.2 _InPlaceLeafQRF subclasses RandomForestQuantileRegressor and overrides the private _get_y_train_leaves. It allocates the final (trees x nodes x outputs x width) int64 array once with np.zeros and has the per-tree fill write into each tree's slice, instead of building one array per tree and copying the list with np.array(list). The width, apply(), bootstrap replay, rank computation, global random.seed()/shuffle() calls in tree order, and the writes are the library's own, so the array is byte-identical and every prediction is unchanged. np.zeros pages that are never written stay unmapped, so internal-node rows and padding past each leaf's entries cost no resident memory, and the second copy is gone. _fit_forest now builds the subclass; no other non-test code constructs the library's forest. quantile-forest is pinned to ==1.4.2 (uv.lock already resolved 1.4.2), and _InPlaceLeafQRF.fit raises a RuntimeError naming both versions when any other release is imported, before growing a tree. tools/measure_qrf_leaf_memory.py fits one synthetic forest shaped like the CPS-ORG wage fit (100 trees, continuous positive target, no cap) or a base near-discrete fit (32 trees, 4,096 cap) with each class in a fresh process, and reports each process's peak RSS before and after the fit, and whether the two leaf arrays hash the same. At 3,000 near-discrete rows the library fit added 0.93 GiB and the in-place fit 0.11 GiB; at 4,000 wage rows (width 280) 1.33 GiB and 1.03 GiB. Both arrays were identical. Re-pins for the changed bytes: - APPROVED_UV_LOCK_SHA256, for the uv.lock specifier change; - the US F0 seed map, seed protocol and spec_sha256 pins, which attest microcosm.fit.qrf's source: repin, coverage (41/41), repin, --check clean; - the fit.qrf parity fixture's implementation hash and node keys (graph_parity_repin fit.qrf), which left every direct.csv unchanged. Co-Authored-By: Claude Opus 5.5 --- .../qrf-leaf-array-in-place.changed.md | 5 + docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 6 +- .../build/us_runtime/worker_identity.py | 2 +- .../shared/test_spec_engine_loader.py | 3 +- .../us/test_us_multispine_pool_tool.py | 3 +- packages/microcosm-fit/pyproject.toml | 7 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 235 +++++++++++++- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 298 ++++++++++++++++++ uv.lock | 2 +- 11 files changed, 562 insertions(+), 17 deletions(-) create mode 100644 changelog.d/qrf-leaf-array-in-place.changed.md create mode 100644 tools/measure_qrf_leaf_memory.py diff --git a/changelog.d/qrf-leaf-array-in-place.changed.md b/changelog.d/qrf-leaf-array-in-place.changed.md new file mode 100644 index 0000000000..ff8246b60f --- /dev/null +++ b/changelog.d/qrf-leaf-array-in-place.changed.md @@ -0,0 +1,5 @@ +microcosm-fit's QRF forests build their leaf array in place. quantile-forest stores, for every tree, the training rows each leaf holds in one zero-padded int64 array (trees x nodes x outputs x width); version 1.4.2 builds one array per tree and then copies the list into the final array, which writes every padding byte and makes the whole padded array resident while both copies exist. `_fit_forest` now builds `_InPlaceLeafQRF`, a subclass that allocates the final array once and fills each tree's slice directly. The array is byte-identical to the library's, so every prediction and draw is unchanged; tests compare the two classes byte for byte on continuous, capped near-discrete, multi-output and weighted fits, and compare grid predictions and draws. + +- quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method, and `_InPlaceLeafQRF.fit` refuses any other installed release before growing a tree. +- `tools/measure_qrf_leaf_memory.py` fits one synthetic CPS-ORG-like wage forest or one capped near-discrete forest with each class in a fresh process and reports each fit's peak resident memory. +- Pickling or deep-copying a fitted forest still writes the full padded array, as before. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 348354e26c..d4d1a0adaa 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", + "protocol_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2" }, "failures": [], "observed": { - "map_sha256": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", + "protocol_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index fff542b87b..52ae74bca1 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -402,8 +402,10 @@ # microcosm#1641 moves both again: it rewords docstrings and a comment in # solve and the delivery gate's docstring in ssi_take_up, which now names # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. - "seed_map": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "seed_protocol": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the + # forests' leaf arrays are byte-identical, and no draw changes. + "seed_map": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", + "seed_protocol": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py index c8a8996ea0..f534791af7 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py @@ -28,7 +28,7 @@ PRIMARY_QRF_WORKER_MODULE = "microcosm.build.us_runtime.puf_qrf_worker" PRIMARY_QRF_INTERPRETER_PLACEHOLDER = "{python_interpreter}" APPROVED_UV_LOCK_SHA256 = ( - "6a823b13f3ee70a454ebf6828631037fc0f13a9e0dc8e7624ae8dfb68e0f4b89" + "67037e0ecbd8d4eb700756371a8ba1c7637dc3b884c44ccd0126fdb757e5df88" ) LEGACY_CAMPAIGN_UV_LOCK_SHA256 = ( "27f47e385cfa35e2644a37410d1804b361ad9aee123577551c8421547bda65ee" diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 56e430cbe6..c29723c544 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -32,8 +32,9 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # kernels' bytes too. # microcosm#1641's docstring and comment wording in solve and ssi_take_up # moves it again. + # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "cb9742d5089eddb8783ee1cb890206b33a35efe5ff572656dbd58a1b95ea1e28" + "dda333cf1ccbad20d8d9b26ad2a73925675f4dd171256832ca2cae09153d4953" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index a22f1927d5..93338ab6d9 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -363,7 +363,8 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1543's fit input checks in microcosm.fit.qrf move it again. # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84", + # The in-place QRF leaf array in microcosm.fit.qrf moves it again. + "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09", }, } diff --git a/packages/microcosm-fit/pyproject.toml b/packages/microcosm-fit/pyproject.toml index 04c3da08d7..a947a31000 100644 --- a/packages/microcosm-fit/pyproject.toml +++ b/packages/microcosm-fit/pyproject.toml @@ -17,7 +17,12 @@ dependencies = [ # bound: this package's own sklearn usage (HistGradientBoostingClassifier, # forest .fit() without sample_weight) is stable across 1.5-1.9. "scikit-learn>=1.5", - "quantile-forest>=1.4.2", + # Exact: microcosm.fit.qrf._InPlaceLeafQRF replaces the private + # RandomForestQuantileRegressor._get_y_train_leaves with a copy of 1.4.2's + # that fills the leaf array in place, and refuses to fit under any other + # release (_SUPPORTED_QUANTILE_FOREST_VERSION). Raise both together, after + # comparing the override with the new release's method. + "quantile-forest==1.4.2", "numpy>=2", "pandas>=2.3", ] diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 89d322dc10..3281265f60 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -60,13 +60,17 @@ import math import numbers import os +import random +import warnings from collections.abc import Callable, Mapping, Sequence from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, replace import numpy as np import pandas as pd +import quantile_forest from quantile_forest import RandomForestQuantileRegressor +from quantile_forest import _quantile_forest as _quantile_forest_module from sklearn.ensemble import HistGradientBoostingClassifier from microcosm.fit.model import ( @@ -1142,6 +1146,233 @@ def _locate_rows( return np.clip(out, 0.0, np.nextafter(1.0, 0.0)) +#: The quantile-forest release whose private leaf-array builder +#: :class:`_InPlaceLeafQRF` reproduces. ``microcosm-fit``'s ``pyproject.toml`` +#: pins exactly this release, and a fit under any other installed release is +#: refused, because a private method can change in any release. +_SUPPORTED_QUANTILE_FOREST_VERSION = "1.4.2" + + +def _require_supported_quantile_forest() -> None: + """Refuse a quantile-forest release the in-place override was not checked on. + + Raises: + RuntimeError: If the imported ``quantile_forest`` is not + :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. + """ + installed = quantile_forest.__version__ + if installed != _SUPPORTED_QUANTILE_FOREST_VERSION: + raise RuntimeError( + "microcosm-fit builds QRF leaf arrays with a copy of quantile-forest " + f"{_SUPPORTED_QUANTILE_FOREST_VERSION}'s private " + "RandomForestQuantileRegressor._get_y_train_leaves, but quantile-forest " + f"{installed} is installed. Install quantile-forest==" + f"{_SUPPORTED_QUANTILE_FOREST_VERSION}, the release microcosm-fit " + "pins, or compare the override with the new release's method and " + "update the pin and _SUPPORTED_QUANTILE_FOREST_VERSION together." + ) + + +def _fill_tree_leaves( + tree_leaves: np.ndarray, + bootstrap_indices: np.ndarray, + draw_leaves: np.ndarray, + sample_weight: np.ndarray | None, + leaf_subsample: bool, + max_samples_leaf: int, + random_state: int, +) -> None: + """Write one tree's leaf-to-training-row map into ``tree_leaves``. + + The body is quantile-forest 1.4.2's + ``BaseForestQuantileRegressor._get_y_train_leaves_slice`` with one + change: it writes into the caller's slice of the forest-wide array instead + of allocating a zeroed array of its own and returning it. Every other step, + including the grouping helper, the global ``random.seed``/``random.shuffle`` + calls and the order of the writes, is the library's. + + Args: + tree_leaves: This tree's zeroed ``(nodes, outputs, width)`` slice of the + forest-wide array. + bootstrap_indices: ``(draws, outputs)`` 1-based positions in the sorted + training values of this tree's bootstrap draws. + draw_leaves: The leaf each bootstrap draw reaches in this tree. + sample_weight: Sorted training weights, or ``None``. + leaf_subsample: Whether leaves are cut to ``max_samples_leaf`` entries. + max_samples_leaf: The width of every leaf's row. + random_state: This tree's seed, which also seeds the leaf subsample. + """ + n_outputs = bootstrap_indices.shape[1] + + if sample_weight is not None: + sample_weight = np.squeeze(sample_weight) + + leaf_indices, leaf_values_list = _quantile_forest_module.group_indices_by_value( + draw_leaves + ) + + if leaf_subsample or sample_weight is not None: + if leaf_subsample: + random.seed(random_state) + + for leaf in range(len(leaf_values_list)): + if sample_weight is not None: + # quantile-forest 1.4.2 drops zero-weight entries this way. + weight_mask = sample_weight[leaf_values_list[leaf] - 1] > 0 + leaf_values_list[leaf] = leaf_values_list[leaf][weight_mask] + if leaf_subsample: + if len(leaf_values_list[leaf]) > max_samples_leaf: + random.shuffle(leaf_values_list[leaf]) + leaf_values_list[leaf] = leaf_values_list[leaf][:max_samples_leaf] + if len(leaf_values_list[leaf]) == 0: + leaf_values_list[leaf] = [0] + + if max_samples_leaf == 1: + sorted_positions = bootstrap_indices[leaf_values_list].reshape(-1, 1, n_outputs) + for output in range(n_outputs): + tree_leaves[leaf_indices, output, 0] = sorted_positions[:, 0, output] + else: + filled = _quantile_forest_module.map_indices_to_leaves( + y_train_leaves_slice=tree_leaves, + bootstrap_indices=bootstrap_indices, + leaf_indices=leaf_indices, + leaf_values_list=leaf_values_list, + ) + # The compiled helper writes through a memoryview of its argument and + # returns a view of the same buffer; a copy would leave this slice zero. + if not np.may_share_memory(filled, tree_leaves): + raise RuntimeError( + "quantile-forest's map_indices_to_leaves returned a copy instead " + "of filling the array it was given." + ) + + +class _InPlaceLeafQRF(RandomForestQuantileRegressor): + """A quantile forest whose leaf array is filled in place. + + After growing its trees, quantile-forest maps every leaf to the training + rows it holds in one int64 array of shape ``(trees, nodes, outputs, + width)``, zero-padded to the widest leaf (or to ``max_samples_leaf`` when + that is set). quantile-forest 1.4.2 builds one zeroed array per tree and + then copies the list into the final array with ``np.array(list)``. That + copy writes every byte, padding included, so the whole padded array + becomes resident memory, and for a while both the per-tree arrays and the + copy exist. Pages of an ``np.zeros`` array that are never written cost no + resident memory. + + This subclass allocates the final array once and writes each tree's + entries straight into that tree's slice (:func:`_fill_tree_leaves`). The + width, ``apply``, bootstrap replay and rank computation are the library's + own, as are the ``random.seed``/``random.shuffle`` calls in tree order and + the dtype, shape and C order of the result, so the array is byte-identical + to the library's and so is every prediction. Only the private + ``_get_y_train_leaves`` is replaced, so :meth:`fit` refuses any + quantile-forest release other than + :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. + + Pickling a fitted forest, or deep-copying it, still writes the full padded + array: quantile-forest's ``QuantileForest.__reduce__`` hands the whole + array to pickle. + """ + + def fit(self, X, y, sample_weight=None, sparse_pickle=False): # noqa: N803 + """Check the installed quantile-forest, then fit as the library does.""" + _require_supported_quantile_forest() + return super().fit( + X, y, sample_weight=sample_weight, sparse_pickle=sparse_pickle + ) + + def _get_y_train_leaves( + self, features, sorted_targets, sorter=None, sample_weight=None + ): + """Return the leaf array, built as quantile-forest 1.4.2 builds it. + + The steps up to the per-tree fill are quantile-forest 1.4.2's + ``BaseForestQuantileRegressor._get_y_train_leaves``, unchanged. The + per-tree fill writes into one preallocated array instead of returning + a list that ``np.array`` then copies. + """ + library = _quantile_forest_module + n_samples = features.shape[0] + n_outputs = sorted_targets.shape[-1] + + if isinstance(self.max_samples_leaf, (numbers.Integral, np.integer)): + max_samples_leaf = self.max_samples_leaf + leaf_subsample = True + elif isinstance(self.max_samples_leaf, numbers.Real): + max_samples_leaf = int(math.ceil(self.max_samples_leaf * n_samples)) + leaf_subsample = True + elif self.max_samples_leaf is None: + max_samples_leaf = self.max_samples_leaf + leaf_subsample = False + else: + raise ValueError( + "`max_samples_leaf` must be of integer, float, or None type, " + f"got {type(self.max_samples_leaf)}." + ) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + sample_leaves = self.apply(features) + + if self.bootstrap: + arguments = (n_samples, self.max_samples) + if library.sklearn_version >= library.parse_version("1.9.0"): + arguments += (self.sample_weight_,) + n_samples_bootstrap = library._get_n_samples_bootstrap(*arguments) + + shape = ( + n_samples if not self.bootstrap else n_samples_bootstrap, + self.n_estimators, + ) + bootstrap_indices = np.empty(shape, dtype=np.int64) + draw_leaves = np.empty(shape, dtype=np.int64) + for tree, estimator in enumerate(self.estimators_): + if self.bootstrap: + arguments = (estimator.random_state, n_samples, n_samples_bootstrap) + if library.sklearn_version >= library.parse_version("1.9.0"): + arguments += (self.sample_weight_,) + bootstrap_indices[:, tree] = library._generate_sample_indices( + *arguments + ) + else: + bootstrap_indices[:, tree] = np.arange(n_samples) + draw_leaves[:, tree] = sample_leaves[bootstrap_indices[:, tree], tree] + + if sorter is not None: + bootstrap_indices = np.argsort(sorter, axis=0)[bootstrap_indices] + + bootstrap_indices = bootstrap_indices.reshape(-1, self.n_estimators, n_outputs) + bootstrap_indices += 1 # 0 marks an empty entry + + max_node_count = 0 + max_samples_leaf = 0 if not leaf_subsample else max_samples_leaf + for tree, estimator in enumerate(self.estimators_): + node_count = estimator.tree_.node_count + max_node_count = max(max_node_count, node_count) + if not leaf_subsample: + sample_count = np.max(np.bincount(draw_leaves[:, tree])) + max_samples_leaf = max(max_samples_leaf, sample_count) + + # The library stacks one array per tree with np.array(list), which + # gives exactly this dtype, shape and C order. + leaves = np.zeros( + (len(self.estimators_), max_node_count, n_outputs, max_samples_leaf), + dtype=np.int64, + ) + for tree, estimator in enumerate(self.estimators_): + _fill_tree_leaves( + leaves[tree], + bootstrap_indices[:, tree], + draw_leaves[:, tree], + sample_weight, + leaf_subsample, + max_samples_leaf, + estimator.random_state, + ) + return leaves + + _SERIALIZED_FOREST_N_JOBS = 1 @@ -1478,7 +1709,9 @@ def _fit_forest( f"max_samples_leaf at {_DISCRETE_Y_LEAF_BOUND} for this forest.", flush=True, ) - model = RandomForestQuantileRegressor( + # The in-place leaf array is byte-identical to the library's and avoids + # its full padded copy (see _InPlaceLeafQRF). + model = _InPlaceLeafQRF( n_estimators=n_estimators, max_samples_leaf=effective_max_samples_leaf, random_state=seed, diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 776082a2e7..4ed5fc794e 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"c145a8a43a9d039ff3062675626513a5f127020be13301196680f3e7894ba1ce","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"322704897a8e9e576efced73663c0970b3db05d177eba8d81630d29e46753ee2","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"322704897a8e9e576efced73663c0970b3db05d177eba8d81630d29e46753ee2"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"528712dc4ca84e4ebfb42f923cbca2e7f849ea4d8a9a0688411dfb97cbedb41f"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"99d453803f091d08dd1f158eac9f804768539e2e82a8cd6ec1e9b03c76e8d767"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"caaae527b22edba77e09efc5ded221a4fc6a9eb68f004ed39cd11db771b08891","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"856df6bf6939cddfa04c80e7b580199be75c01b8fefde69fb0a1691b6182685e","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"856df6bf6939cddfa04c80e7b580199be75c01b8fefde69fb0a1691b6182685e"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"98188c27f63e2a8afd3aa2f025803e87c4bb329353b2e115b9fbe038bbd9a25d"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"1f8df1d2f585b39d3264185b73ddbdedb2b7b44c8c2573b55a4fecdfa08759f3"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py new file mode 100644 index 0000000000..78e6439ef7 --- /dev/null +++ b/tools/measure_qrf_leaf_memory.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Measure one heavy QRF fit's peak resident memory, library versus in place. + +quantile-forest 1.4.2 builds a forest's zero-padded leaf array as one array per +tree and then copies the list with ``np.array(list)``, which writes every +byte, padding included. ``microcosm.fit.qrf._InPlaceLeafQRF`` fills one +preallocated array instead. This script fits the same synthetic forest with +each class, each in a fresh Python process, and reports each process's peak +resident set size (``getrusage``'s ``ru_maxrss``) before and after the fit, so +the fit's own peak growth is the difference. + +Two synthetic shapes stand in for the build's heavy fits. Neither reads survey +data. + +- ``wage``: the CPS-ORG ``hourly_wage`` forest. 100 trees, a continuous + positive target and no leaf cap. The full donor pool has 119,237 rows; the + default here is 10,000. Nearly every row has its own predictor vector, so + trees grow about one leaf per distinct bootstrap row, but + ``--rows-in-widest-leaf`` rows share one vector that no split separates. + That leaf is the widest, and its bootstrap draws set the array's padded + width. The production width is not recorded anywhere; the build's 30-35 GB + spike suggests about 150-350. +- ``near-discrete``: a base-stage near-discrete target. 32 trees, five + distinct values dominated by zero, and the 4,096-entry cap that + ``_fit_forest`` applies to targets with 2 to 32 distinct values. The + production pool has up to 207,692 rows; the default here is 10,000. + +The defaults finish in a few minutes on a laptop and stay within a few GB. A +larger ``--rows`` scales memory roughly in proportion to rows times width (the +cap, for ``near-discrete``) times trees, so raise it with care:: + + uv run python tools/measure_qrf_leaf_memory.py + uv run python tools/measure_qrf_leaf_memory.py --shape near-discrete + uv run python tools/measure_qrf_leaf_memory.py --shape wage --rows 5000 --json + +The script also hashes each leaf array after the fit and reports whether the +two are byte-identical. Hashing happens after the peak is read, so it never +raises the reported peak. +""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +import resource +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np + +IMPLEMENTATIONS = ("library", "in-place") +SHAPES = ("wage", "near-discrete") +DEFAULT_TREES = {"wage": 100, "near-discrete": 32} +DEFAULT_ROWS = {"wage": 10_000, "near-discrete": 10_000} + + +def _peak_resident_bytes() -> int: + """Return this process's peak resident set size so far, in bytes.""" + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + # macOS reports bytes; Linux reports kibibytes. + return int(peak) if sys.platform == "darwin" else int(peak) * 1024 + + +def _wage_donors( + rows: int, rows_in_widest_leaf: int, seed: int +) -> tuple[np.ndarray, np.ndarray]: + """Synthetic CPS-ORG-like donors: seven predictors and a positive wage. + + The predictors mirror ``ORG_PREDICTORS`` in kind: annual earnings, weekly + hours, age, sex, Hispanic origin, a four-way race code and a state code. + Earnings are continuous, so nearly every row has its own predictor vector + and trees grow about one leaf per distinct bootstrap row, as the build's + trees do. The first ``rows_in_widest_leaf`` rows share one predictor + vector (a full-time worker at $15 an hour) with differing wages; no split + separates them, so they set the widest leaf and the array's width. + """ + generator = np.random.default_rng(seed) + hours = generator.choice( + [20.0, 25.0, 30.0, 35.0, 40.0, 40.0, 40.0, 45.0, 50.0, 60.0], rows + ) + earnings = np.exp(generator.normal(10.6, 0.7, rows)) + predictors = np.column_stack( + [ + earnings, + hours, + generator.integers(16, 86, rows), + generator.integers(0, 2, rows), + generator.random(rows) < 0.18, + generator.integers(1, 5, rows), + generator.integers(1, 57, rows), + ] + ).astype(np.float64) + shared = min(rows, rows_in_widest_leaf) + predictors[:shared] = [15.0 * 40.0 * 52.0, 40.0, 30.0, 1.0, 0.0, 1.0, 6.0] + typical_wage = predictors[:, 0] / (52.0 * predictors[:, 1]) + wage = np.round(typical_wage * np.exp(generator.normal(0.0, 0.3, rows)), 2) + return predictors, np.maximum(wage, 0.01) + + +def _near_discrete_donors(rows: int, seed: int) -> tuple[np.ndarray, np.ndarray]: + """Synthetic near-discrete donors: five values, zero for most rows. + + Rows whose first predictor is below 0.8 are always zero, so trees isolate + them in a few large pure leaves that exceed the 4,096 cap. The other rows + draw one of the five values at random and split into many small leaves. + """ + generator = np.random.default_rng(seed) + predictors = generator.random((rows, 6)) + predictors[:, 1:] = np.round(predictors[:, 1:] * 20.0) + target = generator.choice([0.0, 1 / 6, 1 / 3, 1 / 2, 1.0], rows) + target[predictors[:, 0] < 0.8] = 0.0 + return predictors, target + + +def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: + """Fit one forest with ``arguments.child`` and report its memory.""" + from quantile_forest import RandomForestQuantileRegressor + + from microcosm.fit import qrf + + if arguments.shape == "wage": + predictors, target = _wage_donors( + arguments.rows, arguments.rows_in_widest_leaf, arguments.seed + ) + max_samples_leaf = None + else: + predictors, target = _near_discrete_donors(arguments.rows, arguments.seed) + distinct = len(np.unique(target)) + if not 2 <= distinct <= qrf._DISCRETE_Y_UNIQUE_MAX: + raise RuntimeError(f"near-discrete donors have {distinct} values") + max_samples_leaf = qrf._DISCRETE_Y_LEAF_BOUND + + model_class = ( + RandomForestQuantileRegressor + if arguments.child == "library" + else qrf._InPlaceLeafQRF + ) + model = model_class( + n_estimators=arguments.trees, + max_samples_leaf=max_samples_leaf, + random_state=arguments.seed, + n_jobs=arguments.n_jobs, + ) + gc.collect() + peak_before = _peak_resident_bytes() + started = time.perf_counter() + model.fit(predictors, target) + fit_seconds = time.perf_counter() - started + peak_after = _peak_resident_bytes() + + leaves = np.asarray(model.forest_.y_train_leaves) + digest = None + if not arguments.no_digest: + digest = hashlib.sha256(memoryview(np.ascontiguousarray(leaves))).hexdigest() + return { + "implementation": arguments.child, + "class": f"{type(model).__module__}.{type(model).__qualname__}", + "shape": arguments.shape, + "rows": arguments.rows, + "trees": arguments.trees, + "max_samples_leaf": max_samples_leaf, + "leaf_array_shape": list(leaves.shape), + "leaf_array_bytes": int(leaves.nbytes), + "leaf_array_sha256": digest, + "fit_seconds": round(fit_seconds, 3), + "peak_resident_bytes_before_fit": peak_before, + "peak_resident_bytes_after_fit": peak_after, + "fit_peak_growth_bytes": peak_after - peak_before, + } + + +def _child_command(arguments: argparse.Namespace, implementation: str) -> list[str]: + command = [ + sys.executable, + str(Path(__file__).resolve()), + "--child", + implementation, + "--shape", + arguments.shape, + "--rows", + str(arguments.rows), + "--trees", + str(arguments.trees), + "--rows-in-widest-leaf", + str(arguments.rows_in_widest_leaf), + "--seed", + str(arguments.seed), + "--n-jobs", + str(arguments.n_jobs), + ] + if arguments.no_digest: + command.append("--no-digest") + return command + + +def _gibibytes(value: int) -> str: + return f"{value / 2**30:.2f} GiB" + + +def _report(results: list[dict[str, object]], *, digests: bool) -> str: + first = results[0] + lines = [ + f"shape {first['shape']}: {first['rows']:,} donor rows, " + f"{first['trees']} trees, max_samples_leaf={first['max_samples_leaf']}", + "leaf array: shape " + + " x ".join(f"{size:,}" for size in first["leaf_array_shape"]) + + f" (trees x nodes x outputs x width), " + f"{_gibibytes(int(first['leaf_array_bytes']))} if every page were resident", + ] + for result in results: + lines.append( + f"{result['implementation']}: peak RSS " + f"{_gibibytes(int(result['peak_resident_bytes_after_fit']))}, " + f"of which the fit added " + f"{_gibibytes(int(result['fit_peak_growth_bytes']))}; " + f"fit took {result['fit_seconds']:.1f} s" + ) + if digests and len(results) == 2: + identical = results[0]["leaf_array_sha256"] == results[1]["leaf_array_sha256"] + lines.append("leaf arrays byte-identical: " + ("yes" if identical else "NO")) + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--shape", choices=SHAPES, default="wage") + parser.add_argument( + "--rows", type=int, help="donor rows (default 10,000 for either shape)" + ) + parser.add_argument( + "--trees", type=int, help="trees (default: 100 for wage, 32 near-discrete)" + ) + parser.add_argument( + "--rows-in-widest-leaf", + type=int, + default=250, + help="wage shape only: donor rows that share one predictor vector " + "(default 250), which sets the array's width", + ) + parser.add_argument("--seed", type=int, default=20261117) + parser.add_argument( + "--n-jobs", + type=int, + default=-1, + help="quantile-forest n_jobs (default -1, as microcosm's fits use)", + ) + parser.add_argument( + "--implementation", + choices=(*IMPLEMENTATIONS, "both"), + default="both", + help="which class to measure (default both, library first)", + ) + parser.add_argument( + "--no-digest", action="store_true", help="skip hashing the leaf arrays" + ) + parser.add_argument("--json", action="store_true", help="print JSON results") + parser.add_argument("--child", choices=IMPLEMENTATIONS, help=argparse.SUPPRESS) + arguments = parser.parse_args(argv) + if arguments.rows is None: + arguments.rows = DEFAULT_ROWS[arguments.shape] + if arguments.trees is None: + arguments.trees = DEFAULT_TREES[arguments.shape] + if arguments.rows < 2 or arguments.trees < 1: + parser.error("--rows must be at least 2 and --trees at least 1") + + if arguments.child is not None: + print(json.dumps(_fit_in_this_process(arguments))) + return 0 + + implementations = ( + IMPLEMENTATIONS + if arguments.implementation == "both" + else (arguments.implementation,) + ) + results = [] + for implementation in implementations: + completed = subprocess.run( + _child_command(arguments, implementation), + check=True, + stdout=subprocess.PIPE, + text=True, + ) + results.append(json.loads(completed.stdout.strip().splitlines()[-1])) + if arguments.json: + print(json.dumps(results, indent=2)) + else: + print(_report(results, digests=not arguments.no_digest)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/uv.lock b/uv.lock index c123b9bea9..0117ec2754 100644 --- a/uv.lock +++ b/uv.lock @@ -974,7 +974,7 @@ requires-dist = [ { name = "microcosm-graph", editable = "packages/microcosm-graph" }, { name = "numpy", specifier = ">=2" }, { name = "pandas", specifier = ">=2.3" }, - { name = "quantile-forest", specifier = ">=1.4.2" }, + { name = "quantile-forest", specifier = "==1.4.2" }, { name = "scikit-learn", specifier = ">=1.5" }, ] From 4609f814e3e71f31b1310d98bbd84725dde4a9b3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:09:13 +0400 Subject: [PATCH 03/15] Address round-one review of the in-place leaf array - _InPlaceLeafQRF._get_y_train_leaves takes the library's own argument names (X, y) again, so keyword callers work; a test compares both overrides' signatures with the library's. - The version check also runs at the top of _get_y_train_leaves, the only place the copied code runs, so calling quantile-forest's own fit on the subclass is refused too (new test, seen failing first). The private quantile_forest._quantile_forest module is imported after that check instead of when qrf.py loads, so a release that moved it gets the explanatory error instead of an ImportError from import microcosm.fit. - The README and the pyproject comment no longer call the quantile-forest requirement a floor, and name BaseForestQuantileRegressor, where the method is defined. - tools/measure_qrf_leaf_memory.py: - fits through _fit_forest with lognormal donor weights, so microcosm's weighted resample and near-discrete cap run as in a build (the wage shape now has about 0.85 nodes per donor row, not 1.2); - reads macOS's lifetime peak physical footprint, which counts pages compressed under memory pressure (ru_maxrss drops when they are), and warns when the library fit's growth is below the array's size; - validates --rows-in-widest-leaf, --seed and the near-discrete row count with argparse errors, and reports a failed child briefly; - records platform, page size, huge-page mode, package versions, seed, n_jobs and every input, and compares shape and dtype as well as the digest; - documents the platform dependence and when the cap's truncation runs. - Re-pinned the US F0 spec pins (repin, coverage 41/41, repin, --check clean) and the fit.qrf parity pins, which every qrf.py edit moves; direct.csv is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../qrf-leaf-array-in-place.changed.md | 6 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- packages/microcosm-fit/README.md | 12 +- packages/microcosm-fit/pyproject.toml | 10 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 49 ++- .../engine_free/shared/test_qrf_leaf_array.py | 31 +- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 370 +++++++++++++----- 11 files changed, 368 insertions(+), 136 deletions(-) diff --git a/changelog.d/qrf-leaf-array-in-place.changed.md b/changelog.d/qrf-leaf-array-in-place.changed.md index ff8246b60f..5d4ed1da75 100644 --- a/changelog.d/qrf-leaf-array-in-place.changed.md +++ b/changelog.d/qrf-leaf-array-in-place.changed.md @@ -1,5 +1,5 @@ microcosm-fit's QRF forests build their leaf array in place. quantile-forest stores, for every tree, the training rows each leaf holds in one zero-padded int64 array (trees x nodes x outputs x width); version 1.4.2 builds one array per tree and then copies the list into the final array, which writes every padding byte and makes the whole padded array resident while both copies exist. `_fit_forest` now builds `_InPlaceLeafQRF`, a subclass that allocates the final array once and fills each tree's slice directly. The array is byte-identical to the library's, so every prediction and draw is unchanged; tests compare the two classes byte for byte on continuous, capped near-discrete, multi-output and weighted fits, and compare grid predictions and draws. -- quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method, and `_InPlaceLeafQRF.fit` refuses any other installed release before growing a tree. -- `tools/measure_qrf_leaf_memory.py` fits one synthetic CPS-ORG-like wage forest or one capped near-discrete forest with each class in a fresh process and reports each fit's peak resident memory. -- Pickling or deep-copying a fitted forest still writes the full padded array, as before. +- quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method. `_InPlaceLeafQRF` refuses any other installed release, in `fit` before growing a tree and again where its copied code runs. +- `tools/measure_qrf_leaf_memory.py` fits one synthetic forest shaped like the CPS-ORG wage fit or a capped near-discrete fit through `_fit_forest`, once with each class and each in a fresh process, and reports each fit's peak memory (the peak physical footprint on macOS, the peak resident set on Linux). +- Pickling or deep-copying a fitted forest still writes the full padded array, as before. New pickles name `microcosm.fit.qrf._InPlaceLeafQRF`, so microcosm-fit from before this change cannot load them; pickles made before it still load and draw the same values. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index d4d1a0adaa..52e4f70b12 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", - "protocol_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2" + "map_sha256": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", + "protocol_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6" }, "failures": [], "observed": { - "map_sha256": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", - "protocol_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2" + "map_sha256": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", + "protocol_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", + "implementation_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", + "implementation_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09" + "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09" + "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 52ae74bca1..c7719609a4 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "a181afb40adaabcdb8db5e3caa0031d0879b398e8a1e7a2d6dc41479cfd9dbac", - "seed_protocol": "52159133e3273dcbc767e2b4a57aed243943c726d0b6260ecac72824215f65b2", + "seed_map": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", + "seed_protocol": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index c29723c544..ae6e6f6816 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "dda333cf1ccbad20d8d9b26ad2a73925675f4dd171256832ca2cae09153d4953" + "8093e4c0b8fd45d73378e75af2a82672ee0bc42114c2870e9c76dcd47094d880" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 93338ab6d9..3ee8430ff6 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "a0794715d1d7545675b6a604af44df7ecf34c8487eed1e142666b32f4c1a1b09", + "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337", }, } diff --git a/packages/microcosm-fit/README.md b/packages/microcosm-fit/README.md index dff310b3f3..069aebaafc 100644 --- a/packages/microcosm-fit/README.md +++ b/packages/microcosm-fit/README.md @@ -53,7 +53,15 @@ doing only calibration never pulls them. `scikit-learn` is unpinned on the upper side (`>=1.5`): the shard's test suite passes on both 1.8 and 1.9, so it coexists in one environment with a -`scikit-learn>=1.9` consumer. This requires `quantile-forest>=1.4.2`, the first -release that tracks the sklearn-1.9 tree ABI +`scikit-learn>=1.9` consumer. That needs quantile-forest 1.4.2 or later, the +first release that tracks the sklearn-1.9 tree ABI (zillow/quantile-forest#152, #153); older `quantile-forest` fails to import under sklearn 1.9. + +`quantile-forest` is pinned exactly (`==1.4.2`). `microcosm.fit.qrf` builds +each forest with a subclass that replaces quantile-forest's private +`BaseForestQuantileRegressor._get_y_train_leaves` with a copy of 1.4.2's that +fills the leaf array in place instead of copying a list of per-tree arrays, +and its `fit` refuses any other installed release. A scikit-learn release +that breaks quantile-forest 1.4.2 therefore needs the pin, the copied method +and `_SUPPORTED_QUANTILE_FOREST_VERSION` moved together. diff --git a/packages/microcosm-fit/pyproject.toml b/packages/microcosm-fit/pyproject.toml index a947a31000..1156a642f8 100644 --- a/packages/microcosm-fit/pyproject.toml +++ b/packages/microcosm-fit/pyproject.toml @@ -12,13 +12,13 @@ dependencies = [ "microcosm-graph>=0.1,<0.2", # scikit-learn 1.9 removed sklearn.tree._tree.DTYPE and changed the # sample-weight signature of the forest bootstrap helpers; quantile-forest - # 1.4.2 (2026-06-21) tracks both (zillow/quantile-forest#152, #153), so the - # floor below is the first release compatible with sklearn 1.9. No upper - # bound: this package's own sklearn usage (HistGradientBoostingClassifier, - # forest .fit() without sample_weight) is stable across 1.5-1.9. + # 1.4.2 (2026-06-21) tracks both (zillow/quantile-forest#152, #153), so it + # is the first release compatible with sklearn 1.9. No upper bound: this + # package's own sklearn usage (HistGradientBoostingClassifier, forest + # .fit() without sample_weight) is stable across 1.5-1.9. "scikit-learn>=1.5", # Exact: microcosm.fit.qrf._InPlaceLeafQRF replaces the private - # RandomForestQuantileRegressor._get_y_train_leaves with a copy of 1.4.2's + # BaseForestQuantileRegressor._get_y_train_leaves with a copy of 1.4.2's # that fills the leaf array in place, and refuses to fit under any other # release (_SUPPORTED_QUANTILE_FOREST_VERSION). Raise both together, after # comparing the override with the new release's method. diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 3281265f60..f578e9ff03 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -70,7 +70,6 @@ import pandas as pd import quantile_forest from quantile_forest import RandomForestQuantileRegressor -from quantile_forest import _quantile_forest as _quantile_forest_module from sklearn.ensemble import HistGradientBoostingClassifier from microcosm.fit.model import ( @@ -1160,12 +1159,12 @@ def _require_supported_quantile_forest() -> None: RuntimeError: If the imported ``quantile_forest`` is not :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. """ - installed = quantile_forest.__version__ + installed = getattr(quantile_forest, "__version__", None) if installed != _SUPPORTED_QUANTILE_FOREST_VERSION: raise RuntimeError( "microcosm-fit builds QRF leaf arrays with a copy of quantile-forest " f"{_SUPPORTED_QUANTILE_FOREST_VERSION}'s private " - "RandomForestQuantileRegressor._get_y_train_leaves, but quantile-forest " + "BaseForestQuantileRegressor._get_y_train_leaves, but quantile-forest " f"{installed} is installed. Install quantile-forest==" f"{_SUPPORTED_QUANTILE_FOREST_VERSION}, the release microcosm-fit " "pins, or compare the override with the new release's method and " @@ -1198,18 +1197,19 @@ def _fill_tree_leaves( training values of this tree's bootstrap draws. draw_leaves: The leaf each bootstrap draw reaches in this tree. sample_weight: Sorted training weights, or ``None``. - leaf_subsample: Whether leaves are cut to ``max_samples_leaf`` entries. + leaf_subsample: Whether leaves are truncated to ``max_samples_leaf`` + entries. max_samples_leaf: The width of every leaf's row. random_state: This tree's seed, which also seeds the leaf subsample. """ + from quantile_forest import _quantile_forest as library + n_outputs = bootstrap_indices.shape[1] if sample_weight is not None: sample_weight = np.squeeze(sample_weight) - leaf_indices, leaf_values_list = _quantile_forest_module.group_indices_by_value( - draw_leaves - ) + leaf_indices, leaf_values_list = library.group_indices_by_value(draw_leaves) if leaf_subsample or sample_weight is not None: if leaf_subsample: @@ -1232,7 +1232,7 @@ def _fill_tree_leaves( for output in range(n_outputs): tree_leaves[leaf_indices, output, 0] = sorted_positions[:, 0, output] else: - filled = _quantile_forest_module.map_indices_to_leaves( + filled = library.map_indices_to_leaves( y_train_leaves_slice=tree_leaves, bootstrap_indices=bootstrap_indices, leaf_indices=leaf_indices, @@ -1266,8 +1266,8 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): own, as are the ``random.seed``/``random.shuffle`` calls in tree order and the dtype, shape and C order of the result, so the array is byte-identical to the library's and so is every prediction. Only the private - ``_get_y_train_leaves`` is replaced, so :meth:`fit` refuses any - quantile-forest release other than + ``_get_y_train_leaves`` is replaced, so :meth:`fit` and + :meth:`_get_y_train_leaves` refuse any quantile-forest release other than :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. Pickling a fitted forest, or deep-copying it, still writes the full padded @@ -1276,25 +1276,32 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): """ def fit(self, X, y, sample_weight=None, sparse_pickle=False): # noqa: N803 - """Check the installed quantile-forest, then fit as the library does.""" + """Check the installed quantile-forest, then fit as the library does. + + The check runs here, before any tree is grown, and again in + :meth:`_get_y_train_leaves`, which also covers a caller that runs the + library's own ``fit`` on this class. + """ _require_supported_quantile_forest() return super().fit( X, y, sample_weight=sample_weight, sparse_pickle=sparse_pickle ) - def _get_y_train_leaves( - self, features, sorted_targets, sorter=None, sample_weight=None - ): + def _get_y_train_leaves(self, X, y, sorter=None, sample_weight=None): # noqa: N803 """Return the leaf array, built as quantile-forest 1.4.2 builds it. - The steps up to the per-tree fill are quantile-forest 1.4.2's - ``BaseForestQuantileRegressor._get_y_train_leaves``, unchanged. The + The signature and the steps up to the per-tree fill are quantile-forest + 1.4.2's ``BaseForestQuantileRegressor._get_y_train_leaves``, unchanged: + ``X`` is the training features and ``y`` the sorted targets. The per-tree fill writes into one preallocated array instead of returning - a list that ``np.array`` then copies. + a list that ``np.array`` then copies, so the library's per-tree method + ``_get_y_train_leaves_slice`` is not called. """ - library = _quantile_forest_module - n_samples = features.shape[0] - n_outputs = sorted_targets.shape[-1] + _require_supported_quantile_forest() + from quantile_forest import _quantile_forest as library + + n_samples = X.shape[0] + n_outputs = y.shape[-1] if isinstance(self.max_samples_leaf, (numbers.Integral, np.integer)): max_samples_leaf = self.max_samples_leaf @@ -1313,7 +1320,7 @@ def _get_y_train_leaves( with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) - sample_leaves = self.apply(features) + sample_leaves = self.apply(X) if self.bootstrap: arguments = (n_samples, self.max_samples) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index e86a0bcf7f..517b4ee401 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -18,6 +18,7 @@ from __future__ import annotations import importlib.metadata +import inspect import pickle import random import tomllib @@ -375,11 +376,12 @@ def counting_shuffle(sequence): def test_public_fit_and_predict_match_the_library(monkeypatch) -> None: - """A chained, regime-gated fit draws the same values with either class. + """A chained public fit draws the same values with either class. - The targets cover a positive continuous amount, a sign-mixed amount (one - positive and one negative forest behind a gate) and a near-discrete ratio - (the 4,096 cap), each chained on the ones before it. + The targets cover a positive continuous amount, an amount of either sign + (a classifier picks the sign, then one forest gives positive and another + negative amounts) and a near-discrete ratio (the 4,096 cap), each fitted + on the predictors and the targets before it. """ generator = np.random.default_rng(9) rows = 1200 @@ -434,6 +436,14 @@ def fit_and_draw() -> pd.DataFrame: # ---------------------------------------------------------------------------- +@pytest.mark.parametrize("method", ["fit", "_get_y_train_leaves"]) +def test_overrides_keep_the_library_signatures(method) -> None: + """Callers that pass the library's argument names by keyword still work.""" + assert inspect.signature(getattr(qrf._InPlaceLeafQRF, method)) == ( + inspect.signature(getattr(RandomForestQuantileRegressor, method)) + ) + + def test_subclass_pickles_and_clones_like_the_library_class() -> None: predictors, target = _continuous_donors(seed=10, rows=300) model = qrf._InPlaceLeafQRF( @@ -512,6 +522,19 @@ def test_fit_refuses_another_quantile_forest_version(monkeypatch, installed) -> assert not hasattr(model, "estimators_") +def test_library_fit_on_the_subclass_refuses_another_version(monkeypatch) -> None: + """Calling quantile-forest's own ``fit`` still reaches the version check. + + The copied leaf-array code runs only inside ``_get_y_train_leaves``, so the + check there covers callers that skip the subclass's ``fit``. + """ + monkeypatch.setattr(quantile_forest, "__version__", "1.4.3") + predictors, target = _continuous_donors(seed=14, rows=60) + model = qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=0) + with pytest.raises(RuntimeError, match="1.4.3"): + RandomForestQuantileRegressor.fit(model, predictors, target) + + def test_fit_forest_refuses_another_quantile_forest_version(monkeypatch) -> None: monkeypatch.setattr(quantile_forest, "__version__", "1.4.3") predictors, target = _continuous_donors(seed=13, rows=60) diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 4ed5fc794e..173c557d27 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"caaae527b22edba77e09efc5ded221a4fc6a9eb68f004ed39cd11db771b08891","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"856df6bf6939cddfa04c80e7b580199be75c01b8fefde69fb0a1691b6182685e","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"856df6bf6939cddfa04c80e7b580199be75c01b8fefde69fb0a1691b6182685e"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"98188c27f63e2a8afd3aa2f025803e87c4bb329353b2e115b9fbe038bbd9a25d"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"1f8df1d2f585b39d3264185b73ddbdedb2b7b44c8c2573b55a4fecdfa08759f3"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"1000f513f729fc0fc41e4ac0bdf1ce8a2545a67efaba23527b3a01f273e81937","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"687476edcdd08ed71bf53940543962145e62e40ac7aae864f0d788770ac9d1d8","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"687476edcdd08ed71bf53940543962145e62e40ac7aae864f0d788770ac9d1d8"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"70ac58c22b3162a5fce85e7f54d4b78cc3401ab1eeb4eca47cd2fc7a943a8ca1"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"54d0c2d11c6e04a0ccc5f270fae00d181a48bb27a94ef85e2088aff0d6326fe8"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 78e6439ef7..8d0313390f 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -1,49 +1,80 @@ #!/usr/bin/env python3 -"""Measure one heavy QRF fit's peak resident memory, library versus in place. +"""Measure one heavy QRF fit's peak memory, quantile-forest's leaf array versus in place. quantile-forest 1.4.2 builds a forest's zero-padded leaf array as one array per tree and then copies the list with ``np.array(list)``, which writes every byte, padding included. ``microcosm.fit.qrf._InPlaceLeafQRF`` fills one -preallocated array instead. This script fits the same synthetic forest with -each class, each in a fresh Python process, and reports each process's peak -resident set size (``getrusage``'s ``ru_maxrss``) before and after the fit, so -the fit's own peak growth is the difference. +preallocated array instead. This script fits the same synthetic forest through +microcosm's ``_fit_forest`` (the weighted resample, the near-discrete cap and +the forest), once with each class and each in a fresh Python process. For the +library run the child process replaces the class ``_fit_forest`` builds with +quantile-forest's own. Each child reports its peak memory just before and just +after the fit, so the fit's own peak growth is the difference. + +Peak memory is read as follows: + +- macOS: the process's lifetime peak physical footprint + (``proc_pid_rusage``'s ``ri_lifetime_max_phys_footprint``), which counts + pages macOS has compressed under memory pressure. The resident set size + (``ru_maxrss``) is reported too, but it drops when pages are compressed, so + on a busy machine it can read lower than the memory the fit used. +- Linux: the peak resident set size (``ru_maxrss``). Pages swapped out under + memory pressure are not counted, so measure on a machine with free memory. + +The result depends on the platform. On macOS, reading a never-written page of +an ``np.zeros`` array makes it resident; on Linux it maps the shared zero page, +which is not counted. Where Linux transparent huge pages are enabled for large +arrays, a first write makes a whole 2 MiB region resident, which shrinks the +in-place saving. The report records the platform, the page size and the huge +page mode. Two synthetic shapes stand in for the build's heavy fits. Neither reads survey -data. +data. Donor weights are lognormal, so ``_fit_forest``'s weighted resample +duplicates rows as it does for weighted survey donors. - ``wage``: the CPS-ORG ``hourly_wage`` forest. 100 trees, a continuous positive target and no leaf cap. The full donor pool has 119,237 rows; the - default here is 10,000. Nearly every row has its own predictor vector, so - trees grow about one leaf per distinct bootstrap row, but - ``--rows-in-widest-leaf`` rows share one vector that no split separates. - That leaf is the widest, and its bootstrap draws set the array's padded - width. The production width is not recorded anywhere; the build's 30-35 GB - spike suggests about 150-350. -- ``near-discrete``: a base-stage near-discrete target. 32 trees, five - distinct values dominated by zero, and the 4,096-entry cap that - ``_fit_forest`` applies to targets with 2 to 32 distinct values. The - production pool has up to 207,692 rows; the default here is 10,000. - -The defaults finish in a few minutes on a laptop and stay within a few GB. A -larger ``--rows`` scales memory roughly in proportion to rows times width (the -cap, for ``near-discrete``) times trees, so raise it with care:: + default here is 10,000. Earnings are continuous, so most rows have their + own predictor vector, but ``--rows-in-widest-leaf`` rows share one vector + that no split separates. That leaf is the widest, and its draws set the + array's padded width. The production width is not recorded anywhere, so + this value is a parameter, not a measurement. +- ``near-discrete``: a base-stage near-discrete target. 32 trees and five + distinct values dominated by zero, so ``_fit_forest`` applies its + 4,096-entry cap. The production pool has up to 207,692 rows; the default + here is 10,000. About 80% of rows are zero in a region the trees isolate in + one leaf; from about 5,100 rows that leaf holds more than 4,096 draws, so + the library's shuffle and truncation run. The width is 4,096 at any size. + +The defaults finish in under a minute on a laptop and need a few GB. Memory +grows roughly in proportion to rows times width (the cap, for +``near-discrete``) times trees, so raise ``--rows`` with care:: uv run python tools/measure_qrf_leaf_memory.py uv run python tools/measure_qrf_leaf_memory.py --shape near-discrete uv run python tools/measure_qrf_leaf_memory.py --shape wage --rows 5000 --json +Set ``POPULACE_FIT_N_JOBS`` to fix quantile-forest's thread count, as for a +build; the report records the value each fit used. + The script also hashes each leaf array after the fit and reports whether the -two are byte-identical. Hashing happens after the peak is read, so it never -raises the reported peak. +two arrays have the same shape, dtype and bytes. Hashing happens after the +peak is read, so it never raises the reported peak, but on macOS it reads +every page and so raises the process's real memory to the array's full size. +Pass ``--no-digest`` for large runs. """ from __future__ import annotations import argparse +import contextlib +import ctypes import gc import hashlib +import importlib.metadata import json +import os +import platform import resource import subprocess import sys @@ -56,6 +87,54 @@ SHAPES = ("wage", "near-discrete") DEFAULT_TREES = {"wage": 100, "near-discrete": 32} DEFAULT_ROWS = {"wage": 10_000, "near-discrete": 10_000} +#: scikit-learn accepts integer seeds below 2**32. +SEED_LIMIT = 2**32 +_RUSAGE_INFO_V4 = 4 + + +class _RusageInfoV4(ctypes.Structure): + """macOS ``struct rusage_info_v4`` from ````.""" + + _fields_ = [("ri_uuid", ctypes.c_uint8 * 16)] + [ + (name, ctypes.c_uint64) + for name in ( + "ri_user_time", + "ri_system_time", + "ri_pkg_idle_wkups", + "ri_interrupt_wkups", + "ri_pageins", + "ri_wired_size", + "ri_resident_size", + "ri_phys_footprint", + "ri_proc_start_abstime", + "ri_proc_exit_abstime", + "ri_child_user_time", + "ri_child_system_time", + "ri_child_pkg_idle_wkups", + "ri_child_interrupt_wkups", + "ri_child_pageins", + "ri_child_elapsed_abstime", + "ri_diskio_bytesread", + "ri_diskio_byteswritten", + "ri_cpu_time_qos_default", + "ri_cpu_time_qos_maintenance", + "ri_cpu_time_qos_background", + "ri_cpu_time_qos_utility", + "ri_cpu_time_qos_legacy", + "ri_cpu_time_qos_user_initiated", + "ri_cpu_time_qos_user_interactive", + "ri_billed_system_time", + "ri_serviced_system_time", + "ri_logical_writes", + "ri_lifetime_max_phys_footprint", + "ri_instructions", + "ri_cycles", + "ri_billed_energy", + "ri_serviced_energy", + "ri_interval_max_phys_footprint", + "ri_runnable_time", + ) + ] def _peak_resident_bytes() -> int: @@ -65,6 +144,47 @@ def _peak_resident_bytes() -> int: return int(peak) if sys.platform == "darwin" else int(peak) * 1024 +def _peak_footprint_bytes() -> int | None: + """Return macOS's lifetime peak physical footprint, or None elsewhere.""" + if sys.platform != "darwin": + return None + library = ctypes.CDLL("/usr/lib/libproc.dylib") + information = _RusageInfoV4() + if library.proc_pid_rusage(os.getpid(), _RUSAGE_INFO_V4, ctypes.byref(information)): + raise OSError("proc_pid_rusage failed") + return int(information.ri_lifetime_max_phys_footprint) + + +def _peak_memory() -> dict[str, int | None]: + return { + "resident_set": _peak_resident_bytes(), + "physical_footprint": _peak_footprint_bytes(), + } + + +def _huge_page_mode() -> str | None: + """Return Linux's transparent huge page setting, or None elsewhere.""" + path = Path("/sys/kernel/mm/transparent_hugepage/enabled") + try: + return path.read_text().strip() + except OSError: + return None + + +def _environment() -> dict[str, object]: + return { + "platform": platform.platform(), + "machine": platform.machine(), + "python": platform.python_version(), + "page_size_bytes": resource.getpagesize(), + "transparent_huge_pages": _huge_page_mode(), + "packages": { + name: importlib.metadata.version(name) + for name in ("numpy", "scikit-learn", "quantile-forest") + }, + } + + def _wage_donors( rows: int, rows_in_widest_leaf: int, seed: int ) -> tuple[np.ndarray, np.ndarray]: @@ -72,11 +192,10 @@ def _wage_donors( The predictors mirror ``ORG_PREDICTORS`` in kind: annual earnings, weekly hours, age, sex, Hispanic origin, a four-way race code and a state code. - Earnings are continuous, so nearly every row has its own predictor vector - and trees grow about one leaf per distinct bootstrap row, as the build's - trees do. The first ``rows_in_widest_leaf`` rows share one predictor - vector (a full-time worker at $15 an hour) with differing wages; no split - separates them, so they set the widest leaf and the array's width. + Earnings are continuous, so most rows have their own predictor vector. The + first ``rows_in_widest_leaf`` rows share one predictor vector (a full-time + worker at $15 an hour) with differing wages; no split separates them, so + they make the widest leaf and set the array's width. """ generator = np.random.default_rng(seed) hours = generator.choice( @@ -94,8 +213,7 @@ def _wage_donors( generator.integers(1, 57, rows), ] ).astype(np.float64) - shared = min(rows, rows_in_widest_leaf) - predictors[:shared] = [15.0 * 40.0 * 52.0, 40.0, 30.0, 1.0, 0.0, 1.0, 6.0] + predictors[:rows_in_widest_leaf] = [15.0 * 40.0 * 52.0, 40.0, 30.0, 1, 0, 1, 6] typical_wage = predictors[:, 0] / (52.0 * predictors[:, 1]) wage = np.round(typical_wage * np.exp(generator.normal(0.0, 0.3, rows)), 2) return predictors, np.maximum(wage, 0.01) @@ -104,9 +222,9 @@ def _wage_donors( def _near_discrete_donors(rows: int, seed: int) -> tuple[np.ndarray, np.ndarray]: """Synthetic near-discrete donors: five values, zero for most rows. - Rows whose first predictor is below 0.8 are always zero, so trees isolate - them in a few large pure leaves that exceed the 4,096 cap. The other rows - draw one of the five values at random and split into many small leaves. + Rows whose first predictor is below 0.8 are always zero, and trees isolate + them in one large leaf. The other rows draw one of the five values at + random and split into many small leaves. """ generator = np.random.default_rng(seed) predictors = generator.random((rows, 6)) @@ -116,60 +234,81 @@ def _near_discrete_donors(rows: int, seed: int) -> tuple[np.ndarray, np.ndarray] return predictors, target -def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: - """Fit one forest with ``arguments.child`` and report its memory.""" - from quantile_forest import RandomForestQuantileRegressor - - from microcosm.fit import qrf - +def _donors(arguments: argparse.Namespace) -> tuple[np.ndarray, ...]: + """Return predictors, target and lognormal donor weights.""" if arguments.shape == "wage": predictors, target = _wage_donors( arguments.rows, arguments.rows_in_widest_leaf, arguments.seed ) - max_samples_leaf = None else: predictors, target = _near_discrete_donors(arguments.rows, arguments.seed) - distinct = len(np.unique(target)) - if not 2 <= distinct <= qrf._DISCRETE_Y_UNIQUE_MAX: - raise RuntimeError(f"near-discrete donors have {distinct} values") - max_samples_leaf = qrf._DISCRETE_Y_LEAF_BOUND - - model_class = ( - RandomForestQuantileRegressor - if arguments.child == "library" - else qrf._InPlaceLeafQRF - ) - model = model_class( - n_estimators=arguments.trees, - max_samples_leaf=max_samples_leaf, - random_state=arguments.seed, - n_jobs=arguments.n_jobs, + weights = np.random.default_rng(arguments.seed + 1).lognormal( + 0.0, 0.5, arguments.rows ) + return predictors, target, weights + + +def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: + """Fit one forest with ``arguments.child`` and report its memory.""" + from quantile_forest import RandomForestQuantileRegressor + + from microcosm.fit import qrf + + if arguments.child == "library": + # This process exists only for this measurement; nothing else uses qrf. + qrf._InPlaceLeafQRF = RandomForestQuantileRegressor + predictors, target, weights = _donors(arguments) + columns = tuple(f"predictor_{index}" for index in range(predictors.shape[1])) + gc.collect() - peak_before = _peak_resident_bytes() + before = _peak_memory() started = time.perf_counter() - model.fit(predictors, target) + # _fit_forest prints a note for near-discrete targets; stdout carries the + # result, so send the note to stderr. + with contextlib.redirect_stdout(sys.stderr): + forest = qrf._fit_forest( + predictors, + target, + columns, + weights, + seed=arguments.seed, + n_estimators=arguments.trees, + max_samples_leaf=None, + rng=np.random.default_rng(arguments.seed), + ) fit_seconds = time.perf_counter() - started - peak_after = _peak_resident_bytes() + after = _peak_memory() + model = forest.model leaves = np.asarray(model.forest_.y_train_leaves) digest = None if not arguments.no_digest: digest = hashlib.sha256(memoryview(np.ascontiguousarray(leaves))).hexdigest() + measure = "physical_footprint" if after["physical_footprint"] else "resident_set" return { "implementation": arguments.child, "class": f"{type(model).__module__}.{type(model).__qualname__}", "shape": arguments.shape, "rows": arguments.rows, "trees": arguments.trees, - "max_samples_leaf": max_samples_leaf, + "rows_in_widest_leaf": ( + arguments.rows_in_widest_leaf if arguments.shape == "wage" else None + ), + "seed": arguments.seed, + "n_jobs": model.n_jobs, + "max_samples_leaf": model.max_samples_leaf, "leaf_array_shape": list(leaves.shape), + "leaf_array_dtype": str(leaves.dtype), "leaf_array_bytes": int(leaves.nbytes), "leaf_array_sha256": digest, "fit_seconds": round(fit_seconds, 3), - "peak_resident_bytes_before_fit": peak_before, - "peak_resident_bytes_after_fit": peak_after, - "fit_peak_growth_bytes": peak_after - peak_before, + "memory_measure": measure, + "peak_bytes_before_fit": before[measure], + "peak_bytes_after_fit": after[measure], + "fit_peak_growth_bytes": after[measure] - before[measure], + "peak_resident_set_bytes_before_fit": before["resident_set"], + "peak_resident_set_bytes_after_fit": after["resident_set"], + "environment": _environment(), } @@ -189,43 +328,78 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s str(arguments.rows_in_widest_leaf), "--seed", str(arguments.seed), - "--n-jobs", - str(arguments.n_jobs), ] if arguments.no_digest: command.append("--no-digest") return command -def _gibibytes(value: int) -> str: - return f"{value / 2**30:.2f} GiB" +def _size(value: int) -> str: + if abs(value) >= 2**30: + return f"{value / 2**30:.2f} GiB" + return f"{value / 2**20:.1f} MiB" + + +def _array_description(result: dict[str, object]) -> str: + shape = " x ".join(f"{size:,}" for size in result["leaf_array_shape"]) + return ( + f"{shape} (trees x nodes x outputs x width), {result['leaf_array_dtype']}, " + f"{_size(int(result['leaf_array_bytes']))} if every page were resident" + ) def _report(results: list[dict[str, object]], *, digests: bool) -> str: first = results[0] + environment = first["environment"] + trees = int(first["trees"]) lines = [ - f"shape {first['shape']}: {first['rows']:,} donor rows, " - f"{first['trees']} trees, max_samples_leaf={first['max_samples_leaf']}", - "leaf array: shape " - + " x ".join(f"{size:,}" for size in first["leaf_array_shape"]) - + f" (trees x nodes x outputs x width), " - f"{_gibibytes(int(first['leaf_array_bytes']))} if every page were resident", + f"{environment['platform']}, page size {environment['page_size_bytes']:,} " + f"bytes, transparent huge pages: {environment['transparent_huge_pages']}", + f"shape {first['shape']}: {first['rows']:,} donor rows, {trees} " + f"{'tree' if trees == 1 else 'trees'}, max_samples_leaf=" + f"{first['max_samples_leaf']}, n_jobs={first['n_jobs']}, seed {first['seed']}" + + ( + f", {first['rows_in_widest_leaf']:,} rows in the widest leaf" + if first["rows_in_widest_leaf"] is not None + else "" + ), ] + if len({_array_description(result) for result in results}) == 1: + lines.append("leaf array: " + _array_description(first)) + measure = ( + "peak physical footprint" + if first["memory_measure"] == "physical_footprint" + else "peak resident set" + ) for result in results: + if len({_array_description(result) for result in results}) > 1: + lines.append( + f"{result['implementation']} leaf array: {_array_description(result)}" + ) lines.append( - f"{result['implementation']}: peak RSS " - f"{_gibibytes(int(result['peak_resident_bytes_after_fit']))}, " - f"of which the fit added " - f"{_gibibytes(int(result['fit_peak_growth_bytes']))}; " - f"fit took {result['fit_seconds']:.1f} s" + f"{result['implementation']}: {measure} " + f"{_size(int(result['peak_bytes_after_fit']))}, of which the fit " + f"added {_size(int(result['fit_peak_growth_bytes']))}; fit took " + f"{result['fit_seconds']:.1f} s" ) + if result["implementation"] == "library" and int( + result["fit_peak_growth_bytes"] + ) < int(result["leaf_array_bytes"]): + lines.append( + "warning: the library fit's growth is below the leaf array's size, " + "although its copy writes every byte; memory was compressed or " + "swapped out during the fit, so these readings are too low" + ) if digests and len(results) == 2: - identical = results[0]["leaf_array_sha256"] == results[1]["leaf_array_sha256"] + identical = all( + results[0][key] == results[1][key] + for key in ("leaf_array_shape", "leaf_array_dtype", "leaf_array_sha256") + ) lines.append("leaf arrays byte-identical: " + ("yes" if identical else "NO")) return "\n".join(lines) -def main(argv: list[str] | None = None) -> int: +def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) @@ -234,7 +408,7 @@ def main(argv: list[str] | None = None) -> int: "--rows", type=int, help="donor rows (default 10,000 for either shape)" ) parser.add_argument( - "--trees", type=int, help="trees (default: 100 for wage, 32 near-discrete)" + "--trees", type=int, help="trees (default 100 for wage, 32 near-discrete)" ) parser.add_argument( "--rows-in-widest-leaf", @@ -244,12 +418,6 @@ def main(argv: list[str] | None = None) -> int: "(default 250), which sets the array's width", ) parser.add_argument("--seed", type=int, default=20261117) - parser.add_argument( - "--n-jobs", - type=int, - default=-1, - help="quantile-forest n_jobs (default -1, as microcosm's fits use)", - ) parser.add_argument( "--implementation", choices=(*IMPLEMENTATIONS, "both"), @@ -266,9 +434,28 @@ def main(argv: list[str] | None = None) -> int: arguments.rows = DEFAULT_ROWS[arguments.shape] if arguments.trees is None: arguments.trees = DEFAULT_TREES[arguments.shape] - if arguments.rows < 2 or arguments.trees < 1: - parser.error("--rows must be at least 2 and --trees at least 1") + if arguments.rows < 2: + parser.error("--rows must be at least 2") + if arguments.trees < 1: + parser.error("--trees must be at least 1") + if not 0 <= arguments.seed < SEED_LIMIT: + parser.error(f"--seed must be at least 0 and below {SEED_LIMIT:,}") + if arguments.shape == "wage" and not ( + 1 <= arguments.rows_in_widest_leaf <= arguments.rows + ): + parser.error("--rows-in-widest-leaf must be between 1 and --rows") + if arguments.shape == "near-discrete" and arguments.child is None: + distinct = len(np.unique(_donors(arguments)[1])) + if distinct < 2: + parser.error( + f"with --rows {arguments.rows} the near-discrete target has " + f"{distinct} distinct value; raise --rows" + ) + return arguments + +def main(argv: list[str] | None = None) -> int: + arguments = _parse_arguments(argv) if arguments.child is not None: print(json.dumps(_fit_in_this_process(arguments))) return 0 @@ -282,10 +469,17 @@ def main(argv: list[str] | None = None) -> int: for implementation in implementations: completed = subprocess.run( _child_command(arguments, implementation), - check=True, stdout=subprocess.PIPE, text=True, + check=False, ) + if completed.returncode != 0: + print( + f"the {implementation} measurement failed with exit code " + f"{completed.returncode}; its error is printed above", + file=sys.stderr, + ) + return 1 results.append(json.loads(completed.stdout.strip().splitlines()[-1])) if arguments.json: print(json.dumps(results, indent=2)) From 27865e54a5784277630620ed2f50897c757fa6a8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:47:36 +0400 Subject: [PATCH 04/15] Address round-two review: close test gaps, correct docstrings, rework the memory script Tests (five deliberate code mutations survived round two; each now fails a test): - emptied weighted leaves: a fit with nine in ten weights at zero records, through quantile-forest's compiled helper, that both classes hand it the same number of [0] placeholders, and more than none; - fractional caps where ceil and floor differ: 0.021 of 400 rows (9), and 0.0047 of 3,000 near-discrete rows (15), which also truncates leaves; - the width-1 branch with three outputs; - the shared-memory check, by making the helper return a copy; - sparse_pickle reaching the library. The weights helper's docstring no longer claims the placeholder runs. qrf.py docstrings: the per-tree fill names all its differences from the library's; the class says fit is wrapped for the version check, that scikit-learn's messages name the subclass, and when untouched pages do become resident (writes; reads on macOS, including prediction and pickling; huge pages on Linux). tools/measure_qrf_leaf_memory.py: - whole-dollar wages bring the wage shape to about 0.7 nodes per donor row, the top of the build's 0.4-0.7; - each child checks it fitted the class it was asked for, and the report prints the class; - a failed or killed measurement is reported by signal or exit code, the other one still runs, and the exit code is 1; - the unreliable low-reading warning is removed; the docstring explains when growth reads low; - libproc is reached through libSystem, with a fallback to ru_maxrss; - the report prints the resident-set peak, the thread count, numpy's huge page request and CPU count; --json carries failures and the identity result; - --rows-in-widest-leaf defaults to half of --rows when smaller, and a wage target with 32 or fewer values is refused instead of silently capped. Re-pinned the US F0 spec pins (repin, coverage 41/41, repin, --check clean) and the fit.qrf parity pins; direct.csv is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../qrf-leaf-array-in-place.changed.md | 2 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 37 ++- .../engine_free/shared/test_qrf_leaf_array.py | 99 ++++++- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 263 +++++++++++++----- 9 files changed, 311 insertions(+), 116 deletions(-) diff --git a/changelog.d/qrf-leaf-array-in-place.changed.md b/changelog.d/qrf-leaf-array-in-place.changed.md index 5d4ed1da75..4d2716f0d4 100644 --- a/changelog.d/qrf-leaf-array-in-place.changed.md +++ b/changelog.d/qrf-leaf-array-in-place.changed.md @@ -2,4 +2,4 @@ microcosm-fit's QRF forests build their leaf array in place. quantile-forest sto - quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method. `_InPlaceLeafQRF` refuses any other installed release, in `fit` before growing a tree and again where its copied code runs. - `tools/measure_qrf_leaf_memory.py` fits one synthetic forest shaped like the CPS-ORG wage fit or a capped near-discrete fit through `_fit_forest`, once with each class and each in a fresh process, and reports each fit's peak memory (the peak physical footprint on macOS, the peak resident set on Linux). -- Pickling or deep-copying a fitted forest still writes the full padded array, as before. New pickles name `microcosm.fit.qrf._InPlaceLeafQRF`, so microcosm-fit from before this change cannot load them; pickles made before it still load and draw the same values. +- Pickling or deep-copying a fitted forest still writes the full padded array, as before. New pickles name `microcosm.fit.qrf._InPlaceLeafQRF`, so microcosm-fit from before this change cannot load them; pickles made before it still load and draw the same values. scikit-learn's validation messages for a forest (a missing value in a predictor, an invalid `max_samples_leaf`) name `_InPlaceLeafQRF` instead of `RandomForestQuantileRegressor`; the exception types are unchanged. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 52e4f70b12..079f3f529c 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", - "protocol_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6" + "map_sha256": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", + "protocol_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7" }, "failures": [], "observed": { - "map_sha256": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", - "protocol_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6" + "map_sha256": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", + "protocol_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", + "implementation_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", + "implementation_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337" + "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337" + "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index c7719609a4..54473fb39f 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "9aec490617fc1234e8f0b215590b1fa1ee76fbc0e58334fa82452398cd162c21", - "seed_protocol": "ecb7d602a8a4358764d3a533ccca8a9561f578154cc84dd558a36dec8feee5e6", + "seed_map": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", + "seed_protocol": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index ae6e6f6816..b1e0878338 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "8093e4c0b8fd45d73378e75af2a82672ee0bc42114c2870e9c76dcd47094d880" + "8b4943101f67eaa7ab5859c2e756300bb775fade203ec281ee795db1b84bf1e3" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 3ee8430ff6..287e6fc149 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "4e85a50e5b0e34de194b9923ecf71197cf8f040252d736f168bcbce3456da337", + "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index f578e9ff03..a9861a2d84 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1184,11 +1184,13 @@ def _fill_tree_leaves( """Write one tree's leaf-to-training-row map into ``tree_leaves``. The body is quantile-forest 1.4.2's - ``BaseForestQuantileRegressor._get_y_train_leaves_slice`` with one - change: it writes into the caller's slice of the forest-wide array instead - of allocating a zeroed array of its own and returning it. Every other step, - including the grouping helper, the global ``random.seed``/``random.shuffle`` - calls and the order of the writes, is the library's. + ``BaseForestQuantileRegressor._get_y_train_leaves_slice``, except that it + writes into the caller's slice of the forest-wide array instead of + allocating a zeroed array of its own and returning it. So it takes no + ``max_node_count``, which only sized that array, and it checks that the + compiled helper wrote into the slice. Every other step, including the + grouping helper, the global ``random.seed``/``random.shuffle`` calls and the + order of the writes, is the library's. Args: tree_leaves: This tree's zeroed ``(nodes, outputs, width)`` slice of the @@ -1257,22 +1259,27 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): then copies the list into the final array with ``np.array(list)``. That copy writes every byte, padding included, so the whole padded array becomes resident memory, and for a while both the per-tree arrays and the - copy exist. Pages of an ``np.zeros`` array that are never written cost no - resident memory. + copy exist. This subclass allocates the final array once and writes each tree's entries straight into that tree's slice (:func:`_fill_tree_leaves`). The width, ``apply``, bootstrap replay and rank computation are the library's own, as are the ``random.seed``/``random.shuffle`` calls in tree order and the dtype, shape and C order of the result, so the array is byte-identical - to the library's and so is every prediction. Only the private - ``_get_y_train_leaves`` is replaced, so :meth:`fit` and - :meth:`_get_y_train_leaves` refuse any quantile-forest release other than - :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. - - Pickling a fitted forest, or deep-copying it, still writes the full padded - array: quantile-forest's ``QuantileForest.__reduce__`` hands the whole - array to pickle. + to the library's and so is every prediction. It replaces the private + ``_get_y_train_leaves`` and wraps :meth:`fit` only to check the version: + both refuse any quantile-forest release other than + :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. scikit-learn's validation + messages name this class instead of ``RandomForestQuantileRegressor``. + + The saving lasts while pages stay untouched. Pages of an ``np.zeros`` + array take no memory until something touches them. A write makes a page + resident, and on macOS so does a read: prediction reads each leaf row it + reaches, and pickling or deep-copying a fitted forest reads the whole + array, because quantile-forest's ``QuantileForest.__reduce__`` hands all + of it to pickle, which also writes it out in full. On Linux a read maps a + shared zero page instead, but where transparent huge pages are granted a + first write makes a whole 2 MiB region resident. """ def fit(self, X, y, sample_weight=None, sparse_pickle=False): # noqa: N803 diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index 517b4ee401..04be1b5aac 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -19,6 +19,7 @@ import importlib.metadata import inspect +import math import pickle import random import tomllib @@ -28,6 +29,7 @@ import pytest import quantile_forest from quantile_forest import RandomForestQuantileRegressor +from quantile_forest import _quantile_forest as quantile_forest_module from sklearn.base import clone from microcosm.fit import fit, qrf @@ -73,8 +75,9 @@ def _near_discrete_donors( def _sample_weights(seed: int, rows: int) -> np.ndarray: """Positive weights with a fifth of the rows at exactly zero. - The library drops zero-weight rows from each leaf, and refills a leaf - that empties with a placeholder, so both branches run. + The library's zero-weight filter runs on every leaf. With a fifth of the + weights at zero no leaf empties; + ``test_weighted_leaves_that_empty_get_the_library_placeholder`` covers that. """ generator = np.random.default_rng(seed) weights = generator.uniform(0.1, 3.0, rows) @@ -183,8 +186,15 @@ def test_continuous_target_without_a_cap_matches_the_library() -> None: assert leaves.shape[-1] > 1 -def test_near_discrete_target_over_the_cap_matches_the_library(monkeypatch) -> None: - """Leaves larger than the cap are shuffled and truncated identically.""" +@pytest.mark.parametrize("cap", [16, 0.0047]) +def test_near_discrete_target_over_the_cap_matches_the_library( + monkeypatch, cap +) -> None: + """Leaves larger than the cap are shuffled and truncated identically. + + The fractional cap is 0.0047 of 3,000 rows, 14.1, which the library rounds + up to 15. + """ shuffle_calls: list[int] = [] original_shuffle = random.shuffle @@ -193,19 +203,19 @@ def counting_shuffle(sequence): return original_shuffle(sequence) monkeypatch.setattr(random, "shuffle", counting_shuffle) - cap = 16 predictors, target = _near_discrete_donors(seed=2) leaves = _assert_same_fit(predictors, target, max_samples_leaf=cap) - assert leaves.shape[-1] == cap + width = cap if isinstance(cap, int) else math.ceil(cap * len(target)) + assert leaves.shape[-1] == width == (16 if isinstance(cap, int) else 15) # Both fits shuffled the same leaves, each larger than the cap, before # truncating them; the library fit ran first. half = len(shuffle_calls) // 2 assert half > 0 assert shuffle_calls[:half] == shuffle_calls[half:] - assert min(shuffle_calls) > cap + assert min(shuffle_calls) > width -@pytest.mark.parametrize("max_samples_leaf", [None, 5]) +@pytest.mark.parametrize("max_samples_leaf", [None, 5, 1]) def test_several_outputs_match_the_library(max_samples_leaf) -> None: predictors, first = _continuous_donors(seed=3) generator = np.random.default_rng(3) @@ -229,11 +239,45 @@ def test_weighted_samples_match_the_library(max_samples_leaf) -> None: ) +def test_weighted_leaves_that_empty_get_the_library_placeholder( + monkeypatch, +) -> None: + """A leaf whose entries the zero-weight filter removes holds ``[0]``. + + Nine in ten weights are zero, so some leaves empty. Both classes hand the + filtered leaves to quantile-forest's compiled helper, which records how + many hold the placeholder. + """ + placeholders: list[int] = [] + original_map = quantile_forest_module.map_indices_to_leaves + + def recording_map(**arguments): + placeholders.append( + sum( + isinstance(values, list) and values == [0] + for values in arguments["leaf_values_list"] + ) + ) + return original_map(**arguments) + + monkeypatch.setattr(quantile_forest_module, "map_indices_to_leaves", recording_map) + predictors, target = _continuous_donors(seed=15, rows=500) + generator = np.random.default_rng(15) + weights = generator.uniform(0.1, 3.0, len(target)) + weights[generator.random(len(target)) < 0.9] = 0.0 + _assert_same_fit(predictors, target, sample_weight=weights, max_samples_leaf=None) + half = len(placeholders) // 2 + assert half == 6 + assert placeholders[:half] == placeholders[half:] + assert sum(placeholders[half:]) > 0 + + @pytest.mark.parametrize( "parameters", [ pytest.param({}, id="library-default-one-sample-per-leaf"), - pytest.param({"max_samples_leaf": 0.02}, id="fractional-cap"), + # 0.021 of 400 rows is 8.4, which the library rounds up to 9. + pytest.param({"max_samples_leaf": 0.021}, id="fractional-cap"), pytest.param({"max_samples_leaf": None, "bootstrap": False}, id="no-bootstrap"), pytest.param({"max_samples_leaf": 9, "max_samples": 0.5}, id="half-bootstrap"), pytest.param( @@ -242,7 +286,11 @@ def test_weighted_samples_match_the_library(max_samples_leaf) -> None: ], ) def test_other_forest_settings_match_the_library(parameters) -> None: - """Settings microcosm does not use still give the library's array.""" + """Other forest settings still give the library's array. + + ``_fit_forest`` passes a fractional cap when a chain configuration asks + for one; the bootstrap settings are ones microcosm leaves at the default. + """ predictors, target = _continuous_donors(seed=5, rows=400) _assert_same_fit(predictors, target, **parameters) @@ -252,6 +300,37 @@ def test_parallel_tree_fitting_matches_the_library() -> None: _assert_same_fit(predictors, target, max_samples_leaf=None, n_jobs=-1) +def test_fill_refuses_a_helper_that_returns_a_copy(monkeypatch) -> None: + """If the compiled helper stopped writing into its argument, fitting fails. + + A copy would leave the preallocated slice at zero, so every leaf would + read as empty. + """ + original_map = quantile_forest_module.map_indices_to_leaves + + def copying_map(**arguments): + arguments["y_train_leaves_slice"] = arguments["y_train_leaves_slice"].copy() + return original_map(**arguments) + + monkeypatch.setattr(quantile_forest_module, "map_indices_to_leaves", copying_map) + predictors, target = _continuous_donors(seed=16, rows=100) + model = qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=0) + with pytest.raises(RuntimeError, match="returned a copy"): + model.fit(predictors, target) + + +def test_sparse_pickle_reaches_the_library() -> None: + predictors, target = _continuous_donors(seed=17, rows=200) + model = qrf._InPlaceLeafQRF(n_estimators=3, max_samples_leaf=None, random_state=2) + model.fit(predictors, target, sparse_pickle=True) + assert model.forest_.sparse_pickle + restored = pickle.loads(pickle.dumps(model)) + _assert_byte_identical( + np.asarray(restored.forest_.y_train_leaves), + np.asarray(model.forest_.y_train_leaves), + ) + + # ---------------------------------------------------------------------------- # microcosm's forest construction uses the subclass # ---------------------------------------------------------------------------- diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 173c557d27..0c60ff1c4b 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"1000f513f729fc0fc41e4ac0bdf1ce8a2545a67efaba23527b3a01f273e81937","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"687476edcdd08ed71bf53940543962145e62e40ac7aae864f0d788770ac9d1d8","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"687476edcdd08ed71bf53940543962145e62e40ac7aae864f0d788770ac9d1d8"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"70ac58c22b3162a5fce85e7f54d4b78cc3401ab1eeb4eca47cd2fc7a943a8ca1"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"54d0c2d11c6e04a0ccc5f270fae00d181a48bb27a94ef85e2088aff0d6326fe8"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"57c7eb13e48fe5257630376ced689407039380ffcb91df8257c2736cbb0c326e","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"166b34a87ae5998e01a245e6e05e2f3804c4933b0613ba8ef4ffdd338b834a5f","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"166b34a87ae5998e01a245e6e05e2f3804c4933b0613ba8ef4ffdd338b834a5f"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"e0b4ea4f53bc17f58924eb46666422b3e3973edd8e58566c9498776fe3dc8939"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"81f749f2ea2e003ca1267d491bfe33f832fa91e697354c6a1afde787e7aee962"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 8d0313390f..5c3f54f8e9 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -8,25 +8,30 @@ microcosm's ``_fit_forest`` (the weighted resample, the near-discrete cap and the forest), once with each class and each in a fresh Python process. For the library run the child process replaces the class ``_fit_forest`` builds with -quantile-forest's own. Each child reports its peak memory just before and just -after the fit, so the fit's own peak growth is the difference. +quantile-forest's own, and each child checks which class it fitted. Each child +reports its peak memory just before and just after the fit, so the fit's own +peak growth is the difference. Peak memory is read as follows: - macOS: the process's lifetime peak physical footprint (``proc_pid_rusage``'s ``ri_lifetime_max_phys_footprint``), which counts - pages macOS has compressed under memory pressure. The resident set size - (``ru_maxrss``) is reported too, but it drops when pages are compressed, so + pages macOS has compressed under memory pressure. The peak resident set size + (``ru_maxrss``) is reported beside it; it drops when pages are compressed, so on a busy machine it can read lower than the memory the fit used. - Linux: the peak resident set size (``ru_maxrss``). Pages swapped out under memory pressure are not counted, so measure on a machine with free memory. +Growth can also read a little low when the fit reuses memory that the process +already used, and so already counted in its peak, before the fit started. That +matters only for small fits. + The result depends on the platform. On macOS, reading a never-written page of an ``np.zeros`` array makes it resident; on Linux it maps the shared zero page, -which is not counted. Where Linux transparent huge pages are enabled for large -arrays, a first write makes a whole 2 MiB region resident, which shrinks the -in-place saving. The report records the platform, the page size and the huge -page mode. +which is not counted. On Linux, numpy asks for transparent huge pages on large +arrays, and where the kernel grants them a first write makes a whole 2 MiB +region resident, which shrinks the in-place saving. The report records the +platform, the page size, the kernel's huge page mode and numpy's request. Two synthetic shapes stand in for the build's heavy fits. Neither reads survey data. Donor weights are lognormal, so ``_fit_forest``'s weighted resample @@ -34,11 +39,13 @@ - ``wage``: the CPS-ORG ``hourly_wage`` forest. 100 trees, a continuous positive target and no leaf cap. The full donor pool has 119,237 rows; the - default here is 10,000. Earnings are continuous, so most rows have their - own predictor vector, but ``--rows-in-widest-leaf`` rows share one vector - that no split separates. That leaf is the widest, and its draws set the - array's padded width. The production width is not recorded anywhere, so - this value is a parameter, not a measurement. + default here is 10,000. Wages are whole dollars, so neighbouring donors + often share a wage and the trees grow about 0.7 nodes per donor row, the + top of the 0.4 to 0.7 the build's trees have. ``--rows-in-widest-leaf`` rows + share one predictor vector that no split separates; their draws, after the + weighted resample and the forest's bootstrap, make the widest leaf and so + set the array's padded width, which the report shows. The production width + is not recorded anywhere, so that option is a parameter, not a measurement. - ``near-discrete``: a base-stage near-discrete target. 32 trees and five distinct values dominated by zero, so ``_fit_forest`` applies its 4,096-entry cap. The production pool has up to 207,692 rows; the default @@ -55,13 +62,17 @@ uv run python tools/measure_qrf_leaf_memory.py --shape wage --rows 5000 --json Set ``POPULACE_FIT_N_JOBS`` to fix quantile-forest's thread count, as for a -build; the report records the value each fit used. +build; the report records the setting and the thread count it gave. The script also hashes each leaf array after the fit and reports whether the two arrays have the same shape, dtype and bytes. Hashing happens after the peak is read, so it never raises the reported peak, but on macOS it reads every page and so raises the process's real memory to the array's full size. Pass ``--no-digest`` for large runs. + +If one measurement fails, for example because the operating system stopped +the library run for using too much memory, the other still runs, the report +shows what completed, and the exit code is 1. """ from __future__ import annotations @@ -76,6 +87,7 @@ import os import platform import resource +import signal import subprocess import sys import time @@ -84,9 +96,14 @@ import numpy as np IMPLEMENTATIONS = ("library", "in-place") +EXPECTED_CLASSES = { + "library": "quantile_forest._quantile_forest.RandomForestQuantileRegressor", + "in-place": "microcosm.fit.qrf._InPlaceLeafQRF", +} SHAPES = ("wage", "near-discrete") DEFAULT_TREES = {"wage": 100, "near-discrete": 32} DEFAULT_ROWS = {"wage": 10_000, "near-discrete": 10_000} +DEFAULT_ROWS_IN_WIDEST_LEAF = 250 #: scikit-learn accepts integer seeds below 2**32. SEED_LIMIT = 2**32 _RUSAGE_INFO_V4 = 4 @@ -145,13 +162,22 @@ def _peak_resident_bytes() -> int: def _peak_footprint_bytes() -> int | None: - """Return macOS's lifetime peak physical footprint, or None elsewhere.""" + """Return macOS's lifetime peak physical footprint. + + Returns None off macOS, or where ``proc_pid_rusage`` cannot be loaded, so + the caller falls back to the resident set size. + """ if sys.platform != "darwin": return None - library = ctypes.CDLL("/usr/lib/libproc.dylib") + try: + system = ctypes.CDLL("/usr/lib/libSystem.B.dylib", use_errno=True) + read_usage = system.proc_pid_rusage + except (OSError, AttributeError): + return None information = _RusageInfoV4() - if library.proc_pid_rusage(os.getpid(), _RUSAGE_INFO_V4, ctypes.byref(information)): - raise OSError("proc_pid_rusage failed") + if read_usage(os.getpid(), _RUSAGE_INFO_V4, ctypes.byref(information)) != 0: + error = ctypes.get_errno() + raise OSError(error, f"proc_pid_rusage failed: {os.strerror(error)}") return int(information.ri_lifetime_max_phys_footprint) @@ -164,20 +190,30 @@ def _peak_memory() -> dict[str, int | None]: def _huge_page_mode() -> str | None: """Return Linux's transparent huge page setting, or None elsewhere.""" - path = Path("/sys/kernel/mm/transparent_hugepage/enabled") try: - return path.read_text().strip() + return Path("/sys/kernel/mm/transparent_hugepage/enabled").read_text().strip() except OSError: return None +def _numpy_requests_huge_pages() -> bool | None: + try: + from numpy._core import multiarray + + return bool(multiarray._get_madvise_hugepage()) + except (ImportError, AttributeError): + return None + + def _environment() -> dict[str, object]: return { "platform": platform.platform(), "machine": platform.machine(), "python": platform.python_version(), + "cpu_count": os.cpu_count(), "page_size_bytes": resource.getpagesize(), "transparent_huge_pages": _huge_page_mode(), + "numpy_requests_huge_pages": _numpy_requests_huge_pages(), "packages": { name: importlib.metadata.version(name) for name in ("numpy", "scikit-learn", "quantile-forest") @@ -192,10 +228,10 @@ def _wage_donors( The predictors mirror ``ORG_PREDICTORS`` in kind: annual earnings, weekly hours, age, sex, Hispanic origin, a four-way race code and a state code. - Earnings are continuous, so most rows have their own predictor vector. The - first ``rows_in_widest_leaf`` rows share one predictor vector (a full-time - worker at $15 an hour) with differing wages; no split separates them, so - they make the widest leaf and set the array's width. + The wage follows earnings over hours with some noise, in whole dollars. + The first ``rows_in_widest_leaf`` rows share one predictor vector (a + full-time worker earning about $15 an hour) with differing wages; no split + separates them, so they make the widest leaf. """ generator = np.random.default_rng(seed) hours = generator.choice( @@ -215,8 +251,8 @@ def _wage_donors( ).astype(np.float64) predictors[:rows_in_widest_leaf] = [15.0 * 40.0 * 52.0, 40.0, 30.0, 1, 0, 1, 6] typical_wage = predictors[:, 0] / (52.0 * predictors[:, 1]) - wage = np.round(typical_wage * np.exp(generator.normal(0.0, 0.3, rows)), 2) - return predictors, np.maximum(wage, 0.01) + wage = np.round(typical_wage * np.exp(generator.normal(0.0, 0.15, rows))) + return predictors, np.maximum(wage, 1.0) def _near_discrete_donors(rows: int, seed: int) -> tuple[np.ndarray, np.ndarray]: @@ -250,6 +286,7 @@ def _donors(arguments: argparse.Namespace) -> tuple[np.ndarray, ...]: def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: """Fit one forest with ``arguments.child`` and report its memory.""" + import joblib from quantile_forest import RandomForestQuantileRegressor from microcosm.fit import qrf @@ -280,14 +317,25 @@ def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: after = _peak_memory() model = forest.model + fitted_class = f"{type(model).__module__}.{type(model).__qualname__}" + if fitted_class != EXPECTED_CLASSES[arguments.child]: + raise RuntimeError( + f"the {arguments.child} run fitted {fitted_class}, not " + f"{EXPECTED_CLASSES[arguments.child]}; _fit_forest no longer builds " + "the class this script replaces" + ) leaves = np.asarray(model.forest_.y_train_leaves) digest = None if not arguments.no_digest: digest = hashlib.sha256(memoryview(np.ascontiguousarray(leaves))).hexdigest() - measure = "physical_footprint" if after["physical_footprint"] else "resident_set" + measure = ( + "physical_footprint" + if after["physical_footprint"] is not None + else "resident_set" + ) return { "implementation": arguments.child, - "class": f"{type(model).__module__}.{type(model).__qualname__}", + "class": fitted_class, "shape": arguments.shape, "rows": arguments.rows, "trees": arguments.trees, @@ -296,6 +344,7 @@ def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: ), "seed": arguments.seed, "n_jobs": model.n_jobs, + "threads": joblib.effective_n_jobs(model.n_jobs), "max_samples_leaf": model.max_samples_leaf, "leaf_array_shape": list(leaves.shape), "leaf_array_dtype": str(leaves.dtype), @@ -334,12 +383,49 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s return command +def _run_child(arguments: argparse.Namespace, implementation: str) -> dict | str: + """Run one measurement; return its result, or why it failed.""" + completed = subprocess.run( + _child_command(arguments, implementation), + stdout=subprocess.PIPE, + text=True, + check=False, + ) + if completed.returncode < 0: + stopped_by = signal.Signals(-completed.returncode).name + return ( + f"the {implementation} measurement was stopped by {stopped_by}; an " + "out-of-memory stop by the operating system looks like this" + ) + if completed.returncode != 0: + return ( + f"the {implementation} measurement failed with exit code " + f"{completed.returncode}; its error is printed above" + ) + return json.loads(completed.stdout.strip().splitlines()[-1]) + + +def _identical(results: list[dict[str, object]]) -> bool | None: + if len(results) != 2 or any( + result["leaf_array_sha256"] is None for result in results + ): + return None + return all( + results[0][key] == results[1][key] + for key in ("leaf_array_shape", "leaf_array_dtype", "leaf_array_sha256") + ) + + def _size(value: int) -> str: if abs(value) >= 2**30: return f"{value / 2**30:.2f} GiB" return f"{value / 2**20:.1f} MiB" +def _plural(count: int, word: str) -> str: + return f"{count:,} {word}" + ("" if count == 1 else "s") + + def _array_description(result: dict[str, object]) -> str: shape = " x ".join(f"{size:,}" for size in result["leaf_array_shape"]) return ( @@ -348,23 +434,32 @@ def _array_description(result: dict[str, object]) -> str: ) -def _report(results: list[dict[str, object]], *, digests: bool) -> str: +def _report( + results: list[dict[str, object]], failures: list[str], identical: bool | None +) -> str: + lines = list(failures) + if not results: + return "\n".join(lines) first = results[0] environment = first["environment"] - trees = int(first["trees"]) - lines = [ - f"{environment['platform']}, page size {environment['page_size_bytes']:,} " - f"bytes, transparent huge pages: {environment['transparent_huge_pages']}", - f"shape {first['shape']}: {first['rows']:,} donor rows, {trees} " - f"{'tree' if trees == 1 else 'trees'}, max_samples_leaf=" - f"{first['max_samples_leaf']}, n_jobs={first['n_jobs']}, seed {first['seed']}" + lines += [ + f"{environment['platform']}, {environment['cpu_count']} CPUs, page size " + f"{environment['page_size_bytes']:,} bytes, transparent huge pages: " + f"{environment['transparent_huge_pages']}, numpy requests huge pages: " + f"{environment['numpy_requests_huge_pages']}", + f"shape {first['shape']}: {_plural(int(first['rows']), 'donor row')}, " + f"{_plural(int(first['trees']), 'tree')}, max_samples_leaf=" + f"{first['max_samples_leaf']}, n_jobs={first['n_jobs']} " + f"({_plural(int(first['threads']), 'thread')}), seed {first['seed']}" + ( - f", {first['rows_in_widest_leaf']:,} rows in the widest leaf" + f", {_plural(int(first['rows_in_widest_leaf']), 'row')} sharing one " + "predictor vector" if first["rows_in_widest_leaf"] is not None else "" ), ] - if len({_array_description(result) for result in results}) == 1: + descriptions = {_array_description(result) for result in results} + if len(descriptions) == 1: lines.append("leaf array: " + _array_description(first)) measure = ( "peak physical footprint" @@ -372,29 +467,29 @@ def _report(results: list[dict[str, object]], *, digests: bool) -> str: else "peak resident set" ) for result in results: - if len({_array_description(result) for result in results}) > 1: + if len(descriptions) > 1: lines.append( f"{result['implementation']} leaf array: {_array_description(result)}" ) + resident = "" + if result["memory_measure"] != "resident_set": + resident = ( + " (peak resident set " + f"{_size(int(result['peak_resident_set_bytes_after_fit']))}, the fit " + "added " + + _size( + int(result["peak_resident_set_bytes_after_fit"]) + - int(result["peak_resident_set_bytes_before_fit"]) + ) + + ")" + ) lines.append( - f"{result['implementation']}: {measure} " + f"{result['implementation']} ({result['class']}): {measure} " f"{_size(int(result['peak_bytes_after_fit']))}, of which the fit " - f"added {_size(int(result['fit_peak_growth_bytes']))}; fit took " - f"{result['fit_seconds']:.1f} s" - ) - if result["implementation"] == "library" and int( - result["fit_peak_growth_bytes"] - ) < int(result["leaf_array_bytes"]): - lines.append( - "warning: the library fit's growth is below the leaf array's size, " - "although its copy writes every byte; memory was compressed or " - "swapped out during the fit, so these readings are too low" - ) - if digests and len(results) == 2: - identical = all( - results[0][key] == results[1][key] - for key in ("leaf_array_shape", "leaf_array_dtype", "leaf_array_sha256") + f"added {_size(int(result['fit_peak_growth_bytes']))}{resident}; fit " + f"took {result['fit_seconds']:.1f} s" ) + if identical is not None: lines.append("leaf arrays byte-identical: " + ("yes" if identical else "NO")) return "\n".join(lines) @@ -413,9 +508,9 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: parser.add_argument( "--rows-in-widest-leaf", type=int, - default=250, help="wage shape only: donor rows that share one predictor vector " - "(default 250), which sets the array's width", + f"(default {DEFAULT_ROWS_IN_WIDEST_LEAF}, or half of --rows if that is " + "smaller); their draws make the widest leaf, whose width the report shows", ) parser.add_argument("--seed", type=int, default=20261117) parser.add_argument( @@ -434,6 +529,10 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: arguments.rows = DEFAULT_ROWS[arguments.shape] if arguments.trees is None: arguments.trees = DEFAULT_TREES[arguments.shape] + if arguments.rows_in_widest_leaf is None: + arguments.rows_in_widest_leaf = max( + 1, min(DEFAULT_ROWS_IN_WIDEST_LEAF, arguments.rows // 2) + ) if arguments.rows < 2: parser.error("--rows must be at least 2") if arguments.trees < 1: @@ -444,13 +543,21 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: 1 <= arguments.rows_in_widest_leaf <= arguments.rows ): parser.error("--rows-in-widest-leaf must be between 1 and --rows") - if arguments.shape == "near-discrete" and arguments.child is None: + if arguments.child is None: + from microcosm.fit.qrf import _DISCRETE_Y_UNIQUE_MAX + distinct = len(np.unique(_donors(arguments)[1])) - if distinct < 2: + if arguments.shape == "near-discrete" and distinct < 2: parser.error( f"with --rows {arguments.rows} the near-discrete target has " f"{distinct} distinct value; raise --rows" ) + if arguments.shape == "wage" and distinct <= _DISCRETE_Y_UNIQUE_MAX: + parser.error( + f"with --rows {arguments.rows} the wage target has only {distinct} " + f"distinct values, so _fit_forest would cap its leaves as a " + "near-discrete target; raise --rows" + ) return arguments @@ -465,27 +572,29 @@ def main(argv: list[str] | None = None) -> int: if arguments.implementation == "both" else (arguments.implementation,) ) - results = [] + results: list[dict[str, object]] = [] + failures: list[str] = [] for implementation in implementations: - completed = subprocess.run( - _child_command(arguments, implementation), - stdout=subprocess.PIPE, - text=True, - check=False, - ) - if completed.returncode != 0: - print( - f"the {implementation} measurement failed with exit code " - f"{completed.returncode}; its error is printed above", - file=sys.stderr, - ) - return 1 - results.append(json.loads(completed.stdout.strip().splitlines()[-1])) + outcome = _run_child(arguments, implementation) + if isinstance(outcome, str): + failures.append(outcome) + else: + results.append(outcome) + identical = _identical(results) if arguments.json: - print(json.dumps(results, indent=2)) + print( + json.dumps( + { + "results": results, + "failures": failures, + "leaf_arrays_identical": identical, + }, + indent=2, + ) + ) else: - print(_report(results, digests=not arguments.no_digest)) - return 0 + print(_report(results, failures, identical)) + return 1 if failures else 0 if __name__ == "__main__": From 1dea2d1d5d7ea4cb26e9942aebf350c55a5a9dee Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:35:58 +0400 Subject: [PATCH 05/15] Address round-three review: test the remaining mutations, tighten the memory script Round three found no defect in the leaf array, the random state or the predictions; nine deliberate code changes that alter behaviour still passed the tests. New tests cover each: - the forest keeps the one preallocated buffer the fill wrote (a copy has the same bytes but makes every padding page resident); - fit returns the model, and the default pickle format stays dense; - DataFrame predictors give the library's warnings and array; - emptied weighted leaves under a cap of 3 and of 1; - weights that are tiny, zero or negative go through the library's positive-weight filter; - a quantile-forest without __version__ is refused; - with scikit-learn 1.9 reported, both classes pass the same sample_weight_ to the private bootstrap helpers. Docstrings now say the fill checks that the helper's result shares memory with the slice, that the filter drops non-positive weights, and that an oversized max_samples_leaf raises ValueError where the library raises MemoryError; the pyproject comment names the private sklearn helpers the copy calls. tools/measure_qrf_leaf_memory.py: a child that exits without a JSON result is a failure instead of a crash; differing leaf arrays set exit code 1; only SIGKILL gets the out-of-memory note, and unnamed signals are printed by number; the report gives trees grown at once rather than the pool size, labels each result's own measure, and says when --no-digest skipped the comparison; --json records the arguments and structured failures; --rows-in-widest-leaf is refused for the near-discrete shape; the docstring states the sizes from which the widest-leaf and node-density statements hold, and why the wage shape's saving is mostly the second copy. Re-pinned the US F0 spec pins (repin, coverage 41/41, repin, --check clean) and the fit.qrf parity pins; direct.csv is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- packages/microcosm-fit/pyproject.toml | 5 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 11 +- .../engine_free/shared/test_qrf_leaf_array.py | 151 +++++++++++++++- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 164 +++++++++++++----- 9 files changed, 289 insertions(+), 68 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 079f3f529c..19147039d0 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", - "protocol_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7" + "map_sha256": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", + "protocol_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004" }, "failures": [], "observed": { - "map_sha256": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", - "protocol_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7" + "map_sha256": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", + "protocol_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", + "implementation_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", + "implementation_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3" + "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3" + "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 54473fb39f..34c09c89c3 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "46d360f5e1e9ccc99abda87b65ed11dcf03ec69d1ce8f4cea6ea5af35e1d56f4", - "seed_protocol": "e58b68b1a21174b74f5ece6e289494d96ababd6f95ad21890d3635a6080b63c7", + "seed_map": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", + "seed_protocol": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index b1e0878338..67e0c2729f 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "8b4943101f67eaa7ab5859c2e756300bb775fade203ec281ee795db1b84bf1e3" + "dbd6b7ca962cf0d4e36032adaad61ed0614fc50fca20d56b00e69d17aaa47e71" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 287e6fc149..87ba7008b9 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "6126a0a18b9e2fbed9185251a7a1dd461d205e7fc3437c5e91ca35142842dbe3", + "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629", }, } diff --git a/packages/microcosm-fit/pyproject.toml b/packages/microcosm-fit/pyproject.toml index 1156a642f8..4b7788280e 100644 --- a/packages/microcosm-fit/pyproject.toml +++ b/packages/microcosm-fit/pyproject.toml @@ -15,7 +15,10 @@ dependencies = [ # 1.4.2 (2026-06-21) tracks both (zillow/quantile-forest#152, #153), so it # is the first release compatible with sklearn 1.9. No upper bound: this # package's own sklearn usage (HistGradientBoostingClassifier, forest - # .fit() without sample_weight) is stable across 1.5-1.9. + # .fit() without sample_weight) is stable across 1.5-1.9. The leaf-array + # copy in microcosm.fit.qrf also calls sklearn's private bootstrap helpers, + # through quantile-forest's module, with the arguments 1.4.2 passes them + # for the installed sklearn version. "scikit-learn>=1.5", # Exact: microcosm.fit.qrf._InPlaceLeafQRF replaces the private # BaseForestQuantileRegressor._get_y_train_leaves with a copy of 1.4.2's diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index a9861a2d84..e8e8fa1b23 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1188,7 +1188,8 @@ def _fill_tree_leaves( writes into the caller's slice of the forest-wide array instead of allocating a zeroed array of its own and returning it. So it takes no ``max_node_count``, which only sized that array, and it checks that the - compiled helper wrote into the slice. Every other step, including the + array the compiled helper returns shares memory with the slice, as it does + when the helper writes into its argument. Every other step, including the grouping helper, the global ``random.seed``/``random.shuffle`` calls and the order of the writes, is the library's. @@ -1219,7 +1220,8 @@ def _fill_tree_leaves( for leaf in range(len(leaf_values_list)): if sample_weight is not None: - # quantile-forest 1.4.2 drops zero-weight entries this way. + # quantile-forest 1.4.2 drops entries whose weight is not + # positive this way. weight_mask = sample_weight[leaf_values_list[leaf] - 1] > 0 leaf_values_list[leaf] = leaf_values_list[leaf][weight_mask] if leaf_subsample: @@ -1270,7 +1272,10 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): ``_get_y_train_leaves`` and wraps :meth:`fit` only to check the version: both refuse any quantile-forest release other than :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. scikit-learn's validation - messages name this class instead of ``RandomForestQuantileRegressor``. + messages name this class instead of ``RandomForestQuantileRegressor``. A + ``max_samples_leaf`` so large that the whole forest's array exceeds the + largest size numpy can describe raises numpy's ``ValueError`` here, where + the library, allocating one tree at a time, raises ``MemoryError``. The saving lasts while pages stay untouched. Pages of an ``np.zeros`` array take no memory until something touches them. A write makes a page diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index 04be1b5aac..fe82507ca8 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -23,6 +23,7 @@ import pickle import random import tomllib +import warnings import numpy as np import pandas as pd @@ -31,6 +32,7 @@ from quantile_forest import RandomForestQuantileRegressor from quantile_forest import _quantile_forest as quantile_forest_module from sklearn.base import clone +from sklearn.utils.fixes import parse_version from microcosm.fit import fit, qrf from test_support.paths import paths_for @@ -59,7 +61,7 @@ def _near_discrete_donors( """Target with four distinct values, dominated by zero. Two predictors with ``predictor_levels`` values each give at most - ``predictor_levels**2`` distinct predictor vectors, so leaves hold hundreds + ``predictor_levels**2`` distinct predictor vectors, so leaves hold tens to hundreds of rows: far more than the small caps the tests set. """ generator = np.random.default_rng(seed) @@ -239,14 +241,16 @@ def test_weighted_samples_match_the_library(max_samples_leaf) -> None: ) +@pytest.mark.parametrize("max_samples_leaf", [None, 3, 1]) def test_weighted_leaves_that_empty_get_the_library_placeholder( - monkeypatch, + monkeypatch, max_samples_leaf ) -> None: """A leaf whose entries the zero-weight filter removes holds ``[0]``. Nine in ten weights are zero, so some leaves empty. Both classes hand the filtered leaves to quantile-forest's compiled helper, which records how - many hold the placeholder. + many hold the placeholder. With a cap of one entry the helper is not + used, and only the arrays are compared. """ placeholders: list[int] = [] original_map = quantile_forest_module.map_indices_to_leaves @@ -265,13 +269,38 @@ def recording_map(**arguments): generator = np.random.default_rng(15) weights = generator.uniform(0.1, 3.0, len(target)) weights[generator.random(len(target)) < 0.9] = 0.0 - _assert_same_fit(predictors, target, sample_weight=weights, max_samples_leaf=None) + _assert_same_fit( + predictors, + target, + sample_weight=weights, + max_samples_leaf=max_samples_leaf, + ) + if max_samples_leaf == 1: + assert placeholders == [] + return + # Six trees per class, each handed to the helper once. half = len(placeholders) // 2 assert half == 6 assert placeholders[:half] == placeholders[half:] assert sum(placeholders[half:]) > 0 +@pytest.mark.parametrize("max_samples_leaf", [None, 5]) +def test_weight_filter_drops_every_weight_that_is_not_positive( + max_samples_leaf, +) -> None: + """Small positive weights stay; zero and negative weights go, as in 1.4.2.""" + predictors, target = _continuous_donors(seed=18, rows=600) + generator = np.random.default_rng(18) + weights = generator.choice([-1.0, 0.0, 1e-3, 0.04, 0.5, 2.0, 3.0], len(target)) + _assert_same_fit( + predictors, + target, + sample_weight=weights, + max_samples_leaf=max_samples_leaf, + ) + + @pytest.mark.parametrize( "parameters", [ @@ -301,10 +330,11 @@ def test_parallel_tree_fitting_matches_the_library() -> None: def test_fill_refuses_a_helper_that_returns_a_copy(monkeypatch) -> None: - """If the compiled helper stopped writing into its argument, fitting fails. + """If the compiled helper returned a copy, fitting fails. - A copy would leave the preallocated slice at zero, so every leaf would - read as empty. + The fill checks that the array the helper returns shares memory with the + slice it was given. A copy would leave the preallocated slice at zero, so + every leaf would read as empty. """ original_map = quantile_forest_module.map_indices_to_leaves @@ -319,6 +349,105 @@ def copying_map(**arguments): model.fit(predictors, target) +def test_forest_keeps_the_array_the_fill_wrote(monkeypatch) -> None: + """The stored leaf array is the one preallocated buffer, not a copy of it. + + A copy would hold the same bytes but make every padding page resident, + which is the memory this subclass exists to save. + """ + written: list[np.ndarray] = [] + original_fill = qrf._fill_tree_leaves + + def recording_fill(tree_leaves, *arguments): + written.append(tree_leaves) + return original_fill(tree_leaves, *arguments) + + monkeypatch.setattr(qrf, "_fill_tree_leaves", recording_fill) + predictors, target = _continuous_donors(seed=19, rows=300) + model = qrf._InPlaceLeafQRF(n_estimators=4, max_samples_leaf=None, random_state=1) + model.fit(predictors, target) + stored = np.asarray(model.forest_.y_train_leaves) + assert len(written) == 4 + for tree, tree_leaves in enumerate(written): + assert np.shares_memory(stored[tree], tree_leaves) + # One buffer for the whole forest: each slice is a view of the same base. + assert {id(tree_leaves.base) for tree_leaves in written} == {id(written[0].base)} + + +def test_fit_returns_the_model_and_keeps_the_default_pickle_format() -> None: + predictors, target = _continuous_donors(seed=20, rows=150) + model = qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=4) + assert model.fit(predictors, target) is model + assert not model.forest_.sparse_pickle + + +def test_dataframe_predictors_give_the_library_warnings_and_array() -> None: + """quantile-forest silences ``apply``'s feature-name warning; so does the copy.""" + predictors, target = _continuous_donors(seed=21, rows=300) + frame = pd.DataFrame(predictors, columns=["first", "second", "third"]) + warning_texts = {} + leaves = {} + for name, model_class in ( + ("library", RandomForestQuantileRegressor), + ("in_place", qrf._InPlaceLeafQRF), + ): + model = model_class(n_estimators=3, max_samples_leaf=None, random_state=6) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + model.fit(frame, target) + warning_texts[name] = [ + (type(warning.message), str(warning.message)) for warning in caught + ] + leaves[name] = np.asarray(model.forest_.y_train_leaves) + assert warning_texts["in_place"] == warning_texts["library"] + _assert_byte_identical(leaves["in_place"], leaves["library"]) + + +def test_scikit_learn_1_9_bootstrap_arguments_match_the_library(monkeypatch) -> None: + """Under scikit-learn 1.9 both classes pass the helpers the same weights. + + scikit-learn 1.9 adds a ``sample_weight`` argument to its private + bootstrap helpers, and quantile-forest 1.4.2 passes ``sample_weight_`` + when it finds 1.9 or later. The installed scikit-learn is older, so the + test reports 1.9 and wraps the helpers to record that argument and drop it. + """ + recorded: list[tuple[str, object]] = [] + original_count = quantile_forest_module._get_n_samples_bootstrap + original_indices = quantile_forest_module._generate_sample_indices + + def count_with_weights(n_samples, max_samples, sample_weight): + recorded.append( + ("count", None if sample_weight is None else sample_weight.sum()) + ) + return original_count(n_samples, max_samples) + + def indices_with_weights( + random_state, n_samples, n_samples_bootstrap, sample_weight + ): + recorded.append( + ("indices", None if sample_weight is None else sample_weight.sum()) + ) + return original_indices(random_state, n_samples, n_samples_bootstrap) + + monkeypatch.setattr( + quantile_forest_module, "sklearn_version", parse_version("1.9.0") + ) + monkeypatch.setattr( + quantile_forest_module, "_get_n_samples_bootstrap", count_with_weights + ) + monkeypatch.setattr( + quantile_forest_module, "_generate_sample_indices", indices_with_weights + ) + predictors, target = _continuous_donors(seed=22, rows=300) + weights = np.random.default_rng(22).uniform(0.5, 2.0, len(target)) + _assert_same_fit(predictors, target, sample_weight=weights, max_samples_leaf=None) + # One count and one index call per tree (six trees), for each class. + half = len(recorded) // 2 + assert half == 7 + assert recorded[:half] == recorded[half:] + assert all(weight_sum == pytest.approx(weights.sum()) for _, weight_sum in recorded) + + def test_sparse_pickle_reaches_the_library() -> None: predictors, target = _continuous_donors(seed=17, rows=200) model = qrf._InPlaceLeafQRF(n_estimators=3, max_samples_leaf=None, random_state=2) @@ -614,6 +743,14 @@ def test_library_fit_on_the_subclass_refuses_another_version(monkeypatch) -> Non RandomForestQuantileRegressor.fit(model, predictors, target) +def test_fit_refuses_a_quantile_forest_without_a_version(monkeypatch) -> None: + monkeypatch.delattr(quantile_forest, "__version__") + predictors, target = _continuous_donors(seed=23, rows=60) + model = qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=0) + with pytest.raises(RuntimeError, match="None is installed"): + model.fit(predictors, target) + + def test_fit_forest_refuses_another_quantile_forest_version(monkeypatch) -> None: monkeypatch.setattr(quantile_forest, "__version__", "1.4.3") predictors, target = _continuous_donors(seed=13, rows=60) diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 0c60ff1c4b..452eac4e42 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"57c7eb13e48fe5257630376ced689407039380ffcb91df8257c2736cbb0c326e","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"166b34a87ae5998e01a245e6e05e2f3804c4933b0613ba8ef4ffdd338b834a5f","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"166b34a87ae5998e01a245e6e05e2f3804c4933b0613ba8ef4ffdd338b834a5f"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"e0b4ea4f53bc17f58924eb46666422b3e3973edd8e58566c9498776fe3dc8939"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"81f749f2ea2e003ca1267d491bfe33f832fa91e697354c6a1afde787e7aee962"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"a5de61571ec6e3cce429cd3038545b771580e447c908952b760314645fa20cb7","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"05f2e733ccadfd9b8172e74f5ba8c530a3da70cfdc1a1f35d5642358162b270b","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"05f2e733ccadfd9b8172e74f5ba8c530a3da70cfdc1a1f35d5642358162b270b"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"c75496ab781ed7da968b1d710b0b02e68f6e6006beba60590f6835e553c1b280"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"c91c2082e858e3066d3f7493d6fcd907735abb0c058ddede9e557956883af485"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 5c3f54f8e9..2d559f8a19 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -17,8 +17,9 @@ - macOS: the process's lifetime peak physical footprint (``proc_pid_rusage``'s ``ri_lifetime_max_phys_footprint``), which counts pages macOS has compressed under memory pressure. The peak resident set size - (``ru_maxrss``) is reported beside it; it drops when pages are compressed, so - on a busy machine it can read lower than the memory the fit used. + (``ru_maxrss``) is reported beside it; the resident set shrinks when pages + are compressed, so on a busy machine its peak can understate the memory the + fit used. - Linux: the peak resident set size (``ru_maxrss``). Pages swapped out under memory pressure are not counted, so measure on a machine with free memory. @@ -37,21 +38,32 @@ data. Donor weights are lognormal, so ``_fit_forest``'s weighted resample duplicates rows as it does for weighted survey donors. -- ``wage``: the CPS-ORG ``hourly_wage`` forest. 100 trees, a continuous - positive target and no leaf cap. The full donor pool has 119,237 rows; the - default here is 10,000. Wages are whole dollars, so neighbouring donors - often share a wage and the trees grow about 0.7 nodes per donor row, the - top of the 0.4 to 0.7 the build's trees have. ``--rows-in-widest-leaf`` rows - share one predictor vector that no split separates; their draws, after the - weighted resample and the forest's bootstrap, make the widest leaf and so - set the array's padded width, which the report shows. The production width - is not recorded anywhere, so that option is a parameter, not a measurement. +- ``wage``: the CPS-ORG ``hourly_wage`` forest. 100 trees, a positive target + in whole dollars with hundreds of distinct values, which ``_fit_forest`` + treats as continuous, so no leaf cap. The full donor pool has 119,237 rows; + the default here is 10,000. Because wages are whole dollars, neighbouring + donors often share a wage, and from about 2,000 rows the trees grow about + 0.7 nodes per donor row, the top of the 0.4 to 0.7 the build's trees have + (fewer at small sizes, where the shared rows below are a large share of the + donors). ``--rows-in-widest-leaf`` rows share one predictor vector that no + split separates. From about 30 such rows, their draws after the weighted + resample and the forest's bootstrap make the widest leaf and so set the + array's padded width; other leaves hold about 30 entries at most. The + report shows the width. The production width is not recorded anywhere, so + that option is a parameter, not a measurement. A leaf row of a few hundred + entries is narrower than a memory page, so the in-place fill still writes + nearly every page of the array, and the saving for this shape is mostly the + library's second copy. - ``near-discrete``: a base-stage near-discrete target. 32 trees and five distinct values dominated by zero, so ``_fit_forest`` applies its 4,096-entry cap. The production pool has up to 207,692 rows; the default here is 10,000. About 80% of rows are zero in a region the trees isolate in one leaf; from about 5,100 rows that leaf holds more than 4,096 draws, so the library's shuffle and truncation run. The width is 4,096 at any size. + The trees grow about 0.1 nodes per donor row; the build's near-discrete + trees' density is not recorded. Each 32 KiB leaf row spans several pages, + so most pages are never written, and the in-place fill saves most of the + array as well as the second copy. The defaults finish in under a minute on a laptop and need a few GB. Memory grows roughly in proportion to rows times width (the cap, for @@ -62,7 +74,8 @@ uv run python tools/measure_qrf_leaf_memory.py --shape wage --rows 5000 --json Set ``POPULACE_FIT_N_JOBS`` to fix quantile-forest's thread count, as for a -build; the report records the setting and the thread count it gave. +build; the report records the setting and how many trees it could grow at +once (the thread count, at most the number of trees). The script also hashes each leaf array after the fit and reports whether the two arrays have the same shape, dtype and bytes. Hashing happens after the @@ -72,7 +85,9 @@ If one measurement fails, for example because the operating system stopped the library run for using too much memory, the other still runs, the report -shows what completed, and the exit code is 1. +shows what completed, and the exit code is 1. The exit code is also 1 when +the two leaf arrays differ, since the memory comparison then compares +different arrays. """ from __future__ import annotations @@ -344,7 +359,7 @@ def _fit_in_this_process(arguments: argparse.Namespace) -> dict[str, object]: ), "seed": arguments.seed, "n_jobs": model.n_jobs, - "threads": joblib.effective_n_jobs(model.n_jobs), + "trees_at_once": min(joblib.effective_n_jobs(model.n_jobs), arguments.trees), "max_samples_leaf": model.max_samples_leaf, "leaf_array_shape": list(leaves.shape), "leaf_array_dtype": str(leaves.dtype), @@ -373,36 +388,67 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s str(arguments.rows), "--trees", str(arguments.trees), - "--rows-in-widest-leaf", - str(arguments.rows_in_widest_leaf), "--seed", str(arguments.seed), ] + if arguments.shape == "wage": + command += ["--rows-in-widest-leaf", str(arguments.rows_in_widest_leaf)] if arguments.no_digest: command.append("--no-digest") return command -def _run_child(arguments: argparse.Namespace, implementation: str) -> dict | str: - """Run one measurement; return its result, or why it failed.""" +def _signal_name(number: int) -> str: + try: + return signal.Signals(number).name + except ValueError: + return f"signal {number}" + + +def _run_child( + arguments: argparse.Namespace, implementation: str +) -> tuple[dict[str, object] | None, dict[str, object] | None]: + """Run one measurement; return its result, or a description of its failure.""" completed = subprocess.run( _child_command(arguments, implementation), stdout=subprocess.PIPE, text=True, check=False, ) + failure: dict[str, object] = { + "implementation": implementation, + "exit_code": completed.returncode, + "signal": None, + } if completed.returncode < 0: - stopped_by = signal.Signals(-completed.returncode).name - return ( - f"the {implementation} measurement was stopped by {stopped_by}; an " - "out-of-memory stop by the operating system looks like this" + stopped_by = _signal_name(-completed.returncode) + failure["signal"] = stopped_by + failure["message"] = ( + f"the {implementation} measurement was stopped by {stopped_by}" + + ( + "; the operating system stops a process this way when memory runs out" + if -completed.returncode == signal.SIGKILL + else "" + ) ) + return None, failure if completed.returncode != 0: - return ( + failure["message"] = ( f"the {implementation} measurement failed with exit code " - f"{completed.returncode}; its error is printed above" + f"{completed.returncode}; its error is on standard error" ) - return json.loads(completed.stdout.strip().splitlines()[-1]) + return None, failure + lines = completed.stdout.strip().splitlines() + try: + result = json.loads(lines[-1]) + except (IndexError, json.JSONDecodeError): + result = None + if not isinstance(result, dict): + failure["message"] = ( + f"the {implementation} measurement exited without printing a result" + ) + return None, failure + return result, None def _identical(results: list[dict[str, object]]) -> bool | None: @@ -434,10 +480,18 @@ def _array_description(result: dict[str, object]) -> str: ) +def _measure_label(result: dict[str, object]) -> str: + if result["memory_measure"] == "physical_footprint": + return "peak physical footprint" + return "peak resident set" + + def _report( - results: list[dict[str, object]], failures: list[str], identical: bool | None + results: list[dict[str, object]], + failures: list[dict[str, object]], + identical: bool | None, ) -> str: - lines = list(failures) + lines = [str(failure["message"]) for failure in failures] if not results: return "\n".join(lines) first = results[0] @@ -449,8 +503,9 @@ def _report( f"{environment['numpy_requests_huge_pages']}", f"shape {first['shape']}: {_plural(int(first['rows']), 'donor row')}, " f"{_plural(int(first['trees']), 'tree')}, max_samples_leaf=" - f"{first['max_samples_leaf']}, n_jobs={first['n_jobs']} " - f"({_plural(int(first['threads']), 'thread')}), seed {first['seed']}" + f"{first['max_samples_leaf']}, n_jobs={first['n_jobs']} (up to " + f"{_plural(int(first['trees_at_once']), 'tree')} grown at once), seed " + f"{first['seed']}" + ( f", {_plural(int(first['rows_in_widest_leaf']), 'row')} sharing one " "predictor vector" @@ -461,11 +516,6 @@ def _report( descriptions = {_array_description(result) for result in results} if len(descriptions) == 1: lines.append("leaf array: " + _array_description(first)) - measure = ( - "peak physical footprint" - if first["memory_measure"] == "physical_footprint" - else "peak resident set" - ) for result in results: if len(descriptions) > 1: lines.append( @@ -484,13 +534,15 @@ def _report( + ")" ) lines.append( - f"{result['implementation']} ({result['class']}): {measure} " + f"{result['implementation']} ({result['class']}): {_measure_label(result)} " f"{_size(int(result['peak_bytes_after_fit']))}, of which the fit " f"added {_size(int(result['fit_peak_growth_bytes']))}{resident}; fit " f"took {result['fit_seconds']:.1f} s" ) if identical is not None: lines.append("leaf arrays byte-identical: " + ("yes" if identical else "NO")) + elif len(results) == 2: + lines.append("leaf arrays not compared (--no-digest)") return "\n".join(lines) @@ -498,7 +550,9 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) - parser.add_argument("--shape", choices=SHAPES, default="wage") + parser.add_argument( + "--shape", choices=SHAPES, default="wage", help="synthetic shape (default wage)" + ) parser.add_argument( "--rows", type=int, help="donor rows (default 10,000 for either shape)" ) @@ -510,9 +564,16 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: type=int, help="wage shape only: donor rows that share one predictor vector " f"(default {DEFAULT_ROWS_IN_WIDEST_LEAF}, or half of --rows if that is " - "smaller); their draws make the widest leaf, whose width the report shows", + "smaller); from about 30 rows their draws make the widest leaf, whose " + "width the report shows", + ) + parser.add_argument( + "--seed", + type=int, + default=20261117, + help=f"seed for the donors and the forest, 0 to {SEED_LIMIT - 1:,} " + "(default 20261117)", ) - parser.add_argument("--seed", type=int, default=20261117) parser.add_argument( "--implementation", choices=(*IMPLEMENTATIONS, "both"), @@ -529,6 +590,8 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: arguments.rows = DEFAULT_ROWS[arguments.shape] if arguments.trees is None: arguments.trees = DEFAULT_TREES[arguments.shape] + if arguments.shape != "wage" and arguments.rows_in_widest_leaf is not None: + parser.error("--rows-in-widest-leaf applies only to --shape wage") if arguments.rows_in_widest_leaf is None: arguments.rows_in_widest_leaf = max( 1, min(DEFAULT_ROWS_IN_WIDEST_LEAF, arguments.rows // 2) @@ -573,18 +636,31 @@ def main(argv: list[str] | None = None) -> int: else (arguments.implementation,) ) results: list[dict[str, object]] = [] - failures: list[str] = [] + failures: list[dict[str, object]] = [] for implementation in implementations: - outcome = _run_child(arguments, implementation) - if isinstance(outcome, str): - failures.append(outcome) + result, failure = _run_child(arguments, implementation) + if failure is not None: + failures.append(failure) else: - results.append(outcome) + results.append(result) identical = _identical(results) if arguments.json: print( json.dumps( { + "arguments": { + "shape": arguments.shape, + "rows": arguments.rows, + "trees": arguments.trees, + "rows_in_widest_leaf": ( + arguments.rows_in_widest_leaf + if arguments.shape == "wage" + else None + ), + "seed": arguments.seed, + "implementations": list(implementations), + "digest": not arguments.no_digest, + }, "results": results, "failures": failures, "leaf_arrays_identical": identical, @@ -594,7 +670,7 @@ def main(argv: list[str] | None = None) -> int: ) else: print(_report(results, failures, identical)) - return 1 if failures else 0 + return 1 if failures or identical is False else 0 if __name__ == "__main__": From e4e940a4682c07f69c8dd36adf6b5d6e35f4e538 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:25:45 +0400 Subject: [PATCH 06/15] Address round-four review: real scikit-learn 1.9, page residency, honest filter wording Round four found no input where the subclass's leaf array, random state, attributes, predictions or exceptions differ from the library's (620 random cases, 120 of them under scikit-learn 1.9.1). It found: - The simulated scikit-learn 1.9 test dropped the weights before calling the real helpers, so it failed under a real 1.9, and it compared only the weights' sum. Its wrappers now pass the weights on when the installed scikit-learn takes them, and it checks that both classes hand the helpers the fit's own sample_weight_ array, once per count and once per tree. - quantile-forest 1.4.2's weight filter looks up each entry's weight by the draw's position minus one, not by the drawn row. The copy keeps that exactly; the comment and the test's name and docstring now say so instead of describing a positive-weight filter. - New tests: a fit leaves warnings.filters as it found them; weighted fits the library refuses (several outputs, one row) raise the same IndexError; and in a fresh process, mincore shows that about a quarter of a capped forest's 71 MiB array is in memory after the fit, against all of it for the library's copy (the test requires under 0.6, and skips where huge pages are always on or mincore is unavailable). - The class docstring notes that a failed whole-forest allocation leaves Python's random state where it was, unlike the library's. tools/measure_qrf_leaf_memory.py: the child marks its result line and the parent checks the result's fields, so other output cannot be mistaken for or hide it; a one-valued target gets its own message; failures in --json give the exit code, the signal number and its name (or null). Re-pinned the US F0 spec pins (repin, coverage 41/41, repin, --check clean) and the fit.qrf parity pins; direct.csv is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 10 +- .../engine_free/shared/test_qrf_leaf_array.py | 167 +++++++++++++++--- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 62 +++++-- 8 files changed, 214 insertions(+), 51 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 19147039d0..602112e3c8 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", - "protocol_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004" + "map_sha256": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", + "protocol_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85" }, "failures": [], "observed": { - "map_sha256": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", - "protocol_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004" + "map_sha256": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", + "protocol_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", + "implementation_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", + "implementation_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629" + "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629" + "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 34c09c89c3..5af3b175dd 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "9fd9c3abac2069d3581710dbb2602978ecaaba70a6e02b66b8c3fad69d495d9d", - "seed_protocol": "8e7b70d0b89f9041d31700b31c75ef486024d815e4cc37cf7743fd52f5049004", + "seed_map": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", + "seed_protocol": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 67e0c2729f..ec3dedb1fa 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "dbd6b7ca962cf0d4e36032adaad61ed0614fc50fca20d56b00e69d17aaa47e71" + "875b92355d4d4728e72fdc2dd5091f6ebb0273bdd46c41d5f7a3ac8ee2de9583" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 87ba7008b9..ca8903e59b 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "66e952d42651b136284770b1475df1a929fc11b4eb767fcb71873802d1546629", + "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index e8e8fa1b23..02870bbf7f 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1220,8 +1220,9 @@ def _fill_tree_leaves( for leaf in range(len(leaf_values_list)): if sample_weight is not None: - # quantile-forest 1.4.2 drops entries whose weight is not - # positive this way. + # quantile-forest 1.4.2's filter, copied as it is: it looks + # up each entry's weight by the draw's position minus one, not + # by the drawn row. weight_mask = sample_weight[leaf_values_list[leaf] - 1] > 0 leaf_values_list[leaf] = leaf_values_list[leaf][weight_mask] if leaf_subsample: @@ -1275,7 +1276,10 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): messages name this class instead of ``RandomForestQuantileRegressor``. A ``max_samples_leaf`` so large that the whole forest's array exceeds the largest size numpy can describe raises numpy's ``ValueError`` here, where - the library, allocating one tree at a time, raises ``MemoryError``. + the library, allocating one tree at a time, raises ``MemoryError``. When + the one allocation fails, it fails before any tree's ``random`` calls, + so Python's ``random`` state differs from the library's after that + failed fit. The saving lasts while pages stay untouched. Pages of an ``np.zeros`` array take no memory until something touches them. A write makes a page diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index fe82507ca8..11dffecac7 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -20,15 +20,20 @@ import importlib.metadata import inspect import math +import os import pickle import random +import subprocess +import sys import tomllib import warnings +from pathlib import Path import numpy as np import pandas as pd import pytest import quantile_forest +import sklearn from quantile_forest import RandomForestQuantileRegressor from quantile_forest import _quantile_forest as quantile_forest_module from sklearn.base import clone @@ -286,10 +291,15 @@ def recording_map(**arguments): @pytest.mark.parametrize("max_samples_leaf", [None, 5]) -def test_weight_filter_drops_every_weight_that_is_not_positive( +def test_weight_filter_matches_the_library_for_tiny_zero_and_negative_weights( max_samples_leaf, ) -> None: - """Small positive weights stay; zero and negative weights go, as in 1.4.2.""" + """quantile-forest 1.4.2's weight filter is copied as it is. + + It looks up each entry's weight by the draw's position minus one, not by + the drawn row, so it keeps or drops entries by another row's weight. Tiny, + zero and negative weights all reach the comparison it makes. + """ predictors, target = _continuous_donors(seed=18, rows=600) generator = np.random.default_rng(18) weights = generator.choice([-1.0, 0.0, 1e-3, 0.04, 0.5, 2.0, 3.0], len(target)) @@ -404,29 +414,38 @@ def test_dataframe_predictors_give_the_library_warnings_and_array() -> None: def test_scikit_learn_1_9_bootstrap_arguments_match_the_library(monkeypatch) -> None: - """Under scikit-learn 1.9 both classes pass the helpers the same weights. - - scikit-learn 1.9 adds a ``sample_weight`` argument to its private - bootstrap helpers, and quantile-forest 1.4.2 passes ``sample_weight_`` - when it finds 1.9 or later. The installed scikit-learn is older, so the - test reports 1.9 and wraps the helpers to record that argument and drop it. + """Under scikit-learn 1.9 both classes pass the helpers ``sample_weight_``. + + scikit-learn 1.9 adds a required ``sample_weight`` argument to its private + bootstrap helpers, and quantile-forest 1.4.2 passes the fit's + ``sample_weight_`` when it finds 1.9 or later. The test reports 1.9 and + wraps the helpers to record whether they received that exact array. Under + an older scikit-learn the wrappers then drop it before calling the + installed helpers; under 1.9 or later they pass it on. """ - recorded: list[tuple[str, object]] = [] + recorded: list[tuple[str, bool]] = [] original_count = quantile_forest_module._get_n_samples_bootstrap original_indices = quantile_forest_module._generate_sample_indices + installed_takes_weights = parse_version(sklearn.__version__) >= parse_version( + "1.9.0" + ) + predictors, target = _continuous_donors(seed=22, rows=300) + weights = np.random.default_rng(22).uniform(0.5, 2.0, len(target)) def count_with_weights(n_samples, max_samples, sample_weight): - recorded.append( - ("count", None if sample_weight is None else sample_weight.sum()) - ) + recorded.append(("count", sample_weight is weights)) + if installed_takes_weights: + return original_count(n_samples, max_samples, sample_weight) return original_count(n_samples, max_samples) def indices_with_weights( random_state, n_samples, n_samples_bootstrap, sample_weight ): - recorded.append( - ("indices", None if sample_weight is None else sample_weight.sum()) - ) + recorded.append(("indices", sample_weight is weights)) + if installed_takes_weights: + return original_indices( + random_state, n_samples, n_samples_bootstrap, sample_weight + ) return original_indices(random_state, n_samples, n_samples_bootstrap) monkeypatch.setattr( @@ -438,14 +457,118 @@ def indices_with_weights( monkeypatch.setattr( quantile_forest_module, "_generate_sample_indices", indices_with_weights ) - predictors, target = _continuous_donors(seed=22, rows=300) - weights = np.random.default_rng(22).uniform(0.5, 2.0, len(target)) _assert_same_fit(predictors, target, sample_weight=weights, max_samples_leaf=None) - # One count and one index call per tree (six trees), for each class. - half = len(recorded) // 2 - assert half == 7 - assert recorded[:half] == recorded[half:] - assert all(weight_sum == pytest.approx(weights.sum()) for _, weight_sum in recorded) + # One count call, then one index call per tree (six trees), for each class. + expected = [("count", True)] + [("indices", True)] * 6 + assert recorded == expected + expected + + +def test_fit_leaves_the_warning_filters_as_they_were() -> None: + """The copy silences ``apply``'s warning only inside ``catch_warnings``.""" + predictors, target = _continuous_donors(seed=24, rows=150) + before = list(warnings.filters) + qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=5).fit( + predictors, target + ) + assert warnings.filters == before + + +def _fit_outcome(model_class, predictors, target, weights) -> tuple[object, object]: + """Fit and return the leaf array's bytes, or the exception it raised.""" + model = model_class(n_estimators=3, max_samples_leaf=None, random_state=0) + try: + model.fit(predictors, target, sample_weight=weights) + except Exception as error: # the exception itself is the outcome compared + return type(error), str(error).replace(model_class.__name__, "") + return "fitted", np.asarray(model.forest_.y_train_leaves).tobytes() + + +@pytest.mark.parametrize("case", ["several-outputs", "one-row"]) +def test_weighted_fits_the_library_refuses_are_refused_alike(case) -> None: + """quantile-forest 1.4.2 fails on these weighted fits; so does the copy.""" + predictors, first = _continuous_donors(seed=25, rows=200) + if case == "several-outputs": + target = np.column_stack([first, first * 2.0]) + else: + predictors, target = predictors[:1], first[:1] + weights = np.linspace(0.5, 2.0, len(predictors)) + library = _fit_outcome(RandomForestQuantileRegressor, predictors, target, weights) + in_place = _fit_outcome(qrf._InPlaceLeafQRF, predictors, target, weights) + assert library[0] is IndexError + assert in_place == library + + +#: Run in a fresh Python process, so the forest's array gets pages no earlier +#: allocation in the test session has written. A large allocation can reuse +#: memory freed earlier in the process, which ``calloc`` then zeroes, writing +#: every page. Prints the share of the array's pages that are mapped, or +#: "unavailable" when ``mincore`` cannot be called. +_RESIDENT_SHARE_CHILD = """ +import ctypes +import ctypes.util +import os + +import numpy as np +from numpy._core import multiarray + +from microcosm.fit import qrf + +# A transparent huge page makes 2 MiB resident at the first write. +multiarray._set_madvise_hugepage(False) +generator = np.random.default_rng(26) +predictors = generator.integers(0, 12, size=(3000, 2)).astype(np.float64) +target = generator.choice([0.0, 0.25, 0.5, 1.0], size=3000, p=[0.85, 0.05, 0.05, 0.05]) +model = qrf._InPlaceLeafQRF( + n_estimators=8, max_samples_leaf=4096, random_state=3, n_jobs=1 +) +model.fit(predictors, target) +leaves = np.asarray(model.forest_.y_train_leaves) +assert leaves.nbytes > 40 * 2**20, leaves.nbytes +library_path = ctypes.util.find_library("c") +if library_path is None: + print("unavailable") + raise SystemExit(0) +libc = ctypes.CDLL(library_path, use_errno=True) +libc.mincore.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] +libc.mincore.restype = ctypes.c_int +page = os.sysconf("SC_PAGE_SIZE") +start = leaves.ctypes.data +aligned = start - start % page +length = start + leaves.nbytes - aligned +pages = -(-length // page) +status = (ctypes.c_ubyte * pages)() +if libc.mincore(aligned, length, status) != 0: + print("unavailable") + raise SystemExit(0) +print(float(np.mean(np.frombuffer(status, dtype=np.uint8) & 1))) +""" + + +def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: + """Most pages of a capped forest's padded array are never touched. + + Each node's row is 4,096 entries (32 KiB) wide, and a leaf's few entries + sit at the start of its row, so rows of internal nodes and most of each + leaf row are never written, and ``mincore`` reports those pages as not in + memory. The library's ``np.array(list)`` copy writes them all (a share of + 1.0). The array, over 40 MiB, is larger than glibc's largest mmap + threshold, so it gets fresh pages; numpy's request for transparent huge + pages is turned off in the child. + """ + huge_page_setting = Path("/sys/kernel/mm/transparent_hugepage/enabled") + if huge_page_setting.exists() and "[always]" in huge_page_setting.read_text(): + pytest.skip("transparent huge pages are always on") + completed = subprocess.run( + [sys.executable, "-c", _RESIDENT_SHARE_CHILD], + capture_output=True, + text=True, + check=True, + env={**os.environ, "OMP_NUM_THREADS": "1"}, + ) + reading = completed.stdout.strip().splitlines()[-1] + if reading == "unavailable": + pytest.skip("mincore is unavailable") + assert float(reading) < 0.6 def test_sparse_pickle_reaches_the_library() -> None: diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 452eac4e42..481e1a100f 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"a5de61571ec6e3cce429cd3038545b771580e447c908952b760314645fa20cb7","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"05f2e733ccadfd9b8172e74f5ba8c530a3da70cfdc1a1f35d5642358162b270b","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"05f2e733ccadfd9b8172e74f5ba8c530a3da70cfdc1a1f35d5642358162b270b"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"c75496ab781ed7da968b1d710b0b02e68f6e6006beba60590f6835e553c1b280"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"c91c2082e858e3066d3f7493d6fcd907735abb0c058ddede9e557956883af485"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"74d2cc92994d7af3a4fdda11b0d35090a742ae6dfd8c1f0d633209b6ebb35e75","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"1284dc9145b55021042ea6511c3f2dc95e5c65200af476a2fe9cc2e2833b1922","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"1284dc9145b55021042ea6511c3f2dc95e5c65200af476a2fe9cc2e2833b1922"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"475481bd7536d7e22daaadc40fff668b6bb3c072aa0b5ed11b44ded15a401111"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"f915deebff829b754c2784b882451730945e3c131ff3706b93e68a52d13eb5d6"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 2d559f8a19..75d4ac9a14 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -87,7 +87,9 @@ the library run for using too much memory, the other still runs, the report shows what completed, and the exit code is 1. The exit code is also 1 when the two leaf arrays differ, since the memory comparison then compares -different arrays. +different arrays. In ``--json`` output each failure gives the child's exit +code (negative when a signal stopped it, as Python's ``subprocess`` reports +it), the signal's number and name, and a message. """ from __future__ import annotations @@ -119,6 +121,34 @@ DEFAULT_TREES = {"wage": 100, "near-discrete": 32} DEFAULT_ROWS = {"wage": 10_000, "near-discrete": 10_000} DEFAULT_ROWS_IN_WIDEST_LEAF = 250 +#: Fields the parent reads from every child result. +REQUIRED_RESULT_FIELDS = frozenset( + { + "implementation", + "class", + "leaf_array_shape", + "leaf_array_dtype", + "leaf_array_bytes", + "leaf_array_sha256", + "memory_measure", + "peak_bytes_after_fit", + "fit_peak_growth_bytes", + "peak_resident_set_bytes_before_fit", + "peak_resident_set_bytes_after_fit", + "fit_seconds", + "shape", + "rows", + "trees", + "rows_in_widest_leaf", + "seed", + "n_jobs", + "trees_at_once", + "max_samples_leaf", + "environment", + } +) +#: Marks the child's result line on standard output. +RESULT_PREFIX = "measure_qrf_leaf_memory result: " #: scikit-learn accepts integer seeds below 2**32. SEED_LIMIT = 2**32 _RUSAGE_INFO_V4 = 4 @@ -398,11 +428,11 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s return command -def _signal_name(number: int) -> str: +def _signal_name(number: int) -> str | None: try: return signal.Signals(number).name except ValueError: - return f"signal {number}" + return None def _run_child( @@ -418,11 +448,13 @@ def _run_child( failure: dict[str, object] = { "implementation": implementation, "exit_code": completed.returncode, + "signal_number": None, "signal": None, } if completed.returncode < 0: - stopped_by = _signal_name(-completed.returncode) - failure["signal"] = stopped_by + failure["signal_number"] = -completed.returncode + failure["signal"] = _signal_name(-completed.returncode) + stopped_by = failure["signal"] or f"signal {-completed.returncode}" failure["message"] = ( f"the {implementation} measurement was stopped by {stopped_by}" + ( @@ -438,12 +470,16 @@ def _run_child( f"{completed.returncode}; its error is on standard error" ) return None, failure - lines = completed.stdout.strip().splitlines() + marked = [ + line[len(RESULT_PREFIX) :] + for line in completed.stdout.splitlines() + if line.startswith(RESULT_PREFIX) + ] try: - result = json.loads(lines[-1]) + result = json.loads(marked[-1]) except (IndexError, json.JSONDecodeError): result = None - if not isinstance(result, dict): + if not isinstance(result, dict) or not REQUIRED_RESULT_FIELDS <= set(result): failure["message"] = ( f"the {implementation} measurement exited without printing a result" ) @@ -610,15 +646,15 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: from microcosm.fit.qrf import _DISCRETE_Y_UNIQUE_MAX distinct = len(np.unique(_donors(arguments)[1])) - if arguments.shape == "near-discrete" and distinct < 2: + if distinct < 2: parser.error( - f"with --rows {arguments.rows} the near-discrete target has " - f"{distinct} distinct value; raise --rows" + f"with --rows {arguments.rows} and --seed {arguments.seed} the " + f"{arguments.shape} target has one value; raise --rows" ) if arguments.shape == "wage" and distinct <= _DISCRETE_Y_UNIQUE_MAX: parser.error( f"with --rows {arguments.rows} the wage target has only {distinct} " - f"distinct values, so _fit_forest would cap its leaves as a " + "distinct values, so _fit_forest would cap its leaves as a " "near-discrete target; raise --rows" ) return arguments @@ -627,7 +663,7 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: def main(argv: list[str] | None = None) -> int: arguments = _parse_arguments(argv) if arguments.child is not None: - print(json.dumps(_fit_in_this_process(arguments))) + print(RESULT_PREFIX + json.dumps(_fit_in_this_process(arguments))) return 0 implementations = ( From 1dd856803a050710763ef776374b7ab41c34429a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:02 +0400 Subject: [PATCH 07/15] Address round-five review: portable tests, accurate failure notes Round five found no difference from quantile-forest 1.4.2 in the leaf array, random state, predictions or exceptions, and every mutant that changes behaviour is now caught. It found: - Under scikit-learn 1.9, sklearn's own tree growing refuses negative weights, so the weight-filter test drops them there; its docstring says so. The weight-filter docstrings no longer call it a zero-weight filter. - The class docstring's note on a failed allocation now says the random state can differ only when a leaf cap is set and the library gets past a tree before failing; the documented too-large case leaves both equal. - The page-residency test skips with pages over 16 KiB or any huge page size set to always, unsets glibc's MALLOC_PERTURB_ in its child, and shows the child's error output when it fails. - The warning-filter test reads the active filters through warnings._get_filters where it exists, so context-aware warnings (free-threaded builds) cannot hide a leaked filter. - The memory script tells apart no result, a result that is not a JSON object, and one that lacks fields or has a null where a value is required; the wage distinct-value message names --seed. Re-pinned the US F0 spec pins (repin, coverage 41/41, repin, --check clean) and the fit.qrf parity pins; direct.csv is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 +++--- .../build/spec_engine/inventory_coverage.py | 4 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 9 +-- .../engine_free/shared/test_qrf_leaf_array.py | 56 ++++++++++++++----- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/measure_qrf_leaf_memory.py | 34 +++++++++-- 8 files changed, 87 insertions(+), 38 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 602112e3c8..fd18ffd8e1 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", - "protocol_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85" + "map_sha256": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", + "protocol_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df" }, "failures": [], "observed": { - "map_sha256": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", - "protocol_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85" + "map_sha256": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", + "protocol_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", + "implementation_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", + "implementation_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff" + "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff" + "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 5af3b175dd..ba8da40648 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "73c55f420e6064a8a1f566fa383006a308e3d9524832dfaec1d659a5461a1711", - "seed_protocol": "784843de3e2695149f018e1c3d07cab0e9ba7c98693b21a6d485e7c265964d85", + "seed_map": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", + "seed_protocol": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index ec3dedb1fa..a274506f50 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "875b92355d4d4728e72fdc2dd5091f6ebb0273bdd46c41d5f7a3ac8ee2de9583" + "5778dd8521f888a09afcc092c463de5ae7dc46296eaac2ab88ffde48806a872a" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index ca8903e59b..fbf6aa88ab 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "866831db8ca3c4acba1492836440da24702be4326c13c9d26eaf78db5e8e1fff", + "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 02870bbf7f..530bd74a08 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1276,10 +1276,11 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): messages name this class instead of ``RandomForestQuantileRegressor``. A ``max_samples_leaf`` so large that the whole forest's array exceeds the largest size numpy can describe raises numpy's ``ValueError`` here, where - the library, allocating one tree at a time, raises ``MemoryError``. When - the one allocation fails, it fails before any tree's ``random`` calls, - so Python's ``random`` state differs from the library's after that - failed fit. + the library, allocating one tree at a time, raises ``MemoryError``. A + failed allocation here comes before any tree's ``random`` calls. So with a + leaf cap set, if the library gets past at least one tree before its own + allocation or its final copy fails, Python's ``random`` state can differ + from the library's after that failed fit. The saving lasts while pages stay untouched. Pages of an ``np.zeros`` array take no memory until something touches them. A write makes a page diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index 11dffecac7..6df882d55d 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -82,7 +82,7 @@ def _near_discrete_donors( def _sample_weights(seed: int, rows: int) -> np.ndarray: """Positive weights with a fifth of the rows at exactly zero. - The library's zero-weight filter runs on every leaf. With a fifth of the + The library's weight filter runs on every leaf. With a fifth of the weights at zero no leaf empties; ``test_weighted_leaves_that_empty_get_the_library_placeholder`` covers that. """ @@ -250,9 +250,10 @@ def test_weighted_samples_match_the_library(max_samples_leaf) -> None: def test_weighted_leaves_that_empty_get_the_library_placeholder( monkeypatch, max_samples_leaf ) -> None: - """A leaf whose entries the zero-weight filter removes holds ``[0]``. + """A leaf whose entries the weight filter removes holds ``[0]``. - Nine in ten weights are zero, so some leaves empty. Both classes hand the + Nine in ten weights are zero, so the filter, which reads another row's + weight for each entry, empties some leaves. Both classes hand the filtered leaves to quantile-forest's compiled helper, which records how many hold the placeholder. With a cap of one entry the helper is not used, and only the arrays are compared. @@ -297,12 +298,16 @@ def test_weight_filter_matches_the_library_for_tiny_zero_and_negative_weights( """quantile-forest 1.4.2's weight filter is copied as it is. It looks up each entry's weight by the draw's position minus one, not by - the drawn row, so it keeps or drops entries by another row's weight. Tiny, - zero and negative weights all reach the comparison it makes. + the drawn row, so it keeps or drops entries by another row's weight. Tiny + and zero weights reach the comparison it makes, and so do negative ones + before scikit-learn 1.9, which refuses them while growing the trees. """ predictors, target = _continuous_donors(seed=18, rows=600) generator = np.random.default_rng(18) - weights = generator.choice([-1.0, 0.0, 1e-3, 0.04, 0.5, 2.0, 3.0], len(target)) + levels = [-1.0, 0.0, 1e-3, 0.04, 0.5, 2.0, 3.0] + if parse_version(sklearn.__version__) >= parse_version("1.9.0"): + levels.remove(-1.0) + weights = generator.choice(levels, len(target)) _assert_same_fit( predictors, target, @@ -464,13 +469,18 @@ def indices_with_weights( def test_fit_leaves_the_warning_filters_as_they_were() -> None: - """The copy silences ``apply``'s warning only inside ``catch_warnings``.""" + """The copy silences ``apply``'s warning only inside ``catch_warnings``. + + With context-aware warnings (the default on free-threaded builds) the + active filters live in a context variable, which ``_get_filters`` reads. + """ + active_filters = getattr(warnings, "_get_filters", lambda: warnings.filters) predictors, target = _continuous_donors(seed=24, rows=150) - before = list(warnings.filters) + before = list(active_filters()) qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=5).fit( predictors, target ) - assert warnings.filters == before + assert list(active_filters()) == before def _fit_outcome(model_class, predictors, target, weights) -> tuple[object, object]: @@ -553,18 +563,34 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: memory. The library's ``np.array(list)`` copy writes them all (a share of 1.0). The array, over 40 MiB, is larger than glibc's largest mmap threshold, so it gets fresh pages; numpy's request for transparent huge - pages is turned off in the child. + pages is turned off in the child, and glibc's ``MALLOC_PERTURB_``, which + fills allocations, is unset. About a quarter of the pages hold entries + with 16 KiB pages and a sixteenth with 4 KiB pages. With pages over + 16 KiB, or huge pages always on at any size, most pages hold an entry, + so the test skips. """ - huge_page_setting = Path("/sys/kernel/mm/transparent_hugepage/enabled") - if huge_page_setting.exists() and "[always]" in huge_page_setting.read_text(): - pytest.skip("transparent huge pages are always on") + if os.sysconf("SC_PAGE_SIZE") > 16 * 2**10: + pytest.skip("memory pages are larger than 16 KiB") + huge_page_settings = Path("/sys/kernel/mm/transparent_hugepage") + for setting in [ + huge_page_settings / "enabled", + *huge_page_settings.glob("hugepages-*/enabled"), + ]: + if setting.exists() and "[always]" in setting.read_text(): + pytest.skip(f"transparent huge pages are always on ({setting})") + environment = { + name: value + for name, value in os.environ.items() + if name not in {"MALLOC_PERTURB_", "MALLOC_PERTURB"} + } completed = subprocess.run( [sys.executable, "-c", _RESIDENT_SHARE_CHILD], capture_output=True, text=True, - check=True, - env={**os.environ, "OMP_NUM_THREADS": "1"}, + check=False, + env={**environment, "OMP_NUM_THREADS": "1"}, ) + assert completed.returncode == 0, completed.stderr reading = completed.stdout.strip().splitlines()[-1] if reading == "unavailable": pytest.skip("mincore is unavailable") diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 481e1a100f..6e6df2b63a 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"74d2cc92994d7af3a4fdda11b0d35090a742ae6dfd8c1f0d633209b6ebb35e75","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"1284dc9145b55021042ea6511c3f2dc95e5c65200af476a2fe9cc2e2833b1922","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"1284dc9145b55021042ea6511c3f2dc95e5c65200af476a2fe9cc2e2833b1922"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"475481bd7536d7e22daaadc40fff668b6bb3c072aa0b5ed11b44ded15a401111"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"f915deebff829b754c2784b882451730945e3c131ff3706b93e68a52d13eb5d6"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"e1883411a845b1b1ec8c24eeb72eacd3201f102aae6a74a938f6f08d5d173db6","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"71a555e7669691d7b1105d891fbff136828f68314fbd140af1c8c00285f69a99","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"71a555e7669691d7b1105d891fbff136828f68314fbd140af1c8c00285f69a99"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"67ed441109b4d6e4d08d8d8f04812f21ef7b764f026ce3c817f5d2c698437643"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"e9e36be7d74a0247da2add7ea08bb8e13aff412d09e9beb39419372ce04f24f4"}},"seed":947} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 75d4ac9a14..a4ed292c29 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -147,6 +147,11 @@ "environment", } ) +#: Required fields that may hold null: no digest under --no-digest, no row +#: count for the near-discrete shape, and no cap for an uncapped forest. +NULLABLE_RESULT_FIELDS = frozenset( + {"leaf_array_sha256", "rows_in_widest_leaf", "max_samples_leaf"} +) #: Marks the child's result line on standard output. RESULT_PREFIX = "measure_qrf_leaf_memory result: " #: scikit-learn accepts integer seeds below 2**32. @@ -475,13 +480,30 @@ def _run_child( for line in completed.stdout.splitlines() if line.startswith(RESULT_PREFIX) ] + if not marked: + failure["message"] = ( + f"the {implementation} measurement exited without printing a result" + ) + return None, failure try: result = json.loads(marked[-1]) - except (IndexError, json.JSONDecodeError): + except json.JSONDecodeError: result = None - if not isinstance(result, dict) or not REQUIRED_RESULT_FIELDS <= set(result): + if not isinstance(result, dict): failure["message"] = ( - f"the {implementation} measurement exited without printing a result" + f"the {implementation} measurement printed a result that is not a " + "JSON object" + ) + return None, failure + missing = sorted( + field + for field in REQUIRED_RESULT_FIELDS + if field not in result + or (result[field] is None and field not in NULLABLE_RESULT_FIELDS) + ) + if missing: + failure["message"] = ( + f"the {implementation} measurement's result lacks " + ", ".join(missing) ) return None, failure return result, None @@ -653,9 +675,9 @@ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace: ) if arguments.shape == "wage" and distinct <= _DISCRETE_Y_UNIQUE_MAX: parser.error( - f"with --rows {arguments.rows} the wage target has only {distinct} " - "distinct values, so _fit_forest would cap its leaves as a " - "near-discrete target; raise --rows" + f"with --rows {arguments.rows} and --seed {arguments.seed} the wage " + f"target has only {distinct} distinct values, so _fit_forest would " + "cap its leaves as a near-discrete target; raise --rows" ) return arguments From 527bc7d0f669cceb3db43453ba88e94a3d6e55cf Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:47:20 +0400 Subject: [PATCH 08/15] Address round-six review: negative weights under scikit-learn 1.9, stricter result checks Round six found nothing that changes what _InPlaceLeafQRF computes. It found: - From scikit-learn 1.9 the forest's weighted bootstrap draw (not tree growing) refuses negative weights. The weight-filter test now runs with bootstrapping on and off; negative weights are left out only with it on under 1.9, so on every version they reach the copied filter. - A numpy integer leaf cap (np.int64(16)) is now tested; it must count as an integer, as in the library. - The page-residency test also unsets GLIBC_TUNABLES in its child and skips where os.sysconf is missing. - tools/measure_qrf_leaf_memory.py: which result fields may be null now depends on the run (the digest only under --no-digest, the cap only for the uncapped wage forest), and numeric fields, the array shape and the environment record are type-checked, so a malformed result is reported as unusable with the reason instead of being accepted or crashing. qrf.py is unchanged, so no pin moves. The tests pass under scikit-learn 1.8.0 (49 cases), and the changed ones under 1.9.1. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_qrf_leaf_array.py | 32 ++++--- tools/measure_qrf_leaf_memory.py | 96 ++++++++++++++++--- 2 files changed, 104 insertions(+), 24 deletions(-) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index 6df882d55d..a251af6921 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -193,14 +193,14 @@ def test_continuous_target_without_a_cap_matches_the_library() -> None: assert leaves.shape[-1] > 1 -@pytest.mark.parametrize("cap", [16, 0.0047]) +@pytest.mark.parametrize("cap", [16, np.int64(16), 0.0047]) def test_near_discrete_target_over_the_cap_matches_the_library( monkeypatch, cap ) -> None: """Leaves larger than the cap are shuffled and truncated identically. The fractional cap is 0.0047 of 3,000 rows, 14.1, which the library rounds - up to 15. + up to 15. A numpy integer cap counts as an integer, as in the library. """ shuffle_calls: list[int] = [] original_shuffle = random.shuffle @@ -212,8 +212,9 @@ def counting_shuffle(sequence): monkeypatch.setattr(random, "shuffle", counting_shuffle) predictors, target = _near_discrete_donors(seed=2) leaves = _assert_same_fit(predictors, target, max_samples_leaf=cap) - width = cap if isinstance(cap, int) else math.ceil(cap * len(target)) - assert leaves.shape[-1] == width == (16 if isinstance(cap, int) else 15) + integer_cap = isinstance(cap, int | np.integer) + width = cap if integer_cap else math.ceil(cap * len(target)) + assert leaves.shape[-1] == width == (16 if integer_cap else 15) # Both fits shuffled the same leaves, each larger than the cap, before # truncating them; the library fit ran first. half = len(shuffle_calls) // 2 @@ -291,21 +292,24 @@ def recording_map(**arguments): assert sum(placeholders[half:]) > 0 +@pytest.mark.parametrize("bootstrap", [True, False]) @pytest.mark.parametrize("max_samples_leaf", [None, 5]) def test_weight_filter_matches_the_library_for_tiny_zero_and_negative_weights( - max_samples_leaf, + max_samples_leaf, bootstrap ) -> None: """quantile-forest 1.4.2's weight filter is copied as it is. It looks up each entry's weight by the draw's position minus one, not by - the drawn row, so it keeps or drops entries by another row's weight. Tiny - and zero weights reach the comparison it makes, and so do negative ones - before scikit-learn 1.9, which refuses them while growing the trees. + the drawn row, so it keeps or drops entries by another row's weight. Tiny, + zero and negative weights all reach the comparison it makes. From + scikit-learn 1.9 the forest's weighted bootstrap draw refuses negative + weights, so with bootstrapping on they are left out there; with it off + they reach the filter on every version. """ predictors, target = _continuous_donors(seed=18, rows=600) generator = np.random.default_rng(18) levels = [-1.0, 0.0, 1e-3, 0.04, 0.5, 2.0, 3.0] - if parse_version(sklearn.__version__) >= parse_version("1.9.0"): + if bootstrap and parse_version(sklearn.__version__) >= parse_version("1.9.0"): levels.remove(-1.0) weights = generator.choice(levels, len(target)) _assert_same_fit( @@ -313,6 +317,7 @@ def test_weight_filter_matches_the_library_for_tiny_zero_and_negative_weights( target, sample_weight=weights, max_samples_leaf=max_samples_leaf, + bootstrap=bootstrap, ) @@ -563,12 +568,15 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: memory. The library's ``np.array(list)`` copy writes them all (a share of 1.0). The array, over 40 MiB, is larger than glibc's largest mmap threshold, so it gets fresh pages; numpy's request for transparent huge - pages is turned off in the child, and glibc's ``MALLOC_PERTURB_``, which - fills allocations, is unset. About a quarter of the pages hold entries + pages is turned off in the child, and glibc's ``MALLOC_PERTURB_`` and + ``GLIBC_TUNABLES`` (which can fill allocations or request huge pages) are + unset. About a quarter of the pages hold entries with 16 KiB pages and a sixteenth with 4 KiB pages. With pages over 16 KiB, or huge pages always on at any size, most pages hold an entry, so the test skips. """ + if not hasattr(os, "sysconf"): + pytest.skip("os.sysconf is unavailable") if os.sysconf("SC_PAGE_SIZE") > 16 * 2**10: pytest.skip("memory pages are larger than 16 KiB") huge_page_settings = Path("/sys/kernel/mm/transparent_hugepage") @@ -581,7 +589,7 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: environment = { name: value for name, value in os.environ.items() - if name not in {"MALLOC_PERTURB_", "MALLOC_PERTURB"} + if name not in {"MALLOC_PERTURB_", "GLIBC_TUNABLES"} } completed = subprocess.run( [sys.executable, "-c", _RESIDENT_SHARE_CHILD], diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index a4ed292c29..cb1b028ce0 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -147,10 +147,31 @@ "environment", } ) -#: Required fields that may hold null: no digest under --no-digest, no row -#: count for the near-discrete shape, and no cap for an uncapped forest. -NULLABLE_RESULT_FIELDS = frozenset( - {"leaf_array_sha256", "rows_in_widest_leaf", "max_samples_leaf"} +#: Required result fields that hold a number. +NUMERIC_RESULT_FIELDS = frozenset( + { + "leaf_array_bytes", + "peak_bytes_after_fit", + "fit_peak_growth_bytes", + "peak_resident_set_bytes_before_fit", + "peak_resident_set_bytes_after_fit", + "fit_seconds", + "rows", + "trees", + "seed", + "n_jobs", + "trees_at_once", + } +) +#: Fields of a result's ``environment`` that the report reads. +REQUIRED_ENVIRONMENT_FIELDS = frozenset( + { + "platform", + "cpu_count", + "page_size_bytes", + "transparent_huge_pages", + "numpy_requests_huge_pages", + } ) #: Marks the child's result line on standard output. RESULT_PREFIX = "measure_qrf_leaf_memory result: " @@ -433,6 +454,61 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s return command +def _nullable_fields(arguments: argparse.Namespace) -> set[str]: + """Return the result fields that may be null for this run's options.""" + nullable = set() + if arguments.no_digest: + nullable.add("leaf_array_sha256") + if arguments.shape == "wage": + nullable.add("max_samples_leaf") # the wage forest has no cap + else: + nullable.add("rows_in_widest_leaf") + return nullable + + +def _result_problems( + result: dict[str, object], arguments: argparse.Namespace +) -> list[str]: + """Describe what makes a child's result unusable; empty if nothing does.""" + nullable = _nullable_fields(arguments) + problems = [] + missing = sorted(REQUIRED_RESULT_FIELDS - set(result)) + if missing: + problems.append("missing " + ", ".join(missing)) + null = sorted( + field + for field in REQUIRED_RESULT_FIELDS & set(result) + if result[field] is None and field not in nullable + ) + if null: + problems.append("null " + ", ".join(null)) + not_numbers = sorted( + field + for field in NUMERIC_RESULT_FIELDS & set(result) + if result[field] is not None + and ( + isinstance(result[field], bool) + or not isinstance(result[field], int | float) + ) + ) + if not_numbers: + problems.append("not a number: " + ", ".join(not_numbers)) + shape = result.get("leaf_array_shape") + if "leaf_array_shape" in result and not ( + isinstance(shape, list) and all(isinstance(size, int) for size in shape) + ): + problems.append("leaf_array_shape is not a list of integers") + environment = result.get("environment") + if "environment" in result: + if not isinstance(environment, dict): + problems.append("environment is not an object") + else: + lacking = sorted(REQUIRED_ENVIRONMENT_FIELDS - set(environment)) + if lacking: + problems.append("environment missing " + ", ".join(lacking)) + return problems + + def _signal_name(number: int) -> str | None: try: return signal.Signals(number).name @@ -495,15 +571,11 @@ def _run_child( "JSON object" ) return None, failure - missing = sorted( - field - for field in REQUIRED_RESULT_FIELDS - if field not in result - or (result[field] is None and field not in NULLABLE_RESULT_FIELDS) - ) - if missing: + problems = _result_problems(result, arguments) + if problems: failure["message"] = ( - f"the {implementation} measurement's result lacks " + ", ".join(missing) + f"the {implementation} measurement's result is unusable: " + + "; ".join(problems) ) return None, failure return result, None From eff0781570a51583ef2bd9daf59b0e20da260c5a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:25:52 +0400 Subject: [PATCH 09/15] Address round-seven review: stricter measurement result checks Round seven found the test changes sound; every mutant that changes behaviour is caught under scikit-learn 1.8.0, including the numpy-integer cap and negative weights without bootstrapping. The remaining findings were in tools/measure_qrf_leaf_memory.py, for malformed child results that a real child never prints: - numbers must be finite and fit in 64 bits (NaN, infinity and huge integers were accepted and then crashed the report); - fields that must be null for the run's options are now required to be null, and the rest to hold a value (a wage result with a cap, or a near-discrete one with a widest-leaf count, was accepted); - rows_in_widest_leaf and max_samples_leaf are type-checked, as are the environment's platform, page size and CPU count, the digest's format, the array shape (four non-negative integers), the memory measure's name and the implementation name; - a null shape or environment is reported once. Tests: the cap parametrisation has named cases, and the residency test's child keeps GLIBC_TUNABLES entries other than glibc.malloc ones. qrf.py is unchanged, so no pin moves. 49 cases pass under scikit-learn 1.8.0. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_qrf_leaf_array.py | 29 ++++-- tools/measure_qrf_leaf_memory.py | 90 +++++++++++++------ 2 files changed, 86 insertions(+), 33 deletions(-) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index a251af6921..1de3ca5de0 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -193,7 +193,14 @@ def test_continuous_target_without_a_cap_matches_the_library() -> None: assert leaves.shape[-1] > 1 -@pytest.mark.parametrize("cap", [16, np.int64(16), 0.0047]) +@pytest.mark.parametrize( + "cap", + [ + pytest.param(16, id="integer"), + pytest.param(np.int64(16), id="numpy-integer"), + pytest.param(0.0047, id="fraction"), + ], +) def test_near_discrete_target_over_the_cap_matches_the_library( monkeypatch, cap ) -> None: @@ -568,12 +575,12 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: memory. The library's ``np.array(list)`` copy writes them all (a share of 1.0). The array, over 40 MiB, is larger than glibc's largest mmap threshold, so it gets fresh pages; numpy's request for transparent huge - pages is turned off in the child, and glibc's ``MALLOC_PERTURB_`` and - ``GLIBC_TUNABLES`` (which can fill allocations or request huge pages) are - unset. About a quarter of the pages hold entries - with 16 KiB pages and a sixteenth with 4 KiB pages. With pages over - 16 KiB, or huge pages always on at any size, most pages hold an entry, - so the test skips. + pages is turned off in the child, and glibc's ``MALLOC_PERTURB_`` and its + ``glibc.malloc`` tunables (which can fill allocations or request huge + pages) are removed from its environment. About a quarter of the pages + hold entries with 16 KiB pages and a sixteenth with 4 KiB pages. With + pages over 16 KiB, or huge pages always on at any size, most pages hold + an entry, so the test skips. """ if not hasattr(os, "sysconf"): pytest.skip("os.sysconf is unavailable") @@ -591,6 +598,14 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: for name, value in os.environ.items() if name not in {"MALLOC_PERTURB_", "GLIBC_TUNABLES"} } + # Keep unrelated tunables (some aarch64 setups need static TLS ones). + other_tunables = [ + tunable + for tunable in os.environ.get("GLIBC_TUNABLES", "").split(":") + if tunable and not tunable.startswith("glibc.malloc.") + ] + if other_tunables: + environment["GLIBC_TUNABLES"] = ":".join(other_tunables) completed = subprocess.run( [sys.executable, "-c", _RESIDENT_SHARE_CHILD], capture_output=True, diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index cb1b028ce0..e53682bda9 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -101,6 +101,7 @@ import hashlib import importlib.metadata import json +import math import os import platform import resource @@ -454,58 +455,95 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s return command -def _nullable_fields(arguments: argparse.Namespace) -> set[str]: - """Return the result fields that may be null for this run's options.""" - nullable = set() +def _null_fields(arguments: argparse.Namespace) -> set[str]: + """Return the result fields that must be null for this run's options. + + Every other required field must hold a value. + """ + null = set() if arguments.no_digest: - nullable.add("leaf_array_sha256") + null.add("leaf_array_sha256") if arguments.shape == "wage": - nullable.add("max_samples_leaf") # the wage forest has no cap + null.add("max_samples_leaf") # the wage forest has no cap else: - nullable.add("rows_in_widest_leaf") - return nullable + null.add("rows_in_widest_leaf") + return null + + +def _is_number(value: object) -> bool: + """Whether ``value`` is a finite int or float that fits in 64 bits.""" + if isinstance(value, bool) or not isinstance(value, int | float): + return False + if isinstance(value, float): + return math.isfinite(value) + return abs(value) < 2**63 def _result_problems( - result: dict[str, object], arguments: argparse.Namespace + result: dict[str, object], arguments: argparse.Namespace, implementation: str ) -> list[str]: """Describe what makes a child's result unusable; empty if nothing does.""" - nullable = _nullable_fields(arguments) + must_be_null = _null_fields(arguments) + present = REQUIRED_RESULT_FIELDS & set(result) problems = [] missing = sorted(REQUIRED_RESULT_FIELDS - set(result)) if missing: problems.append("missing " + ", ".join(missing)) - null = sorted( - field - for field in REQUIRED_RESULT_FIELDS & set(result) - if result[field] is None and field not in nullable - ) + null = sorted(field for field in present - must_be_null if result[field] is None) if null: problems.append("null " + ", ".join(null)) + not_null = sorted( + field for field in present & must_be_null if result[field] is not None + ) + if not_null: + problems.append("should be null for these options: " + ", ".join(not_null)) + numeric = NUMERIC_RESULT_FIELDS | {"rows_in_widest_leaf", "max_samples_leaf"} not_numbers = sorted( field - for field in NUMERIC_RESULT_FIELDS & set(result) - if result[field] is not None - and ( - isinstance(result[field], bool) - or not isinstance(result[field], int | float) - ) + for field in present & numeric + if result[field] is not None and not _is_number(result[field]) ) if not_numbers: - problems.append("not a number: " + ", ".join(not_numbers)) + problems.append("not a finite number: " + ", ".join(not_numbers)) + if result.get("implementation", implementation) != implementation: + problems.append(f"implementation is not {implementation!r}") + if result.get("memory_measure", "resident_set") not in { + "physical_footprint", + "resident_set", + }: + problems.append("memory_measure is not a known measure") + digest = result.get("leaf_array_sha256") + if digest is not None and not ( + isinstance(digest, str) + and len(digest) == 64 + and all(character in "0123456789abcdef" for character in digest) + ): + problems.append("leaf_array_sha256 is not a SHA-256 digest") shape = result.get("leaf_array_shape") - if "leaf_array_shape" in result and not ( - isinstance(shape, list) and all(isinstance(size, int) for size in shape) + if shape is not None and not ( + isinstance(shape, list) + and len(shape) == 4 + and all( + isinstance(size, int) and not isinstance(size, bool) and size >= 0 + for size in shape + ) ): - problems.append("leaf_array_shape is not a list of integers") + problems.append("leaf_array_shape is not four non-negative integers") environment = result.get("environment") - if "environment" in result: + if environment is not None: if not isinstance(environment, dict): problems.append("environment is not an object") else: lacking = sorted(REQUIRED_ENVIRONMENT_FIELDS - set(environment)) if lacking: problems.append("environment missing " + ", ".join(lacking)) + if not isinstance(environment.get("platform", ""), str): + problems.append("environment platform is not text") + if not _is_number(environment.get("page_size_bytes", 0)): + problems.append("environment page_size_bytes is not a number") + cpu_count = environment.get("cpu_count") + if cpu_count is not None and not _is_number(cpu_count): + problems.append("environment cpu_count is not a number") return problems @@ -571,7 +609,7 @@ def _run_child( "JSON object" ) return None, failure - problems = _result_problems(result, arguments) + problems = _result_problems(result, arguments, implementation) if problems: failure["message"] = ( f"the {implementation} measurement's result is unusable: " From 2197a78bf7efec6d0c0cc59c0bd10b1e0572fb77 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:38:38 +0400 Subject: [PATCH 10/15] Address round-eight review: one safeguard for malformed measurement results Round eight found every real child result accepted, but more malformed results (a list in memory_measure, integers over Python's digit limit, deep nesting, NaN in unchecked fields, unprintable strings) that could still crash the parent or reach --json output. Instead of one check per field, tools/measure_qrf_leaf_memory.py now: - parses with parse_constant refusing NaN and Infinity, and treats any ValueError or RecursionError from parsing as a result that is not standard JSON; - turns any exception while checking a result, or while formatting it for the report, into a reported failure for that measurement, so the other measurement still reports; - checks that each result describes the run the parent asked for (class, implementation, shape, rows, trees, seed, widest-leaf rows); - writes --json with allow_nan=False and escapes characters the terminal cannot encode in the text report. The page-residency test's child also drops glibc.mem.tagging tunables, since memory tagging makes glibc's calloc zero the whole block. qrf.py is unchanged, so no pin moves. 49 cases pass under scikit-learn 1.8.0, and real runs of every shape and option exit 0. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_qrf_leaf_array.py | 6 +-- tools/measure_qrf_leaf_memory.py | 54 ++++++++++++++++--- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index 1de3ca5de0..f3da84b456 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -576,8 +576,8 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: 1.0). The array, over 40 MiB, is larger than glibc's largest mmap threshold, so it gets fresh pages; numpy's request for transparent huge pages is turned off in the child, and glibc's ``MALLOC_PERTURB_`` and its - ``glibc.malloc`` tunables (which can fill allocations or request huge - pages) are removed from its environment. About a quarter of the pages + ``glibc.malloc`` and ``glibc.mem.tagging`` tunables (which can fill + allocations or request huge pages) are removed from its environment. About a quarter of the pages hold entries with 16 KiB pages and a sixteenth with 4 KiB pages. With pages over 16 KiB, or huge pages always on at any size, most pages hold an entry, so the test skips. @@ -602,7 +602,7 @@ def test_in_place_fill_leaves_unwritten_pages_unmapped() -> None: other_tunables = [ tunable for tunable in os.environ.get("GLIBC_TUNABLES", "").split(":") - if tunable and not tunable.startswith("glibc.malloc.") + if tunable and not tunable.startswith(("glibc.malloc.", "glibc.mem.tagging")) ] if other_tunables: environment["GLIBC_TUNABLES"] = ":".join(other_tunables) diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index e53682bda9..880662d100 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -500,18 +500,40 @@ def _result_problems( numeric = NUMERIC_RESULT_FIELDS | {"rows_in_widest_leaf", "max_samples_leaf"} not_numbers = sorted( field - for field in present & numeric + for field in (present & numeric) - must_be_null if result[field] is not None and not _is_number(result[field]) ) if not_numbers: - problems.append("not a finite number: " + ", ".join(not_numbers)) + problems.append("not a finite number within 64 bits: " + ", ".join(not_numbers)) if result.get("implementation", implementation) != implementation: problems.append(f"implementation is not {implementation!r}") - if result.get("memory_measure", "resident_set") not in { + if ( + result.get("class", EXPECTED_CLASSES[implementation]) + != (EXPECTED_CLASSES[implementation]) + ): + problems.append(f"class is not {EXPECTED_CLASSES[implementation]}") + measure = result.get("memory_measure", "resident_set") + if not isinstance(measure, str) or measure not in { "physical_footprint", "resident_set", }: problems.append("memory_measure is not a known measure") + # The result must describe the run the parent asked for. + requested = { + "shape": arguments.shape, + "rows": arguments.rows, + "trees": arguments.trees, + "seed": arguments.seed, + } + if arguments.shape == "wage": + requested["rows_in_widest_leaf"] = arguments.rows_in_widest_leaf + different = sorted( + field + for field, value in requested.items() + if field in result and result[field] is not None and result[field] != value + ) + if different: + problems.append("differs from the requested run: " + ", ".join(different)) digest = result.get("leaf_array_sha256") if digest is not None and not ( isinstance(digest, str) @@ -547,6 +569,11 @@ def _result_problems( return problems +def _refuse_constant(name: str) -> object: + """Refuse ``NaN`` and ``Infinity``, which Python's json reads but JSON lacks.""" + raise ValueError(f"{name} is not standard JSON") + + def _signal_name(number: int) -> str | None: try: return signal.Signals(number).name @@ -600,16 +627,22 @@ def _run_child( ) return None, failure try: - result = json.loads(marked[-1]) - except json.JSONDecodeError: + result = json.loads(marked[-1], parse_constant=_refuse_constant) + except (ValueError, RecursionError): result = None if not isinstance(result, dict): failure["message"] = ( f"the {implementation} measurement printed a result that is not a " - "JSON object" + "standard JSON object" ) return None, failure - problems = _result_problems(result, arguments, implementation) + try: + problems = _result_problems(result, arguments, implementation) + if not problems: + # Formatting the result alone shows the report can print it. + _report([result], [], None) + except Exception as error: # a malformed result must not stop the other run + problems = [f"it could not be read ({type(error).__name__}: {error})"] if problems: failure["message"] = ( f"the {implementation} measurement's result is unusable: " @@ -834,10 +867,15 @@ def main(argv: list[str] | None = None) -> int: "leaf_arrays_identical": identical, }, indent=2, + allow_nan=False, ) ) else: - print(_report(results, failures, identical)) + report = _report(results, failures, identical) + # Escape anything the terminal's encoding cannot show, such as a lone + # surrogate in a malformed field, instead of failing to print. + encoding = sys.stdout.encoding or "utf-8" + print(report.encode(encoding, "backslashreplace").decode(encoding)) return 1 if failures or identical is False else 0 From 9ec0b2c900e3eb6643bbbc9bc3663284b34b9326 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:53:03 +0400 Subject: [PATCH 11/15] Address round-nine review: child output encoding, strict JSON, matching results Round nine found one problem with real children: a caller's PYTHONIOENCODING (cp500, utf-16, utf-8-sig) changed how the child wrote its result, so the parent either failed to decode it or reported that no result was printed. tools/measure_qrf_leaf_memory.py now runs each child with PYTHONIOENCODING=utf-8 and reads its output as UTF-8, replacing any byte it cannot decode; real runs under all three encodings report both results. For malformed results, which a real child cannot print: - numbers too large for a float (1e400) are refused at parse time; - the safeguard also writes each result as standard JSON in valid UTF-8, so deep nesting and lone surrogates are refused before --json output; - leaf_array_bytes must match the shape for an int64 array; - two results must share their platform record and fit settings (n_jobs, trees grown at once, the cap, the memory measure), or the run reports that they disagree and exits 1. Co-Authored-By: Claude Opus 5.5 --- tools/measure_qrf_leaf_memory.py | 69 +++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 880662d100..094cd8717b 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -23,6 +23,11 @@ - Linux: the peak resident set size (``ru_maxrss``). Pages swapped out under memory pressure are not counted, so measure on a machine with free memory. +The parent checks each child's result before reporting it, and refuses one +that is malformed or describes a different run, so the other measurement +still reports. Two results must share their platform record and fit +settings. + Growth can also read a little low when the fit reuses memory that the process already used, and so already counted in its peak, before the fit started. That matters only for small fits. @@ -551,6 +556,15 @@ def _result_problems( ) ): problems.append("leaf_array_shape is not four non-negative integers") + elif ( + shape is not None + and result.get("leaf_array_dtype") == "int64" + and isinstance(result.get("leaf_array_bytes"), int) + and result["leaf_array_bytes"] != math.prod(shape) * 8 + ): + problems.append("leaf_array_bytes does not match leaf_array_shape") + if result.get("leaf_array_dtype", "int64") != "int64": + problems.append("leaf_array_dtype is not int64") environment = result.get("environment") if environment is not None: if not isinstance(environment, dict): @@ -569,6 +583,14 @@ def _result_problems( return problems +def _finite_float(text: str) -> float: + """Parse a JSON number, refusing one too large for a float (``1e400``).""" + value = float(text) + if not math.isfinite(value): + raise ValueError(f"{text} does not fit in a float") + return value + + def _refuse_constant(name: str) -> object: """Refuse ``NaN`` and ``Infinity``, which Python's json reads but JSON lacks.""" raise ValueError(f"{name} is not standard JSON") @@ -585,11 +607,15 @@ def _run_child( arguments: argparse.Namespace, implementation: str ) -> tuple[dict[str, object] | None, dict[str, object] | None]: """Run one measurement; return its result, or a description of its failure.""" + # The child writes UTF-8 whatever PYTHONIOENCODING the caller has set, + # and the parent reads it as UTF-8, replacing any byte it cannot decode. completed = subprocess.run( _child_command(arguments, implementation), stdout=subprocess.PIPE, - text=True, + encoding="utf-8", + errors="replace", check=False, + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, ) failure: dict[str, object] = { "implementation": implementation, @@ -627,7 +653,9 @@ def _run_child( ) return None, failure try: - result = json.loads(marked[-1], parse_constant=_refuse_constant) + result = json.loads( + marked[-1], parse_constant=_refuse_constant, parse_float=_finite_float + ) except (ValueError, RecursionError): result = None if not isinstance(result, dict): @@ -641,6 +669,9 @@ def _run_child( if not problems: # Formatting the result alone shows the report can print it. _report([result], [], None) + # And that --json can write it as standard JSON in valid UTF-8 + # (this refuses lone surrogates and nesting json cannot write). + json.dumps(result, allow_nan=False, ensure_ascii=False).encode("utf-8") except Exception as error: # a malformed result must not stop the other run problems = [f"it could not be read ({type(error).__name__}: {error})"] if problems: @@ -652,6 +683,27 @@ def _run_child( return result, None +#: Result fields that two measurements of one run must share. +SHARED_RESULT_FIELDS = ( + "environment", + "n_jobs", + "trees_at_once", + "max_samples_leaf", + "memory_measure", +) + + +def _disagreements(results: list[dict[str, object]]) -> list[str]: + """Return the shared fields on which two results differ.""" + if len(results) != 2: + return [] + return [ + field + for field in SHARED_RESULT_FIELDS + if results[0].get(field) != results[1].get(field) + ] + + def _identical(results: list[dict[str, object]]) -> bool | None: if len(results) != 2 or any( result["leaf_array_sha256"] is None for result in results @@ -844,6 +896,19 @@ def main(argv: list[str] | None = None) -> int: failures.append(failure) else: results.append(result) + disagreeing = _disagreements(results) + if disagreeing: + failures.append( + { + "implementation": "both", + "exit_code": None, + "signal_number": None, + "signal": None, + "message": "the two measurements disagree on " + + ", ".join(disagreeing) + + ", so they ran under different settings", + } + ) identical = _identical(results) if arguments.json: print( From e169058d1172f167bf6f378671a153249d08f5b8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:11:18 +0400 Subject: [PATCH 12/15] Use _InPlaceLeafQRF wherever the library class name was not required _Forest now declares and checks its model as _InPlaceLeafQRF, so loading a forest pickled with quantile-forest's class raises TypeError. Package code names RandomForestQuantileRegressor only as the base class. Regenerate the source hash pins that cover microcosm.fit.qrf. Co-Authored-By: Claude Opus 5.5 --- .../qrf-leaf-array-in-place.changed.md | 2 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 ++++++------ .../build/spec_engine/inventory_coverage.py | 4 +-- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 25 +++++++++---------- .../tests/engine_free/shared/test_qrf.py | 8 ++---- .../engine_free/shared/test_qrf_leaf_array.py | 12 +++++++++ .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- 9 files changed, 40 insertions(+), 33 deletions(-) diff --git a/changelog.d/qrf-leaf-array-in-place.changed.md b/changelog.d/qrf-leaf-array-in-place.changed.md index 4d2716f0d4..25aeca948e 100644 --- a/changelog.d/qrf-leaf-array-in-place.changed.md +++ b/changelog.d/qrf-leaf-array-in-place.changed.md @@ -2,4 +2,4 @@ microcosm-fit's QRF forests build their leaf array in place. quantile-forest sto - quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method. `_InPlaceLeafQRF` refuses any other installed release, in `fit` before growing a tree and again where its copied code runs. - `tools/measure_qrf_leaf_memory.py` fits one synthetic forest shaped like the CPS-ORG wage fit or a capped near-discrete fit through `_fit_forest`, once with each class and each in a fresh process, and reports each fit's peak memory (the peak physical footprint on macOS, the peak resident set on Linux). -- Pickling or deep-copying a fitted forest still writes the full padded array, as before. New pickles name `microcosm.fit.qrf._InPlaceLeafQRF`, so microcosm-fit from before this change cannot load them; pickles made before it still load and draw the same values. scikit-learn's validation messages for a forest (a missing value in a predictor, an invalid `max_samples_leaf`) name `_InPlaceLeafQRF` instead of `RandomForestQuantileRegressor`; the exception types are unchanged. +- Pickling or deep-copying a fitted forest still writes the full padded array, as before. Forests now pickle as `microcosm.fit.qrf._InPlaceLeafQRF`, and loading a forest pickled before this change raises `TypeError`; refit it instead. scikit-learn's validation messages for a forest (a missing value in a predictor, an invalid `max_samples_leaf`) name `_InPlaceLeafQRF`; the exception types are unchanged. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index fd18ffd8e1..3d2d88f906 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", - "protocol_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df" + "map_sha256": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "protocol_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176" }, "failures": [], "observed": { - "map_sha256": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", - "protocol_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df" + "map_sha256": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "protocol_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", + "implementation_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", + "implementation_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb" + "spec_sha256": "4628926c07a2e217376b3d146c3506db498d97888d1f3f0412708a11a1a5c913" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb" + "spec_sha256": "4628926c07a2e217376b3d146c3506db498d97888d1f3f0412708a11a1a5c913" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index ba8da40648..8844a7610b 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf moves both again: the # forests' leaf arrays are byte-identical, and no draw changes. - "seed_map": "eab58602d64750681ea21a370690afecd24207555aa78dcf5a3ea2740a181d7b", - "seed_protocol": "38622fb9956a2878ac120db7153425e3337a73b6d3613142af7e55bb962a14df", + "seed_map": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "seed_protocol": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index a274506f50..0511b9ee81 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -34,7 +34,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # moves it again. # The in-place QRF leaf array moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "5778dd8521f888a09afcc092c463de5ae7dc46296eaac2ab88ffde48806a872a" + "30d83d44c9c004c76f49c6ff36d9eb2249f30632f00e3ff72691121100c39d1a" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index fbf6aa88ab..e62aa1b806 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -364,7 +364,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. # The in-place QRF leaf array in microcosm.fit.qrf moves it again. - "spec_sha256": "96d74a46d556bd596308fd02a12addfa3f8d4c77d06fd00a7d3d4abd25e5dbbb", + "spec_sha256": "4628926c07a2e217376b3d146c3506db498d97888d1f3f0412708a11a1a5c913", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 530bd74a08..1b2f4f78b0 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -69,7 +69,6 @@ import numpy as np import pandas as pd import quantile_forest -from quantile_forest import RandomForestQuantileRegressor from sklearn.ensemble import HistGradientBoostingClassifier from microcosm.fit.model import ( @@ -1252,7 +1251,7 @@ def _fill_tree_leaves( ) -class _InPlaceLeafQRF(RandomForestQuantileRegressor): +class _InPlaceLeafQRF(quantile_forest.RandomForestQuantileRegressor): """A quantile forest whose leaf array is filled in place. After growing its trees, quantile-forest maps every leaf to the training @@ -1273,14 +1272,14 @@ class _InPlaceLeafQRF(RandomForestQuantileRegressor): ``_get_y_train_leaves`` and wraps :meth:`fit` only to check the version: both refuse any quantile-forest release other than :data:`_SUPPORTED_QUANTILE_FOREST_VERSION`. scikit-learn's validation - messages name this class instead of ``RandomForestQuantileRegressor``. A - ``max_samples_leaf`` so large that the whole forest's array exceeds the - largest size numpy can describe raises numpy's ``ValueError`` here, where - the library, allocating one tree at a time, raises ``MemoryError``. A - failed allocation here comes before any tree's ``random`` calls. So with a - leaf cap set, if the library gets past at least one tree before its own - allocation or its final copy fails, Python's ``random`` state can differ - from the library's after that failed fit. + messages name this class. A ``max_samples_leaf`` so large that the whole + forest's array exceeds the largest size numpy can describe raises numpy's + ``ValueError`` here, where the library, allocating one tree at a time, + raises ``MemoryError``. A failed allocation here comes before any tree's + ``random`` calls. So with a leaf cap set, if the library gets past at + least one tree before its own allocation or its final copy fails, + Python's ``random`` state can differ from the library's after that failed + fit. The saving lasts while pages stay untouched. Pages of an ``np.zeros`` array take no memory until something touches them. A write makes a page @@ -1404,13 +1403,13 @@ def _get_y_train_leaves(self, X, y, sorter=None, sample_weight=None): # noqa: N class _Forest: """A fitted quantile forest plus the feature columns it was fit on.""" - model: RandomForestQuantileRegressor + model: _InPlaceLeafQRF columns: tuple[str, ...] def __getstate__(self) -> dict[str, object]: """Return a worker-count-neutral pickle payload. - ``RandomForestQuantileRegressor.n_jobs`` controls only runtime + ``_InPlaceLeafQRF.n_jobs`` controls only runtime parallelism. A shallow model copy lets serialization pin that field without mutating the fitted object that will perform the first draw. """ @@ -1423,7 +1422,7 @@ def __setstate__(self, state: Mapping[str, object]) -> None: """Restore the current runtime worker setting after trusted loading.""" model = state["model"] - if not isinstance(model, RandomForestQuantileRegressor): + if not isinstance(model, _InPlaceLeafQRF): raise TypeError("Serialized QRF forest model has an invalid type.") columns = state["columns"] if not isinstance(columns, tuple) or any( diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py index 285f10289a..ccc2379a79 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py @@ -390,9 +390,7 @@ def test_high_quantile_draw_reaches_the_observed_max() -> None: 1, so the observed max is drawable. This is a direct probe of the forest's draw at q=1 against the interior-only (winsorized) grid. """ - from quantile_forest import RandomForestQuantileRegressor - - from microcosm.fit.qrf import _QUANTILE_GRID, _Forest + from microcosm.fit.qrf import _QUANTILE_GRID, _Forest, _InPlaceLeafQRF rng = np.random.default_rng(0) n = 2000 @@ -402,9 +400,7 @@ def test_high_quantile_draw_reaches_the_observed_max() -> None: y = rng.normal(100.0, 10.0, n) observed_max = 1000.0 y[0] = observed_max # a lone extreme: the observed conditional maximum - model = RandomForestQuantileRegressor( - n_estimators=50, max_samples_leaf=None, random_state=0 - ) + model = _InPlaceLeafQRF(n_estimators=50, max_samples_leaf=None, random_state=0) model.fit(x, y) forest = _Forest(model=model, columns=("x",)) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py index f3da84b456..4793fd42ff 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -848,6 +848,18 @@ def test_subclass_pickles_and_clones_like_the_library_class() -> None: assert cloned.get_params() == model.get_params() +def test_forest_refuses_a_pickled_library_class_model() -> None: + """A stored forest must hold the in-place class, not the library's.""" + predictors, target = _continuous_donors(seed=11, rows=120) + library_model = RandomForestQuantileRegressor( + n_estimators=2, max_samples_leaf=None, random_state=3, n_jobs=1 + ) + library_model.fit(predictors, target) + payload = pickle.dumps(qrf._Forest(model=library_model, columns=("a", "b", "c"))) + with pytest.raises(TypeError, match="invalid type"): + pickle.loads(payload) + + # ---------------------------------------------------------------------------- # The exact quantile-forest version the override mirrors # ---------------------------------------------------------------------------- diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 6e6df2b63a..84cacd098d 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"e1883411a845b1b1ec8c24eeb72eacd3201f102aae6a74a938f6f08d5d173db6","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"71a555e7669691d7b1105d891fbff136828f68314fbd140af1c8c00285f69a99","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"71a555e7669691d7b1105d891fbff136828f68314fbd140af1c8c00285f69a99"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"67ed441109b4d6e4d08d8d8f04812f21ef7b764f026ce3c817f5d2c698437643"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"e9e36be7d74a0247da2add7ea08bb8e13aff412d09e9beb39419372ce04f24f4"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"78c79fefce8dcc9bb080f3cb26c7de2bf6f66de63ea6c2d79f3af9244a904e33","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"b199bcbea78c0781c5deae6a6c8cbe8a95b0f34d063afca6c410793bcc52de32","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"b199bcbea78c0781c5deae6a6c8cbe8a95b0f34d063afca6c410793bcc52de32"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"e3a0a6bfbbc3b99eaca29bdbc7a74f02e46b2c5bc3ea76dd6ecedf38d54a2570"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"1ee311acfebb1e9f948e6efaccd083b85f3bafde304738ef51745ca861183b8f"}},"seed":947} From bff48ee0bacc7f49fe3624e99db077eb10294d47 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:40:59 +0400 Subject: [PATCH 13/15] Raise the fitted-model cache schema version Forests pickled with quantile-forest's class are now refused on load, and the cache key does not include the forest class, so an older entry raised TypeError instead of being a miss. Schema version 2 changes the key, so those entries are no longer looked up. Co-Authored-By: Claude Opus 5.5 --- .../qrf-leaf-array-in-place.changed.md | 2 +- .../microcosm-fit/src/microcosm/fit/cache.py | 2 +- .../tests/engine_free/shared/test_cache.py | 24 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/changelog.d/qrf-leaf-array-in-place.changed.md b/changelog.d/qrf-leaf-array-in-place.changed.md index 25aeca948e..ee61ffd278 100644 --- a/changelog.d/qrf-leaf-array-in-place.changed.md +++ b/changelog.d/qrf-leaf-array-in-place.changed.md @@ -2,4 +2,4 @@ microcosm-fit's QRF forests build their leaf array in place. quantile-forest sto - quantile-forest is pinned to exactly 1.4.2, since the subclass replaces a private method. `_InPlaceLeafQRF` refuses any other installed release, in `fit` before growing a tree and again where its copied code runs. - `tools/measure_qrf_leaf_memory.py` fits one synthetic forest shaped like the CPS-ORG wage fit or a capped near-discrete fit through `_fit_forest`, once with each class and each in a fresh process, and reports each fit's peak memory (the peak physical footprint on macOS, the peak resident set on Linux). -- Pickling or deep-copying a fitted forest still writes the full padded array, as before. Forests now pickle as `microcosm.fit.qrf._InPlaceLeafQRF`, and loading a forest pickled before this change raises `TypeError`; refit it instead. scikit-learn's validation messages for a forest (a missing value in a predictor, an invalid `max_samples_leaf`) name `_InPlaceLeafQRF`; the exception types are unchanged. +- Pickling or deep-copying a fitted forest still writes the full padded array, as before. Forests now pickle as `microcosm.fit.qrf._InPlaceLeafQRF`, and loading a forest pickled before this change raises `TypeError`; refit it instead. The fitted-model cache moves to schema version 2, so entries written before this change are cache misses. scikit-learn's validation messages for a forest (a missing value in a predictor, an invalid `max_samples_leaf`) name `_InPlaceLeafQRF`; the exception types are unchanged. diff --git a/packages/microcosm-fit/src/microcosm/fit/cache.py b/packages/microcosm-fit/src/microcosm/fit/cache.py index ea64f2892a..b7416e4ff9 100644 --- a/packages/microcosm-fit/src/microcosm/fit/cache.py +++ b/packages/microcosm-fit/src/microcosm/fit/cache.py @@ -9,7 +9,7 @@ from pathlib import Path from typing import Any -SCHEMA_VERSION = 1 +SCHEMA_VERSION = 2 @dataclass(frozen=True) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_cache.py b/packages/microcosm-fit/tests/engine_free/shared/test_cache.py index 7cac908dbe..5b05cf90ae 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_cache.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_cache.py @@ -1,10 +1,15 @@ from __future__ import annotations +import numpy as np +from quantile_forest import RandomForestQuantileRegressor + +from microcosm.fit import cache as cache_module from microcosm.fit.cache import ( QRFCacheKey, load_fitted_qrf_cache, save_fitted_qrf_cache, ) +from microcosm.fit.qrf import _Forest def _key(seed: int = 0) -> QRFCacheKey: @@ -25,3 +30,22 @@ def test_qrf_cache_save_load_and_miss(tmp_path) -> None: assert path.exists() assert load_fitted_qrf_cache(tmp_path, _key()) == model assert load_fitted_qrf_cache(tmp_path, _key(seed=1)) is None + + +def test_entry_holding_a_library_class_forest_is_a_cache_miss( + tmp_path, monkeypatch +) -> None: + """An entry from schema 1 is ignored rather than unpickled and refused.""" + predictors = np.arange(40, dtype=np.float64).reshape(-1, 1) + target = predictors[:, 0] + 1.0 + library_model = RandomForestQuantileRegressor( + n_estimators=2, random_state=0, n_jobs=1 + ) + library_model.fit(predictors, target) + schema_one_entry = {"forest": _Forest(model=library_model, columns=("x",))} + with monkeypatch.context() as schema_one: + schema_one.setattr(cache_module, "SCHEMA_VERSION", 1) + schema_one_path = save_fitted_qrf_cache(schema_one_entry, tmp_path, _key()) + + assert schema_one_path.exists() + assert load_fitted_qrf_cache(tmp_path, _key()) is None From ec291bb9eea48d4204571eef448b5be914ca90f6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:58:52 +0400 Subject: [PATCH 14/15] Remove malformed-output checks from the QRF memory script The script's child process is the script itself, so validating every field of its result guarded against output it cannot produce. Keep the memory readings, the fitted-class check and the reporting of a failed or stopped child. Co-Authored-By: Claude Opus 5.5 --- tools/measure_qrf_leaf_memory.py | 265 +------------------------------ 1 file changed, 2 insertions(+), 263 deletions(-) diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 094cd8717b..2b435b3649 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -23,11 +23,6 @@ - Linux: the peak resident set size (``ru_maxrss``). Pages swapped out under memory pressure are not counted, so measure on a machine with free memory. -The parent checks each child's result before reporting it, and refuses one -that is malformed or describes a different run, so the other measurement -still reports. Two results must share their platform record and fit -settings. - Growth can also read a little low when the fit reuses memory that the process already used, and so already counted in its peak, before the fit started. That matters only for small fits. @@ -106,7 +101,6 @@ import hashlib import importlib.metadata import json -import math import os import platform import resource @@ -127,58 +121,6 @@ DEFAULT_TREES = {"wage": 100, "near-discrete": 32} DEFAULT_ROWS = {"wage": 10_000, "near-discrete": 10_000} DEFAULT_ROWS_IN_WIDEST_LEAF = 250 -#: Fields the parent reads from every child result. -REQUIRED_RESULT_FIELDS = frozenset( - { - "implementation", - "class", - "leaf_array_shape", - "leaf_array_dtype", - "leaf_array_bytes", - "leaf_array_sha256", - "memory_measure", - "peak_bytes_after_fit", - "fit_peak_growth_bytes", - "peak_resident_set_bytes_before_fit", - "peak_resident_set_bytes_after_fit", - "fit_seconds", - "shape", - "rows", - "trees", - "rows_in_widest_leaf", - "seed", - "n_jobs", - "trees_at_once", - "max_samples_leaf", - "environment", - } -) -#: Required result fields that hold a number. -NUMERIC_RESULT_FIELDS = frozenset( - { - "leaf_array_bytes", - "peak_bytes_after_fit", - "fit_peak_growth_bytes", - "peak_resident_set_bytes_before_fit", - "peak_resident_set_bytes_after_fit", - "fit_seconds", - "rows", - "trees", - "seed", - "n_jobs", - "trees_at_once", - } -) -#: Fields of a result's ``environment`` that the report reads. -REQUIRED_ENVIRONMENT_FIELDS = frozenset( - { - "platform", - "cpu_count", - "page_size_bytes", - "transparent_huge_pages", - "numpy_requests_huge_pages", - } -) #: Marks the child's result line on standard output. RESULT_PREFIX = "measure_qrf_leaf_memory result: " #: scikit-learn accepts integer seeds below 2**32. @@ -460,142 +402,6 @@ def _child_command(arguments: argparse.Namespace, implementation: str) -> list[s return command -def _null_fields(arguments: argparse.Namespace) -> set[str]: - """Return the result fields that must be null for this run's options. - - Every other required field must hold a value. - """ - null = set() - if arguments.no_digest: - null.add("leaf_array_sha256") - if arguments.shape == "wage": - null.add("max_samples_leaf") # the wage forest has no cap - else: - null.add("rows_in_widest_leaf") - return null - - -def _is_number(value: object) -> bool: - """Whether ``value`` is a finite int or float that fits in 64 bits.""" - if isinstance(value, bool) or not isinstance(value, int | float): - return False - if isinstance(value, float): - return math.isfinite(value) - return abs(value) < 2**63 - - -def _result_problems( - result: dict[str, object], arguments: argparse.Namespace, implementation: str -) -> list[str]: - """Describe what makes a child's result unusable; empty if nothing does.""" - must_be_null = _null_fields(arguments) - present = REQUIRED_RESULT_FIELDS & set(result) - problems = [] - missing = sorted(REQUIRED_RESULT_FIELDS - set(result)) - if missing: - problems.append("missing " + ", ".join(missing)) - null = sorted(field for field in present - must_be_null if result[field] is None) - if null: - problems.append("null " + ", ".join(null)) - not_null = sorted( - field for field in present & must_be_null if result[field] is not None - ) - if not_null: - problems.append("should be null for these options: " + ", ".join(not_null)) - numeric = NUMERIC_RESULT_FIELDS | {"rows_in_widest_leaf", "max_samples_leaf"} - not_numbers = sorted( - field - for field in (present & numeric) - must_be_null - if result[field] is not None and not _is_number(result[field]) - ) - if not_numbers: - problems.append("not a finite number within 64 bits: " + ", ".join(not_numbers)) - if result.get("implementation", implementation) != implementation: - problems.append(f"implementation is not {implementation!r}") - if ( - result.get("class", EXPECTED_CLASSES[implementation]) - != (EXPECTED_CLASSES[implementation]) - ): - problems.append(f"class is not {EXPECTED_CLASSES[implementation]}") - measure = result.get("memory_measure", "resident_set") - if not isinstance(measure, str) or measure not in { - "physical_footprint", - "resident_set", - }: - problems.append("memory_measure is not a known measure") - # The result must describe the run the parent asked for. - requested = { - "shape": arguments.shape, - "rows": arguments.rows, - "trees": arguments.trees, - "seed": arguments.seed, - } - if arguments.shape == "wage": - requested["rows_in_widest_leaf"] = arguments.rows_in_widest_leaf - different = sorted( - field - for field, value in requested.items() - if field in result and result[field] is not None and result[field] != value - ) - if different: - problems.append("differs from the requested run: " + ", ".join(different)) - digest = result.get("leaf_array_sha256") - if digest is not None and not ( - isinstance(digest, str) - and len(digest) == 64 - and all(character in "0123456789abcdef" for character in digest) - ): - problems.append("leaf_array_sha256 is not a SHA-256 digest") - shape = result.get("leaf_array_shape") - if shape is not None and not ( - isinstance(shape, list) - and len(shape) == 4 - and all( - isinstance(size, int) and not isinstance(size, bool) and size >= 0 - for size in shape - ) - ): - problems.append("leaf_array_shape is not four non-negative integers") - elif ( - shape is not None - and result.get("leaf_array_dtype") == "int64" - and isinstance(result.get("leaf_array_bytes"), int) - and result["leaf_array_bytes"] != math.prod(shape) * 8 - ): - problems.append("leaf_array_bytes does not match leaf_array_shape") - if result.get("leaf_array_dtype", "int64") != "int64": - problems.append("leaf_array_dtype is not int64") - environment = result.get("environment") - if environment is not None: - if not isinstance(environment, dict): - problems.append("environment is not an object") - else: - lacking = sorted(REQUIRED_ENVIRONMENT_FIELDS - set(environment)) - if lacking: - problems.append("environment missing " + ", ".join(lacking)) - if not isinstance(environment.get("platform", ""), str): - problems.append("environment platform is not text") - if not _is_number(environment.get("page_size_bytes", 0)): - problems.append("environment page_size_bytes is not a number") - cpu_count = environment.get("cpu_count") - if cpu_count is not None and not _is_number(cpu_count): - problems.append("environment cpu_count is not a number") - return problems - - -def _finite_float(text: str) -> float: - """Parse a JSON number, refusing one too large for a float (``1e400``).""" - value = float(text) - if not math.isfinite(value): - raise ValueError(f"{text} does not fit in a float") - return value - - -def _refuse_constant(name: str) -> object: - """Refuse ``NaN`` and ``Infinity``, which Python's json reads but JSON lacks.""" - raise ValueError(f"{name} is not standard JSON") - - def _signal_name(number: int) -> str | None: try: return signal.Signals(number).name @@ -652,56 +458,7 @@ def _run_child( f"the {implementation} measurement exited without printing a result" ) return None, failure - try: - result = json.loads( - marked[-1], parse_constant=_refuse_constant, parse_float=_finite_float - ) - except (ValueError, RecursionError): - result = None - if not isinstance(result, dict): - failure["message"] = ( - f"the {implementation} measurement printed a result that is not a " - "standard JSON object" - ) - return None, failure - try: - problems = _result_problems(result, arguments, implementation) - if not problems: - # Formatting the result alone shows the report can print it. - _report([result], [], None) - # And that --json can write it as standard JSON in valid UTF-8 - # (this refuses lone surrogates and nesting json cannot write). - json.dumps(result, allow_nan=False, ensure_ascii=False).encode("utf-8") - except Exception as error: # a malformed result must not stop the other run - problems = [f"it could not be read ({type(error).__name__}: {error})"] - if problems: - failure["message"] = ( - f"the {implementation} measurement's result is unusable: " - + "; ".join(problems) - ) - return None, failure - return result, None - - -#: Result fields that two measurements of one run must share. -SHARED_RESULT_FIELDS = ( - "environment", - "n_jobs", - "trees_at_once", - "max_samples_leaf", - "memory_measure", -) - - -def _disagreements(results: list[dict[str, object]]) -> list[str]: - """Return the shared fields on which two results differ.""" - if len(results) != 2: - return [] - return [ - field - for field in SHARED_RESULT_FIELDS - if results[0].get(field) != results[1].get(field) - ] + return json.loads(marked[-1]), None def _identical(results: list[dict[str, object]]) -> bool | None: @@ -896,19 +653,6 @@ def main(argv: list[str] | None = None) -> int: failures.append(failure) else: results.append(result) - disagreeing = _disagreements(results) - if disagreeing: - failures.append( - { - "implementation": "both", - "exit_code": None, - "signal_number": None, - "signal": None, - "message": "the two measurements disagree on " - + ", ".join(disagreeing) - + ", so they ran under different settings", - } - ) identical = _identical(results) if arguments.json: print( @@ -932,15 +676,10 @@ def main(argv: list[str] | None = None) -> int: "leaf_arrays_identical": identical, }, indent=2, - allow_nan=False, ) ) else: - report = _report(results, failures, identical) - # Escape anything the terminal's encoding cannot show, such as a lone - # surrogate in a malformed field, instead of failing to print. - encoding = sys.stdout.encoding or "utf-8" - print(report.encode(encoding, "backslashreplace").decode(encoding)) + print(_report(results, failures, identical)) return 1 if failures or identical is False else 0 From 8729ab5d4d62d8931bd464dc31e30cb1468a8351 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:09:38 +0400 Subject: [PATCH 15/15] State that the memory script's default sizes were not measured Co-Authored-By: Claude Opus 5.5 --- tools/measure_qrf_leaf_memory.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py index 2b435b3649..d864f2cdfb 100644 --- a/tools/measure_qrf_leaf_memory.py +++ b/tools/measure_qrf_leaf_memory.py @@ -65,7 +65,8 @@ so most pages are never written, and the in-place fill saves most of the array as well as the second copy. -The defaults finish in under a minute on a laptop and need a few GB. Memory +The defaults are sized to finish in minutes on a laptop and to need a few GB; +only smaller runs have been measured. Memory grows roughly in proportion to rows times width (the cap, for ``near-discrete``) times trees, so raise ``--rows`` with care::