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..ee61ffd278 --- /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. `_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. 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/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index eba12bf9cc..4da5db5ab3 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": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "protocol_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176" }, "failures": [], "observed": { - "map_sha256": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "protocol_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6" + "spec_sha256": "f5eb16a0ff78a0b6622c7701f22a9f12a466e5f2729fd83c200ccc3b519c0292" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6" + "spec_sha256": "f5eb16a0ff78a0b6622c7701f22a9f12a466e5f2729fd83c200ccc3b519c0292" }, "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..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 @@ -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": "afbe93ebeb8d48294581d860aed690c168eb4c2c92461353676a794cefd22584", + "seed_protocol": "05fb40521ffef194cec9c2fe4dfedbbfd02e64ddddfd69f1a591961b61804176", "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..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 @@ -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" + "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 d95d4e964c..fdb83d6569 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,8 @@ 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. # microcosm#1585's us/gates.json row in country_package.json moves it. - "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6", + # The in-place QRF leaf array in microcosm.fit.qrf moves it again. + "spec_sha256": "f5eb16a0ff78a0b6622c7701f22a9f12a466e5f2729fd83c200ccc3b519c0292", }, } 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 04c3da08d7..4b7788280e 100644 --- a/packages/microcosm-fit/pyproject.toml +++ b/packages/microcosm-fit/pyproject.toml @@ -12,12 +12,20 @@ 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. 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", - "quantile-forest>=1.4.2", + # Exact: microcosm.fit.qrf._InPlaceLeafQRF replaces the private + # 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. + "quantile-forest==1.4.2", "numpy>=2", "pandas>=2.3", ] 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/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 89d322dc10..1b2f4f78b0 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -60,13 +60,15 @@ 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 -from quantile_forest import RandomForestQuantileRegressor +import quantile_forest from sklearn.ensemble import HistGradientBoostingClassifier from microcosm.fit.model import ( @@ -1142,6 +1144,258 @@ 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 = 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 " + "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 " + "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``, 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 + 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. + + 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 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 = library.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'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: + 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 = library.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(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 + 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. + + 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. 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. 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 + 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 + """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, X, y, sorter=None, sample_weight=None): # noqa: N803 + """Return the leaf array, built as quantile-forest 1.4.2 builds it. + + 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, so the library's per-tree method + ``_get_y_train_leaves_slice`` is not called. + """ + _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 + 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(X) + + 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 @@ -1149,13 +1403,13 @@ def _locate_rows( 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. """ @@ -1168,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( @@ -1478,7 +1732,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-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 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 new file mode 100644 index 0000000000..4793fd42ff --- /dev/null +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_leaf_array.py @@ -0,0 +1,951 @@ +"""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 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 +from sklearn.utils.fixes import parse_version + +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 tens to 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'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. + """ + 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 + + +@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: + """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. A numpy integer cap counts as an integer, as in the library. + """ + 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) + predictors, target = _near_discrete_donors(seed=2) + leaves = _assert_same_fit(predictors, target, max_samples_leaf=cap) + 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 + assert half > 0 + assert shuffle_calls[:half] == shuffle_calls[half:] + assert min(shuffle_calls) > width + + +@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) + 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("max_samples_leaf", [None, 3, 1]) +def test_weighted_leaves_that_empty_get_the_library_placeholder( + monkeypatch, max_samples_leaf +) -> None: + """A leaf whose entries the weight filter removes holds ``[0]``. + + 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. + """ + 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=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("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, 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, + 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 bootstrap and parse_version(sklearn.__version__) >= parse_version("1.9.0"): + levels.remove(-1.0) + weights = generator.choice(levels, len(target)) + _assert_same_fit( + predictors, + target, + sample_weight=weights, + max_samples_leaf=max_samples_leaf, + bootstrap=bootstrap, + ) + + +@pytest.mark.parametrize( + "parameters", + [ + pytest.param({}, id="library-default-one-sample-per-leaf"), + # 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( + {"max_samples_leaf": None, "max_samples": 150}, id="row-bootstrap" + ), + ], +) +def test_other_forest_settings_match_the_library(parameters) -> None: + """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) + + +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) + + +def test_fill_refuses_a_helper_that_returns_a_copy(monkeypatch) -> None: + """If the compiled helper returned a copy, fitting fails. + + 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 + + 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_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 ``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, 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", 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", 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( + 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 + ) + _assert_same_fit(predictors, target, sample_weight=weights, max_samples_leaf=None) + # 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``. + + 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(active_filters()) + qrf._InPlaceLeafQRF(n_estimators=2, max_samples_leaf=None, random_state=5).fit( + predictors, target + ) + assert list(active_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, and glibc's ``MALLOC_PERTURB_`` and its + ``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. + """ + 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") + 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_", "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.", "glibc.mem.tagging")) + ] + if other_tunables: + environment["GLIBC_TUNABLES"] = ":".join(other_tunables) + completed = subprocess.run( + [sys.executable, "-c", _RESIDENT_SHARE_CHILD], + capture_output=True, + text=True, + 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") + assert float(reading) < 0.6 + + +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 +# ---------------------------------------------------------------------------- + + +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 public fit draws the same values with either class. + + 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 + 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 +# ---------------------------------------------------------------------------- + + +@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( + 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() + + +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 +# ---------------------------------------------------------------------------- + + +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_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_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) + 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), + ) 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..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":"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":"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} diff --git a/tools/measure_qrf_leaf_memory.py b/tools/measure_qrf_leaf_memory.py new file mode 100644 index 0000000000..d864f2cdfb --- /dev/null +++ b/tools/measure_qrf_leaf_memory.py @@ -0,0 +1,688 @@ +#!/usr/bin/env python3 +"""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 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, 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 peak resident set size + (``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. + +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. 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 +duplicates rows as it does for weighted survey donors. + +- ``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 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:: + + 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 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 +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. The exit code is also 1 when +the two leaf arrays differ, since the memory comparison then compares +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 + +import argparse +import contextlib +import ctypes +import gc +import hashlib +import importlib.metadata +import json +import os +import platform +import resource +import signal +import subprocess +import sys +import time +from pathlib import Path + +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 +#: 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 + + +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: + """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 _peak_footprint_bytes() -> int | None: + """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 + 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 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) + + +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.""" + try: + 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") + }, + } + + +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. + 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( + [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) + 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.15, rows))) + return predictors, np.maximum(wage, 1.0) + + +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, 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)) + 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 _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 + ) + else: + predictors, target = _near_discrete_donors(arguments.rows, arguments.seed) + 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.""" + import joblib + 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() + before = _peak_memory() + started = time.perf_counter() + # _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 + 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"] is not None + else "resident_set" + ) + return { + "implementation": arguments.child, + "class": fitted_class, + "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, + "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), + "leaf_array_bytes": int(leaves.nbytes), + "leaf_array_sha256": digest, + "fit_seconds": round(fit_seconds, 3), + "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(), + } + + +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), + "--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 _signal_name(number: int) -> str | None: + try: + return signal.Signals(number).name + except ValueError: + return None + + +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, + encoding="utf-8", + errors="replace", + check=False, + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + ) + failure: dict[str, object] = { + "implementation": implementation, + "exit_code": completed.returncode, + "signal_number": None, + "signal": None, + } + if completed.returncode < 0: + 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}" + + ( + "; 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: + failure["message"] = ( + f"the {implementation} measurement failed with exit code " + f"{completed.returncode}; its error is on standard error" + ) + return None, failure + marked = [ + line[len(RESULT_PREFIX) :] + 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 + return json.loads(marked[-1]), None + + +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 ( + 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 _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[dict[str, object]], + identical: bool | None, +) -> str: + lines = [str(failure["message"]) for failure in failures] + if not results: + return "\n".join(lines) + first = results[0] + environment = first["environment"] + 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']} (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" + if first["rows_in_widest_leaf"] is not None + else "" + ), + ] + descriptions = {_array_description(result) for result in results} + if len(descriptions) == 1: + lines.append("leaf array: " + _array_description(first)) + for result in results: + 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']} ({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) + + +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", help="synthetic shape (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, + 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); 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( + "--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.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) + ) + 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.child is None: + from microcosm.fit.qrf import _DISCRETE_Y_UNIQUE_MAX + + distinct = len(np.unique(_donors(arguments)[1])) + if distinct < 2: + parser.error( + 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} 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 + + +def main(argv: list[str] | None = None) -> int: + arguments = _parse_arguments(argv) + if arguments.child is not None: + print(RESULT_PREFIX + json.dumps(_fit_in_this_process(arguments))) + return 0 + + implementations = ( + IMPLEMENTATIONS + if arguments.implementation == "both" + else (arguments.implementation,) + ) + results: list[dict[str, object]] = [] + failures: list[dict[str, object]] = [] + for implementation in implementations: + result, failure = _run_child(arguments, implementation) + if failure is not None: + failures.append(failure) + else: + 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, + }, + indent=2, + ) + ) + else: + print(_report(results, failures, identical)) + return 1 if failures or identical is False else 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" }, ]