From 94ff4a721bf575fd806338d569030eb5798494c2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 11:42:56 -0500 Subject: [PATCH 1/5] Score single-class folds and refuse weightless balanced classes out_of_fold_proba left each learner's rows at zero in a fold whose training rows hold a single class, since CategoricalClassifier fits no learner there; categorical_scores now refuses such rows. Those rows now take the model's probabilities, certainty of that class, which the model and the training folds' shares already gave. A learner no fold fitted still stays out of the result. _class_balanced_weights divided by each class's total weight and returned NaN weights for a class with none. It now refuses that class, or one whose total overflows, by name. The cross-fitted gate never reached it with such weights: it falls back to the in-sample gate (in_sample_weightless_fold) first. Valid input is unchanged: two differential workloads (772 arrays) match main and microcosm#1543 bit for bit. Co-Authored-By: Claude Opus 5.5 --- .../fit-fold-degenerate-classes.fixed.md | 4 + .../src/microcosm/fit/held_out.py | 35 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 18 +- .../shared/test_fold_degenerate_classes.py | 530 ++++++++++++++++++ 4 files changed, 582 insertions(+), 5 deletions(-) create mode 100644 changelog.d/fit-fold-degenerate-classes.fixed.md create mode 100644 packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py diff --git a/changelog.d/fit-fold-degenerate-classes.fixed.md b/changelog.d/fit-fold-degenerate-classes.fixed.md new file mode 100644 index 0000000000..c2fe2d52e4 --- /dev/null +++ b/changelog.d/fit-fold-degenerate-classes.fixed.md @@ -0,0 +1,4 @@ +Two fold-level cases in microcosm-fit no longer leave values that are not probabilities or weights. Output for every other input is unchanged: a differential run of a fixed workload through the old and new code matched in every value. + +- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model and the training folds' shares already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). Every array the function returns now scores. A learner that no fold fitted, as when the target holds one class, still stays out of the result. Folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows. +- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight, or weight whose total overflows. Before, it returned NaN weights (or zeros, for an overflow). A fit never reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, before it balances anything. diff --git a/packages/microcosm-fit/src/microcosm/fit/held_out.py b/packages/microcosm-fit/src/microcosm/fit/held_out.py index 80fcce09b9..315ee67627 100644 --- a/packages/microcosm-fit/src/microcosm/fit/held_out.py +++ b/packages/microcosm-fit/src/microcosm/fit/held_out.py @@ -79,6 +79,14 @@ def stratified_folds( With ``groups`` whole groups are dealt, each with the rarest class it contains, so rows that share a group are never split across folds. + + Once :func:`can_deal_folds` holds, every class sits in every fold when rows + are dealt. When groups are dealt, only the rarest class (the first in + sorted order, if several tie) is sure to: another class can sit in one + fold. Even so, with three or more folds every fold's training rows (the + other folds) hold two classes or more whenever ``labels`` do. With two + folds they may hold a single class, which :func:`out_of_fold_proba` + handles. """ labels = np.asarray(labels) return _qrf._stratified_folds( @@ -98,10 +106,22 @@ def out_of_fold_proba( """Out-of-fold class probabilities for every row of ``table``. Each fold's rows are scored by the model fitted on the other folds. The - result maps ``"model"`` to the model's probabilities, each fitted learner's - name (``"boosted"``, ``"spline_logit"``) to its own, and ``"marginal"`` to - the training folds' weighted class shares; ``"classes"`` holds the column - order, the sorted categories of ``table[target]``. + result maps ``"model"`` to the model's probabilities, each learner some + fold fitted (``"boosted"``, ``"spline_logit"``) to its own, and + ``"marginal"`` to the training folds' weighted class shares; + ``"classes"`` holds the column order, the sorted categories of + ``table[target]``. + + A fold whose training rows hold a single class fits no learner, and the + model gives that fold's rows the class with certainty, as the training + folds' shares do. Each learner's rows in that fold take the model's + probabilities, so every array holds a distribution in every row + (:func:`categorical_scores` takes each one), and the model, the learners + and the constant are scored on the same rows, differing only where a + learner was fitted. Folds from :func:`stratified_folds` after + :func:`can_deal_folds` reach this only when they deal whole groups into + exactly two folds. A learner that no fold fitted, as when + ``table[target]`` holds one class, stays out of the result. """ weights = np.asarray(weights, dtype=np.float64) folds = np.asarray(folds) @@ -116,6 +136,7 @@ def full(fitted_classes: np.ndarray, proba: np.ndarray) -> np.ndarray: result[:, np.searchsorted(classes, fitted_classes)] = proba return result + single_class = np.zeros(len(table), dtype=bool) for fold in np.unique(folds): train, test = folds != fold, folds == fold fitted = model.fit( @@ -123,6 +144,8 @@ def full(fitted_classes: np.ndarray, proba: np.ndarray) -> np.ndarray: ) scored = {"model": fitted.predict_proba(table.loc[test])} scored.update(fitted.component_proba(table.loc[test])) + if len(fitted.classes_) == 1: + single_class |= test shares = pd.Series(weights[train]).groupby(labels[train]).sum() shares = shares.reindex(classes, fill_value=0.0).to_numpy() for name, proba in scored.items(): @@ -130,6 +153,10 @@ def full(fitted_classes: np.ndarray, proba: np.ndarray) -> np.ndarray: out[name][test] = full(fitted.classes_, proba) out.setdefault("marginal", np.zeros((len(table), len(classes)))) out["marginal"][test] = shares / shares.sum() + if single_class.any(): + # No learner was fitted for these rows, so their rows are still zeros. + for name in out.keys() - {"classes", "model", "marginal"}: + out[name][single_class] = out["model"][single_class] return out diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 019d609906..a631f631f9 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -915,6 +915,15 @@ def _class_balanced_weights( A row keeps its weight relative to the rows of its own class. The result averages one, so the classifier's fit is on the scale of an unweighted one. + + :func:`_cross_fit_gate` calls this only once every fold's training rows + carry weight for every class (:func:`_folds_carry_every_class`); other + folds fall back to the in-sample gate (:attr:`GateOutcome.WEIGHTLESS_FOLD`). + + Raises: + ValueError: If a class's rows carry no weight, or weight whose total is + not finite, naming the class: dividing by that total would give its + rows NaN weights, or weights of zero. """ base = ( np.ones(len(labels), dtype=np.float64) @@ -924,7 +933,14 @@ def _class_balanced_weights( balanced = np.empty(len(labels), dtype=np.float64) for value in np.unique(labels): members = labels == value - balanced[members] = base[members] / base[members].sum() + total = base[members].sum() + if not (np.isfinite(total) and total > 0.0): + raise ValueError( + "Class-balanced weights need every class to carry a positive, " + f"finite total weight; class {value!s} carries {float(total)!r} " + "in these rows." + ) + balanced[members] = base[members] / total return balanced * (len(labels) / balanced.sum()) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py new file mode 100644 index 0000000000..29520ce675 --- /dev/null +++ b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py @@ -0,0 +1,530 @@ +"""Folds whose training rows are degenerate in a class: a single class, or a weightless one. + +``out_of_fold_proba`` fits the categorical model on each fold's training rows. +When those rows hold a single class the model fits no learner, and each +learner's rows in that fold used to stay at zero, which +``categorical_scores`` now refuses (microcosm#1543); before that it scored +them at the log-loss floor. Those rows now take the model's probabilities: +certainty of the one class, as the constant gives too. ``_class_balanced_weights`` +divides each class's weights by that class's total, so a class with no +weight gave NaN; it now refuses the class by name. The cross-fitted gate never +passed it such weights, because it falls back to the in-sample gate first +(``GateOutcome.WEIGHTLESS_FOLD``); the guards below pin that. + +The example tests that name a refusal or a filled row fail before the fixes; +the guards pass on both sides. The properties check that every array +``out_of_fold_proba`` returns is a distribution in every row, that the fix +moves only rows that were all zeros, that stratified folds over three or more +groups always leave two classes in every training fold, and that the balanced +weights keep the previous formula's bits wherever every class carries weight. +""" + +from __future__ import annotations + +import warnings +from unittest import mock + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, event, given, settings +from hypothesis import strategies as st + +from microcosm.fit import ( + BoostedClassifierSettings, + CategoricalClassifier, + GateCalibration, + GateOutcome, + RegimeGatedQRF, + can_deal_folds, + categorical_scores, + out_of_fold_proba, + qrf, + stratified_folds, +) +from microcosm.fit.qrf import _class_balanced_weights, _cross_fit_gate + +#: Cheap property runs: no fitting. +PROPERTY = settings( + max_examples=200, + deadline=None, + derandomize=True, + suppress_health_check=[HealthCheck.too_slow], +) + +#: Property runs whose every example fits classifiers on each fold. +FITTING_PROPERTY = settings( + max_examples=20, + deadline=None, + derandomize=True, + suppress_health_check=[HealthCheck.too_slow], +) + +#: A small classifier that fits any two-class table: no early-stopping split, +#: which needs two rows of every class. +SMALL = CategoricalClassifier( + boosted=BoostedClassifierSettings( + max_iter=10, min_samples_leaf=2, early_stopping=False + ) +) + +LEARNERS = ("boosted", "spline_logit") + + +def _previous_out_of_fold_proba( + model: CategoricalClassifier, + table: pd.DataFrame, + predictors: list[str], + target: str, + *, + weights: np.ndarray, + folds: np.ndarray, +) -> dict[str, np.ndarray]: + """``out_of_fold_proba`` as it stood before this fix, copied verbatim.""" + weights = np.asarray(weights, dtype=np.float64) + folds = np.asarray(folds) + if weights.shape != (len(table),) or folds.shape != (len(table),): + raise ValueError("weights and folds need one value per row.") + labels = table[target].to_numpy() + classes = np.unique(labels) + out: dict[str, np.ndarray] = {"classes": classes} + + def full(fitted_classes: np.ndarray, proba: np.ndarray) -> np.ndarray: + result = np.zeros((len(proba), len(classes))) + result[:, np.searchsorted(classes, fitted_classes)] = proba + return result + + for fold in np.unique(folds): + train, test = folds != fold, folds == fold + fitted = model.fit( + table.loc[train], predictors, [target], weights=weights[train] + ) + scored = {"model": fitted.predict_proba(table.loc[test])} + scored.update(fitted.component_proba(table.loc[test])) + shares = pd.Series(weights[train]).groupby(labels[train]).sum() + shares = shares.reindex(classes, fill_value=0.0).to_numpy() + for name, proba in scored.items(): + out.setdefault(name, np.zeros((len(table), len(classes)))) + out[name][test] = full(fitted.classes_, proba) + out.setdefault("marginal", np.zeros((len(table), len(classes)))) + out["marginal"][test] = shares / shares.sum() + return out + + +def _previous_class_balanced_weights( + labels: np.ndarray, weights: np.ndarray | None +) -> np.ndarray: + """``_class_balanced_weights`` as it stood before this fix, copied verbatim.""" + base = ( + np.ones(len(labels), dtype=np.float64) + if weights is None + else np.asarray(weights, dtype=np.float64) + ) + balanced = np.empty(len(labels), dtype=np.float64) + for value in np.unique(labels): + members = labels == value + balanced[members] = base[members] / base[members].sum() + return balanced * (len(labels) / balanced.sum()) + + +def _same_bits(a: np.ndarray, b: np.ndarray) -> bool: + """Equal dtype, shape and bytes; an object array (the class labels) compares by value.""" + if a.dtype != b.dtype or a.shape != b.shape: + return False + if a.dtype == object: + return a.tolist() == b.tolist() + return a.tobytes() == b.tobytes() + + +def _single_class_rows(labels: np.ndarray, folds: np.ndarray) -> np.ndarray: + """Rows in a fold whose training rows hold a single class.""" + rows = np.zeros(len(labels), dtype=bool) + for fold in np.unique(folds): + if len(np.unique(labels[folds != fold])) == 1: + rows |= folds == fold + return rows + + +def _assert_every_array_scores( + out: dict[str, np.ndarray], labels: np.ndarray, weights: np.ndarray +) -> None: + for name, proba in out.items(): + if name == "classes": + continue + assert proba.shape == (len(labels), len(out["classes"])) + assert ((proba >= 0.0) & (proba <= 1.0)).all(), name + np.testing.assert_allclose(proba.sum(axis=1), 1.0, atol=1e-9, err_msg=name) + categorical_scores(proba, labels, out["classes"], weights) + + +# --- out_of_fold_proba: a fold whose training rows hold a single class ------- + + +def _blocks() -> tuple[pd.DataFrame, np.ndarray]: + """Three folds of 20 rows; the third holds every ``b``, so its training rows hold only ``a``.""" + rng = np.random.default_rng(0) + n = 60 + table = pd.DataFrame( + {"x": rng.normal(size=n), "y": np.where(np.arange(n) < 40, "a", "b")} + ) + return table, np.repeat([0, 1, 2], 20) + + +def test_a_single_class_training_fold_gives_each_learner_the_models_rows() -> None: + """Each learner's rows in that fold were zeros, which the scorer refuses.""" + table, folds = _blocks() + weights = np.ones(len(table)) + out = out_of_fold_proba(SMALL, table, ["x"], "y", weights=weights, folds=folds) + assert set(out) == {"classes", "model", "marginal", *LEARNERS} + held = folds == 2 + certain_a = np.tile([1.0, 0.0], (int(held.sum()), 1)) + for name in ("model", "marginal", *LEARNERS): + np.testing.assert_array_equal(out[name][held], certain_a, err_msg=name) + _assert_every_array_scores(out, table["y"].to_numpy(), weights) + + +def test_two_grouped_folds_can_leave_a_training_fold_with_one_class() -> None: + """Households {a, b}, {a} and {b}: dealt into two folds, one fold's training rows hold only ``a``. + + Every class sits in two households, so ``can_deal_folds`` passes, and the + seed deals {a} alone into fold 1. + """ + rng = np.random.default_rng(3) + household = np.repeat([0, 0, 1, 2], 10) + labels = np.repeat(["a", "b", "a", "b"], 10) + table = pd.DataFrame({"x": rng.normal(size=40), "y": labels}) + assert can_deal_folds(labels, 2, groups=household) + folds = stratified_folds(labels, 2, np.random.default_rng(0), groups=household) + assert set(labels[folds == 1]) == {"a"} + weights = rng.uniform(0.5, 2.0, 40) + out = out_of_fold_proba(SMALL, table, ["x"], "y", weights=weights, folds=folds) + assert set(out) == {"classes", "model", "marginal", *LEARNERS} + _assert_every_array_scores(out, labels, weights) + + +def test_a_learner_no_fold_fitted_stays_out() -> None: + """Guard: a target with one class, or folds that each hold one class, fit no learner. + + The UK APS stage pools a learner only where every major group fitted it, + and a group with a single sub-major group fits neither, so these keep + their old output. + """ + rng = np.random.default_rng(5) + x = rng.normal(size=40) + weights = np.ones(40) + one_class = pd.DataFrame({"x": x, "y": "a"}) + out = out_of_fold_proba( + SMALL, one_class, ["x"], "y", weights=weights, folds=np.arange(40) % 4 + ) + assert set(out) == {"classes", "model", "marginal"} + _assert_every_array_scores(out, one_class["y"].to_numpy(), weights) + + split = pd.DataFrame({"x": x, "y": np.repeat(["a", "b"], 20)}) + folds = np.repeat([0, 1], 20) + out = out_of_fold_proba(SMALL, split, ["x"], "y", weights=weights, folds=folds) + assert set(out) == {"classes", "model", "marginal"} + _assert_every_array_scores(out, split["y"].to_numpy(), weights) + + +def test_folds_that_each_keep_two_classes_are_unchanged() -> None: + """Guard: with every training fold holding two classes, the output is the previous one, bit for bit.""" + rng = np.random.default_rng(1) + n = 120 + x = rng.normal(size=n) + table = pd.DataFrame( + {"x": x, "y": np.where(x + rng.normal(0, 0.7, n) > 0, "up", "down")} + ) + weights = rng.uniform(0.5, 2.0, n) + folds = stratified_folds(table["y"].to_numpy(), 5, np.random.default_rng(2)) + model = CategoricalClassifier(boosted=BoostedClassifierSettings(max_iter=20)) + new = out_of_fold_proba(model, table, ["x"], "y", weights=weights, folds=folds) + old = _previous_out_of_fold_proba( + model, table, ["x"], "y", weights=weights, folds=folds + ) + assert list(new) == list(old) + for name in new: + assert _same_bits(new[name], old[name]), name + + +@st.composite +def _fold_tables(draw): + """Small tables with two or three classes and two to four folds. + + A third of the draws deal folds at random; the rest put every row of the + classes after the first into one fold, so that fold's training rows hold + a single class. + """ + n = draw(st.integers(12, 36)) + n_classes = draw(st.integers(2, 3)) + n_folds = draw(st.integers(2, 4)) + seed = draw(st.integers(0, 2**32 - 1)) + rng = np.random.default_rng(seed) + codes = np.r_[np.arange(n_classes), rng.integers(0, n_classes, n - n_classes)] + rng.shuffle(codes) + labels = np.array(["c0", "c1", "c2"])[codes] + if draw(st.sampled_from(["random", "confined", "confined"])) == "random": + folds = rng.integers(0, n_folds, n) + folds[:n_folds] = np.arange(n_folds) + else: + held = draw(st.integers(0, n_folds - 1)) + folds = np.where(codes == 0, rng.integers(0, n_folds, n), held) + folds[np.flatnonzero(codes == 0)[:1]] = (held + 1) % n_folds + table = pd.DataFrame({"x": rng.normal(size=n), "z": rng.normal(size=n)}) + table["y"] = labels + weights = rng.uniform(0.25, 4.0, n) + boosted_weight = draw(st.sampled_from([0.0, 0.5, 1.0])) + return table, folds, weights, boosted_weight + + +@FITTING_PROPERTY +@given(case=_fold_tables()) +def test_every_array_is_a_distribution_and_only_zero_rows_move(case) -> None: + """Every array scores, and the fix moves only learner rows that were all zeros. + + Every other row keeps the previous implementation's bits, and the moved + rows equal the model's. + """ + table, folds, weights, boosted_weight = case + model = CategoricalClassifier( + boosted_weight=boosted_weight, + boosted=BoostedClassifierSettings( + max_iter=10, min_samples_leaf=2, early_stopping=False + ), + ) + labels = table["y"].to_numpy() + new = out_of_fold_proba(model, table, ["x", "z"], "y", weights=weights, folds=folds) + old = _previous_out_of_fold_proba( + model, table, ["x", "z"], "y", weights=weights, folds=folds + ) + _assert_every_array_scores(new, labels, weights) + assert set(new) == set(old) + moved = _single_class_rows(labels, folds) + event("a single-class training fold" if moved.any() else "no single-class fold") + for name in new: + if name == "classes": + assert _same_bits(new[name], old[name]) + continue + assert _same_bits(new[name][~moved], old[name][~moved]), name + if name in LEARNERS: + assert not old[name][moved].any(), name + np.testing.assert_array_equal(new[name][moved], new["model"][moved]) + else: + assert _same_bits(new[name][moved], old[name][moved]), name + expected = {"classes", "model", "marginal"} + if not moved.all(): + expected |= {"boosted"} if boosted_weight > 0 else set() + expected |= {"spline_logit"} if boosted_weight < 1 else set() + assert set(new) == expected + + +@st.composite +def _households(draw): + """Households of one to four members, each class in at least ``folds`` of them.""" + folds = draw(st.integers(2, 6)) + n_classes = draw(st.integers(2, 4)) + members = draw( + st.lists( + st.lists(st.integers(0, n_classes - 1), min_size=1, max_size=4), + min_size=folds, + max_size=14, + ) + ) + for value in range(n_classes): + lacking = [m for m in members if value not in m] + short = folds - (len(members) - len(lacking)) + for household in lacking[: max(short, 0)]: + household.append(value) + labels = np.array([value for m in members for value in m]) + groups = np.array([g for g, m in enumerate(members) for _ in m]) + seed = draw(st.integers(0, 2**32 - 1)) + return labels, groups, folds, seed + + +@PROPERTY +@given(case=_households()) +def test_three_or_more_grouped_folds_keep_two_classes_in_every_training_fold( + case, +) -> None: + """With three or more folds no training fold holds a single class; with two one may. + + Dealt by row, every class sits in every fold. Dealt by household, the + rarest class sits in every fold, so a training fold with one class holds + only it, and the next rarest class would have to sit wholly in the held-out + fold. Counting households, that needs exactly two folds. The UK SPI stage + deals households into five. + """ + labels, groups, folds, seed = case + assert can_deal_folds(labels, folds, groups=groups) + by_row = stratified_folds(labels, folds, np.random.default_rng(seed)) + for fold in range(folds): + assert set(labels[by_row == fold]) == set(labels) + by_group = stratified_folds( + labels, folds, np.random.default_rng(seed), groups=groups + ) + assert (pd.Series(by_group).groupby(groups).nunique() == 1).all() + if folds >= 3: + for fold in range(folds): + assert len(np.unique(labels[by_group != fold])) >= 2 + + +# --- _class_balanced_weights: a class with no weight ------------------------- + + +def test_balanced_weights_refuse_a_class_with_no_weight_by_name() -> None: + """It divided by the class's total weight and returned NaN weights.""" + labels = np.array([0, 0, 1, 1]) + with pytest.raises(ValueError, match=r"class 1 carries 0\.0"): + _class_balanced_weights(labels, np.array([1.0, 1.0, 0.0, 0.0])) + with pytest.raises(ValueError, match="class -1 carries 0.0"): + _class_balanced_weights(np.array([-1, 0, 1]), np.array([0.0, 2.0, 1.0])) + + +@pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning") +def test_balanced_weights_refuse_a_class_whose_total_overflows() -> None: + """Its total was infinite, so dividing by it gave every row of the class zero weight.""" + labels = np.array([0, 0, 1, 1]) + weights = np.array([1e308, 1e308, 1.0, 1.0]) + with pytest.raises(ValueError, match="class 0 carries inf"): + _class_balanced_weights(labels, weights) + + +@st.composite +def _labelled_weights(draw): + n = draw(st.integers(1, 30)) + labels = np.asarray( + draw(st.lists(st.sampled_from([-1, 0, 1]), min_size=n, max_size=n)) + ) + if draw(st.booleans()): + return labels, None + weight = st.one_of(st.just(0.0), st.floats(1e-6, 1e6)) + return labels, np.asarray(draw(st.lists(weight, min_size=n, max_size=n))) + + +@PROPERTY +@given(case=_labelled_weights()) +def test_balanced_weights_keep_their_bits_and_refuse_exactly_the_weightless( + case, +) -> None: + """Where every class carries weight the result is the previous one, bit for bit. + + Otherwise the helper refuses, naming a class with no weight. + """ + labels, weights = case + base = np.ones(len(labels)) if weights is None else weights + totals = {int(v): base[labels == v].sum() for v in np.unique(labels)} + weightless = [v for v, total in totals.items() if not total > 0.0] + event("a weightless class" if weightless else "every class weighted") + if weightless: + with pytest.raises(ValueError, match="carries 0.0") as raised: + _class_balanced_weights(labels, weights) + assert f"class {weightless[0]} carries" in str(raised.value) + return + with warnings.catch_warnings(): + warnings.simplefilter("error") + balanced = _class_balanced_weights(labels, weights) + previous = _previous_class_balanced_weights(labels, weights) + assert _same_bits(balanced, previous) + class_totals = [balanced[labels == v].sum() for v in totals] + np.testing.assert_allclose(class_totals, class_totals[0], rtol=1e-9) + np.testing.assert_allclose(balanced.mean(), 1.0, rtol=1e-9) + + +def _one_weighted_positive(n: int = 200, positives: int = 30) -> pd.DataFrame: + """A zero-inflated target whose positive sign carries weight on a single row.""" + rng = np.random.default_rng(9) + x = rng.normal(size=n) + positive = np.zeros(n, dtype=bool) + positive[rng.choice(n, size=positives, replace=False)] = True + weight = np.where(positive, 0.0, 1.0) + weight[np.flatnonzero(positive)[0]] = 1.0 + return pd.DataFrame( + { + "x": x, + "target": np.where(positive, rng.lognormal(1.0, 0.5, n), 0.0), + "weight": weight, + } + ) + + +def test_a_sign_weighted_on_one_row_falls_back_to_the_in_sample_gate() -> None: + """Guard: the balanced gate never divides by a fold's missing weight. + + The positive sign carries weight overall, but the fold holding its one + weighted row trains on none, so the fit takes the in-sample gate before + any weights are balanced. + """ + table = _one_weighted_positive() + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + fitted = RegimeGatedQRF( + n_estimators=4, + seed=5, + gate_calibration=GateCalibration.CROSS_FITTED_BALANCED, + ).fit(table, ["x"], ["target"], weights="weight") + assert fitted.gate_outcomes() == {"target": GateOutcome.WEIGHTLESS_FOLD} + + +@st.composite +def _gate_cases(draw): + """Two or three sign classes, each with at least five rows, and weights that are often zero.""" + n_classes = draw(st.integers(2, 3)) + sizes = draw(st.lists(st.integers(5, 14), min_size=n_classes, max_size=n_classes)) + labels = np.repeat(np.arange(n_classes) - (n_classes == 3), sizes) + zero_share = draw(st.sampled_from([0.0, 0.5, 0.9, 0.9])) + seed = draw(st.integers(0, 2**31 - 2)) + rng = np.random.default_rng(seed) + weights = np.where( + rng.uniform(size=len(labels)) < zero_share, + 0.0, + rng.choice([0.5, 1.0, 3.0], size=len(labels)), + ) + for value in np.unique(labels): + if not weights[labels == value].any(): + weights[np.flatnonzero(labels == value)[0]] = 1.0 + x = rng.normal(size=(len(labels), 2)) + x[:, 0] += labels + return x, labels, weights, seed + + +@FITTING_PROPERTY +@given(case=_gate_cases()) +def test_a_cross_fit_balances_only_folds_that_carry_every_class(case) -> None: + """Guard: the balanced gate meets a weightless class only as a fallback. + + Where some fold's training rows carry no weight for a class, the gate + falls back before balancing anything; otherwise every class it balances + carries weight. + """ + features, labels, weights, seed = case + fold_stream, _ = np.random.SeedSequence(seed).spawn(2) + folds = qrf._stratified_folds( + labels, qrf._GATE_CROSS_FIT_FOLDS, np.random.default_rng(fold_stream) + ) + weightless = any( + not weights[(folds != fold) & (labels == value)].sum() > 0.0 + for fold in range(qrf._GATE_CROSS_FIT_FOLDS) + for value in np.unique(labels) + ) + event("a weightless fold" if weightless else "every fold weighted") + totals: list[float] = [] + + def recording(fold_labels, fold_weights): + totals.extend( + float(fold_weights[fold_labels == value].sum()) + for value in np.unique(fold_labels) + ) + return _class_balanced_weights(fold_labels, fold_weights) + + with mock.patch.object(qrf, "_class_balanced_weights", recording): + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + gate, outcome = _cross_fit_gate( + features, labels, weights, seed, balanced=True + ) + if weightless: + assert (gate, outcome) == (None, GateOutcome.WEIGHTLESS_FOLD) + assert totals == [] + else: + assert outcome != GateOutcome.WEIGHTLESS_FOLD + assert len(totals) == qrf._GATE_CROSS_FIT_FOLDS * len(np.unique(labels)) + assert min(totals) > 0.0 From b90f098fb7826d2615469a79809eefc7bf51f4c7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 11:48:05 -0500 Subject: [PATCH 2/5] Repin the attested fit.qrf hashes microcosm.build.spec_engine.seeds attests microcosm.fit.qrf's source bytes. Repinned with tools/repin_us_spec_engine_contracts.py and tools/spec_engine_coverage.py (41/41 inventory checks, 42,394/42,394 fields, --check clean), then python -m tools.graph_parity_repin fit.qrf, which writes only when the local direct call's bytes are 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 +- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index eeaed4eb6b..e2121dfd73 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": "31604a3481bcdad4db5cfd7a0f159c60c1806a2eb3a1ff0514a47af2940ad5ec", - "protocol_sha256": "7114ba07023642223fb227794bb5fa567e571431dd5cfedd1a7cd27a4dee7b85" + "map_sha256": "2de5b5eed504179a521c380a077a3c99a92bbfb95a286b7ec03a2a02003ea295", + "protocol_sha256": "a61c7cf2a2ad6c9d030e81589e5f7ac0c8e4bdd1582aee4f19985d2f202e641d" }, "failures": [], "observed": { - "map_sha256": "31604a3481bcdad4db5cfd7a0f159c60c1806a2eb3a1ff0514a47af2940ad5ec", - "protocol_sha256": "7114ba07023642223fb227794bb5fa567e571431dd5cfedd1a7cd27a4dee7b85" + "map_sha256": "2de5b5eed504179a521c380a077a3c99a92bbfb95a286b7ec03a2a02003ea295", + "protocol_sha256": "a61c7cf2a2ad6c9d030e81589e5f7ac0c8e4bdd1582aee4f19985d2f202e641d" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "7114ba07023642223fb227794bb5fa567e571431dd5cfedd1a7cd27a4dee7b85", + "implementation_sha256": "a61c7cf2a2ad6c9d030e81589e5f7ac0c8e4bdd1582aee4f19985d2f202e641d", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "7114ba07023642223fb227794bb5fa567e571431dd5cfedd1a7cd27a4dee7b85", + "implementation_sha256": "a61c7cf2a2ad6c9d030e81589e5f7ac0c8e4bdd1582aee4f19985d2f202e641d", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "08f7aba00538da1b0a707c1130e870a540e1376872afe3d22749c9ddc9c32fb0" + "spec_sha256": "2de1b843564c587c9b4bf5f35fe24264daedc3331f000f3edf4cd0ba72224e42" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "08f7aba00538da1b0a707c1130e870a540e1376872afe3d22749c9ddc9c32fb0" + "spec_sha256": "2de1b843564c587c9b4bf5f35fe24264daedc3331f000f3edf4cd0ba72224e42" }, "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 fcccd68ce9..75ffaaed85 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 @@ -383,8 +383,8 @@ # The hierarchy value ranks move both again: medicaid_take_up, an # attested kernel module, gives a substituted enrollment spec's value no # rank. No draw, RNG rule or QRF target changes. - "seed_map": "31604a3481bcdad4db5cfd7a0f159c60c1806a2eb3a1ff0514a47af2940ad5ec", - "seed_protocol": "7114ba07023642223fb227794bb5fa567e571431dd5cfedd1a7cd27a4dee7b85", + "seed_map": '2de5b5eed504179a521c380a077a3c99a92bbfb95a286b7ec03a2a02003ea295', + "seed_protocol": 'a61c7cf2a2ad6c9d030e81589e5f7ac0c8e4bdd1582aee4f19985d2f202e641d', "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 d899b2bb89..fe5a53e040 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 @@ -27,7 +27,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The hierarchy value ranks move medicaid_take_up's attested bytes. # The fit input checks from the microimpute bug-parity audit move them too. assert first.spec_sha256 == ( - "e0968e372cedaedea6ed257e6c33f52542b64f1c4b3aa2a8acc3cfd2f2ffdafa" + '85dc3afa338a0b53d5a5d07ed410826dbfe64f5d028c0b40f732c37087286ccc' ) 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 c649d45720..46ad82bf1d 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 @@ -355,7 +355,7 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "08f7aba00538da1b0a707c1130e870a540e1376872afe3d22749c9ddc9c32fb0", + "spec_sha256": '2de1b843564c587c9b4bf5f35fe24264daedc3331f000f3edf4cd0ba72224e42', }, } 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 0465e3c82a..19ce7723dd 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":"45b97e240454495ea3511607d267d06fc96510dc3eea96effa328e8b83ba49a0","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"3051e95dfbb04c084de0c30b5ba9620791efbc94fde92a6896d0ca7f2d143322","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"3051e95dfbb04c084de0c30b5ba9620791efbc94fde92a6896d0ca7f2d143322"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"37da2f51c90983fbb345f60318daf21fe4d34134757807d2d0eeb368c629c403"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"70bcc970f4cadad15e6ae9376080e0cbb01cb0ebd5ced65444e7246ce75070a3"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"642a0c433c2426c0de5d104a9c0f320ae46d682828c0e42501fc817f75badf70","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"042948ba95d52a550eba31ac28f615d537a1c791b61722c8d1c05fecd1ff4f33","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"042948ba95d52a550eba31ac28f615d537a1c791b61722c8d1c05fecd1ff4f33"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"41c572c0b5d43fbc56594da0eeb90c8b4e9f17e2348de863c26ab65e722b64b0"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"235a12bc63b6df1fa8a8500fea1696e7e2fcbdcf65ecead77ea49f44278da732"}},"seed":947} From f3b489a1bc74897d23def132e5688647f54f95bf Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 14:33:57 -0500 Subject: [PATCH 3/5] Refuse only weightless balanced classes; strengthen the fold tests An in-session pre-review found that a fit does reach _class_balanced_weights with a class whose weight total overflows to infinity. Each weight is finite, so the fit's weight checks take it, and _folds_carry_every_class counts inf as weight. Main completes that fit (cross_fitted_class_rates). 94ff4a721 made it raise, and its message, the changelog and the PR body said no fit reached the refusal. The brief says not to change any fit whose classes all carry weight, so the helper now refuses only a total that is not positive: the test _folds_carry_every_class runs on the same totals first, so no fit meets the refusal. Guards pin an overflowing class in the helper and in a full fit against the previous helper, bit for bit; both fail on b90f098fb. Tests: - The grouped-folds property checks that the rarest class sits in every fold. It draws households at the can_deal_folds bound, with boundary examples. A dealing by the commonest class and a random dealing now fail it; both passed before. - The out_of_fold_proba property gains examples for the boosted-only and spline-only models on a single-class fold, and for folds that each hold one class. Wording: - The whole gate falls back, not "other folds". - The reach claim holds for targets with two classes or more. - Every array holds a distribution in every row a fold scores. - The scorer's zero-row hint no longer names a cause out_of_fold_proba removed. Repinned the attested fit.qrf hashes: tools/repin_us_spec_engine_contracts.py, tools/spec_engine_coverage.py (41/41 inventory checks), the repin again, --check clean, then python -m tools.graph_parity_repin fit.qrf. ruff format restores the double quotes the repin tool drops. Co-Authored-By: Claude Opus 5.5 --- .../fit-fold-degenerate-classes.fixed.md | 4 +- 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 +- .../src/microcosm/fit/held_out.py | 18 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 21 +- .../shared/test_fold_degenerate_classes.py | 225 ++++++++++++++---- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- 9 files changed, 216 insertions(+), 78 deletions(-) diff --git a/changelog.d/fit-fold-degenerate-classes.fixed.md b/changelog.d/fit-fold-degenerate-classes.fixed.md index c2fe2d52e4..2fd47ae8cf 100644 --- a/changelog.d/fit-fold-degenerate-classes.fixed.md +++ b/changelog.d/fit-fold-degenerate-classes.fixed.md @@ -1,4 +1,4 @@ Two fold-level cases in microcosm-fit no longer leave values that are not probabilities or weights. Output for every other input is unchanged: a differential run of a fixed workload through the old and new code matched in every value. -- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model and the training folds' shares already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). Every array the function returns now scores. A learner that no fold fitted, as when the target holds one class, still stays out of the result. Folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows. -- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight, or weight whose total overflows. Before, it returned NaN weights (or zeros, for an overflow). A fit never reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, before it balances anything. +- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model and the training folds' shares already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). Each learner's array now scores wherever the model's does. A learner that no fold fitted, as when the target holds one class, still stays out of the result. For a target with two classes or more, folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows. +- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight. Before, it divided by that zero total and returned NaN weights. No fit reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, testing the same totals before it balances anything. A class whose total overflows to infinity still counts as carrying weight, and its rows still weigh zero, as before. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index ffdbd7151c..4cbcd3143f 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": "8356c939c63992cdda1642fc76bde71b2074ccd412e5cdb64d79e03bb38f2dc9", - "protocol_sha256": "bc60564662d9757d90d11601b9c5121e595d39325afa8929691ef5298bc70d0c" + "map_sha256": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", + "protocol_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37" }, "failures": [], "observed": { - "map_sha256": "8356c939c63992cdda1642fc76bde71b2074ccd412e5cdb64d79e03bb38f2dc9", - "protocol_sha256": "bc60564662d9757d90d11601b9c5121e595d39325afa8929691ef5298bc70d0c" + "map_sha256": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", + "protocol_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "bc60564662d9757d90d11601b9c5121e595d39325afa8929691ef5298bc70d0c", + "implementation_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "bc60564662d9757d90d11601b9c5121e595d39325afa8929691ef5298bc70d0c", + "implementation_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "2cc7a8122da956d265c6fb10fdb23e44afe36e9c69395abb30826c5563f211e2" + "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "2cc7a8122da956d265c6fb10fdb23e44afe36e9c69395abb30826c5563f211e2" + "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364" }, "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 87e30bc3c1..8d121c4644 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 @@ -393,8 +393,8 @@ # move both again; no valid input's draw changes. microcosm#1617's refusal # of a weightless class in the balanced gate's weights moves both again; # no fit reached it, and no draw changes. - "seed_map": "8356c939c63992cdda1642fc76bde71b2074ccd412e5cdb64d79e03bb38f2dc9", - "seed_protocol": "bc60564662d9757d90d11601b9c5121e595d39325afa8929691ef5298bc70d0c", + "seed_map": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", + "seed_protocol": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", "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 7a988428aa..ef8c0bff41 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 @@ -27,7 +27,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The hierarchy value ranks move medicaid_take_up's attested bytes. # The fit input checks from the microimpute bug-parity audit move them too. assert first.spec_sha256 == ( - "b08bf6ff0e97ae7fc06507f0c80ab3afd5d7bab6a1a1d6f0b85ca416d6a12ad8" + "d2c56d56aed52af2f5dd12078ebbf3a673bcdcaeeae03d69ab9e5c46a7cf69c6" ) 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 3a7b49a3a6..7daa7736db 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 @@ -355,7 +355,7 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "2cc7a8122da956d265c6fb10fdb23e44afe36e9c69395abb30826c5563f211e2", + "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/held_out.py b/packages/microcosm-fit/src/microcosm/fit/held_out.py index 315ee67627..399981d05e 100644 --- a/packages/microcosm-fit/src/microcosm/fit/held_out.py +++ b/packages/microcosm-fit/src/microcosm/fit/held_out.py @@ -115,13 +115,14 @@ def out_of_fold_proba( A fold whose training rows hold a single class fits no learner, and the model gives that fold's rows the class with certainty, as the training folds' shares do. Each learner's rows in that fold take the model's - probabilities, so every array holds a distribution in every row - (:func:`categorical_scores` takes each one), and the model, the learners - and the constant are scored on the same rows, differing only where a - learner was fitted. Folds from :func:`stratified_folds` after - :func:`can_deal_folds` reach this only when they deal whole groups into - exactly two folds. A learner that no fold fitted, as when - ``table[target]`` holds one class, stays out of the result. + probabilities, so every array holds a distribution in every row a fold + scores (:func:`categorical_scores` takes each one), and the model, the + learners and the constant are scored on the same rows, differing only + where a learner was fitted. When ``table[target]`` holds two classes or + more, folds from :func:`stratified_folds` after :func:`can_deal_folds` + reach this only when they deal whole groups into exactly two folds. A + learner that no fold fitted, as when ``table[target]`` holds one class, + stays out of the result. """ weights = np.asarray(weights, dtype=np.float64) folds = np.asarray(folds) @@ -219,8 +220,7 @@ def _scored_inputs( raise ValueError( f"{int(off.sum())} row(s) of proba do not sum to 1 (within " f"{PROBABILITY_SUM_TOLERANCE:g}); each row must be a distribution " - "over the classes. A row of zeros usually means a learner was not " - "fitted for that row's fold." + "over the classes. A row of zeros means nothing scored that row." ) if w.shape != (n,): raise ValueError(f"weights need one value per label ({n}), got {w.shape}.") diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index a631f631f9..64c460c61c 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -917,13 +917,16 @@ def _class_balanced_weights( averages one, so the classifier's fit is on the scale of an unweighted one. :func:`_cross_fit_gate` calls this only once every fold's training rows - carry weight for every class (:func:`_folds_carry_every_class`); other - folds fall back to the in-sample gate (:attr:`GateOutcome.WEIGHTLESS_FOLD`). + carry weight for every class (:func:`_folds_carry_every_class`, the same + test on the same totals); otherwise the whole gate falls back to the + in-sample gate (:attr:`GateOutcome.WEIGHTLESS_FOLD`), so no fit meets the + refusal below. A class whose total overflows to infinity does carry + weight: its rows weigh zero here, and a fit can reach that. Raises: - ValueError: If a class's rows carry no weight, or weight whose total is - not finite, naming the class: dividing by that total would give its - rows NaN weights, or weights of zero. + ValueError: If a class's rows carry no weight (a total that is not + positive), naming the class: dividing by that total would give its + rows NaN weights. """ base = ( np.ones(len(labels), dtype=np.float64) @@ -934,11 +937,11 @@ def _class_balanced_weights( for value in np.unique(labels): members = labels == value total = base[members].sum() - if not (np.isfinite(total) and total > 0.0): + if not total > 0.0: raise ValueError( - "Class-balanced weights need every class to carry a positive, " - f"finite total weight; class {value!s} carries {float(total)!r} " - "in these rows." + "Class-balanced weights need every class to carry positive " + f"total weight; class {value!s} carries {float(total)!r} in " + "these rows." ) balanced[members] = base[members] / total return balanced * (len(labels) / balanced.sum()) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py index 29520ce675..e3f76e6770 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py @@ -9,25 +9,30 @@ divides each class's weights by that class's total, so a class with no weight gave NaN; it now refuses the class by name. The cross-fitted gate never passed it such weights, because it falls back to the in-sample gate first -(``GateOutcome.WEIGHTLESS_FOLD``); the guards below pin that. +(``GateOutcome.WEIGHTLESS_FOLD``), testing the same totals; the guards below +pin that. A class whose total overflows to infinity does carry weight, so a +fit can pass it to the helper; the helper leaves it as it was (its rows weigh +zero), and a guard pins that such a fit is unchanged. The example tests that name a refusal or a filled row fail before the fixes; the guards pass on both sides. The properties check that every array ``out_of_fold_proba`` returns is a distribution in every row, that the fix -moves only rows that were all zeros, that stratified folds over three or more -groups always leave two classes in every training fold, and that the balanced -weights keep the previous formula's bits wherever every class carries weight. +moves only rows that were all zeros, that folds dealt by household put the +rarest class in every fold and, with three or more folds, leave two classes in +every training fold, and that the balanced weights keep the previous formula's +bits wherever no class is weightless. """ from __future__ import annotations +import contextlib import warnings from unittest import mock import numpy as np import pandas as pd import pytest -from hypothesis import HealthCheck, event, given, settings +from hypothesis import HealthCheck, event, example, given, settings from hypothesis import strategies as st from microcosm.fit import ( @@ -246,13 +251,32 @@ def test_folds_that_each_keep_two_classes_are_unchanged() -> None: assert _same_bits(new[name], old[name]), name +def _fold_example( + codes: list[int], folds: list[int], boosted_weight: float +) -> tuple[pd.DataFrame, np.ndarray, np.ndarray, float]: + """A ``_fold_tables`` case with the given class codes and folds.""" + rng = np.random.default_rng(0) + n = len(codes) + table = pd.DataFrame({"x": rng.normal(size=n), "z": rng.normal(size=n)}) + table["y"] = np.array(["c0", "c1", "c2"])[codes] + return table, np.asarray(folds), rng.uniform(0.25, 4.0, n), boosted_weight + + +#: Six ``c0`` rows over three folds and six ``c1`` rows in the third, whose +#: training rows then hold only ``c0``. +_CONFINED = ([0] * 6 + [1] * 6, [0, 1, 2] * 2 + [2] * 6) +#: Each class in a fold of its own: every training fold holds one class. +_SEPARATED = ([0] * 6 + [1] * 6, [0] * 6 + [1] * 6) + + @st.composite def _fold_tables(draw): """Small tables with two or three classes and two to four folds. - A third of the draws deal folds at random; the rest put every row of the - classes after the first into one fold, so that fold's training rows hold - a single class. + ``confined`` draws put every row of the classes after the first into one + fold, so that fold's training rows hold a single class; ``random`` draws + deal folds at random. The property's examples add a confined fold for the + boosted-only and spline-only models, and folds that each hold one class. """ n = draw(st.integers(12, 36)) n_classes = draw(st.integers(2, 3)) @@ -262,7 +286,7 @@ def _fold_tables(draw): codes = np.r_[np.arange(n_classes), rng.integers(0, n_classes, n - n_classes)] rng.shuffle(codes) labels = np.array(["c0", "c1", "c2"])[codes] - if draw(st.sampled_from(["random", "confined", "confined"])) == "random": + if draw(st.sampled_from(["confined", "random"])) == "random": folds = rng.integers(0, n_folds, n) folds[:n_folds] = np.arange(n_folds) else: @@ -272,12 +296,15 @@ def _fold_tables(draw): table = pd.DataFrame({"x": rng.normal(size=n), "z": rng.normal(size=n)}) table["y"] = labels weights = rng.uniform(0.25, 4.0, n) - boosted_weight = draw(st.sampled_from([0.0, 0.5, 1.0])) + boosted_weight = draw(st.sampled_from([0.5, 0.0, 1.0])) return table, folds, weights, boosted_weight @FITTING_PROPERTY @given(case=_fold_tables()) +@example(case=_fold_example(*_CONFINED, boosted_weight=1.0)) +@example(case=_fold_example(*_CONFINED, boosted_weight=0.0)) +@example(case=_fold_example(*_SEPARATED, boosted_weight=0.5)) def test_every_array_is_a_distribution_and_only_zero_rows_move(case) -> None: """Every array scores, and the fix moves only learner rows that were all zeros. @@ -299,7 +326,12 @@ def test_every_array_is_a_distribution_and_only_zero_rows_move(case) -> None: _assert_every_array_scores(new, labels, weights) assert set(new) == set(old) moved = _single_class_rows(labels, folds) - event("a single-class training fold" if moved.any() else "no single-class fold") + if moved.all(): + event("every training fold holds one class") + elif moved.any(): + event(f"a single-class training fold, boosted_weight={boosted_weight}") + else: + event("no single-class fold") for name in new: if name == "classes": assert _same_bits(new[name], old[name]) @@ -317,41 +349,77 @@ def test_every_array_is_a_distribution_and_only_zero_rows_move(case) -> None: assert set(new) == expected +def _household_case( + members: list[list[int]], folds: int, seed: int +) -> tuple[np.ndarray, np.ndarray, int, int]: + """Row labels and household codes for households holding the given classes.""" + labels = np.array([value for m in members for value in m]) + groups = np.array([g for g, m in enumerate(members) for _ in m]) + return labels, groups, folds, seed + + @st.composite def _households(draw): - """Households of one to four members, each class in at least ``folds`` of them.""" + """Households, each class in at least ``folds`` of them, often exactly that many. + + ``singletons`` gives each class ``folds`` or ``folds + 1`` households of + one member, so a dealing that ignores the classes can leave a fold without + one. ``paired`` puts class 0 into ``folds`` households beside class 1 and + adds households of class 1 alone, so a dealing by any class but the rarest + can crowd class 0 into fewer folds. ``mixed`` draws households of one to + four members. + """ folds = draw(st.integers(2, 6)) n_classes = draw(st.integers(2, 4)) - members = draw( - st.lists( - st.lists(st.integers(0, n_classes - 1), min_size=1, max_size=4), - min_size=folds, - max_size=14, + shape = draw(st.sampled_from(["singletons", "paired", "mixed"])) + if shape == "singletons": + members = [ + [value] + for value in range(n_classes) + for _ in range(folds + draw(st.integers(0, 1))) + ] + elif shape == "paired": + members = [[0, 1] for _ in range(folds)] + members += [[1] for _ in range(draw(st.integers(1, 2 * folds)))] + else: + members = draw( + st.lists( + st.lists(st.integers(0, n_classes - 1), min_size=1, max_size=4), + min_size=folds, + max_size=14, + ) ) - ) for value in range(n_classes): lacking = [m for m in members if value not in m] short = folds - (len(members) - len(lacking)) for household in lacking[: max(short, 0)]: household.append(value) - labels = np.array([value for m in members for value in m]) - groups = np.array([g for g, m in enumerate(members) for _ in m]) - seed = draw(st.integers(0, 2**32 - 1)) - return labels, groups, folds, seed + order = draw(st.permutations(range(len(members)))) + members = [members[i] for i in order] + return _household_case(members, folds, draw(st.integers(0, 2**32 - 1))) @PROPERTY @given(case=_households()) -def test_three_or_more_grouped_folds_keep_two_classes_in_every_training_fold( - case, -) -> None: - """With three or more folds no training fold holds a single class; with two one may. - - Dealt by row, every class sits in every fold. Dealt by household, the - rarest class sits in every fold, so a training fold with one class holds - only it, and the next rarest class would have to sit wholly in the held-out - fold. Counting households, that needs exactly two folds. The UK SPI stage - deals households into five. +@example(case=_household_case([[0]] * 3 + [[1]] * 3, folds=3, seed=0)) +@example(case=_household_case([[0, 1]] * 3 + [[1]] * 4, folds=3, seed=0)) +@example(case=_household_case([[0, 1]] * 3, folds=3, seed=4)) +@example(case=_household_case([[0, 1], [0], [1]], folds=2, seed=0)) +def test_grouped_folds_put_the_rarest_class_in_every_fold(case) -> None: + """Dealt by household, the rarest class sits in every fold; with three or more folds no training fold holds one class. + + Dealt by row, every class sits in every fold. Dealt by household, each + household goes with its rarest class, counted in households (the first in + sorted order if several tie). So every household holding the rarest class + R is dealt round the folds in R's stratum, and R sits in every fold. A + training fold holding one class then holds only R, and the class R2 that + comes next in that order would have to sit wholly in the held-out fold. + Households holding R2 but not R are dealt round the folds in R2's stratum, + so at most one of them can sit there; the rest hold R, at most + ``ceil(n_R / K)`` to a fold, where ``n_R <= n_R2``. That needs + ``n_R2 - 1 <= ceil(n_R2 / K)``, which fails for every ``K >= 3`` once + ``can_deal_folds`` gives ``n_R2 >= K``. With two folds it can happen. The + UK SPI stage deals households into five folds. """ labels, groups, folds, seed = case assert can_deal_folds(labels, folds, groups=groups) @@ -362,9 +430,24 @@ def test_three_or_more_grouped_folds_keep_two_classes_in_every_training_fold( labels, folds, np.random.default_rng(seed), groups=groups ) assert (pd.Series(by_group).groupby(groups).nunique() == 1).all() + counts = ( + pd.DataFrame({"label": labels, "group": groups}) + .drop_duplicates() + .groupby("label") + .size() + ) + rarest = counts.index[int(np.argmin(counts.to_numpy()))] + for fold in range(folds): + assert (labels[by_group == fold] == rarest).any(), fold + one_class = [f for f in range(folds) if len(np.unique(labels[by_group != f])) < 2] + at_bound = ( + "a class at the bound" if counts.min() == folds else "every class above it" + ) if folds >= 3: - for fold in range(folds): - assert len(np.unique(labels[by_group != fold])) >= 2 + assert one_class == [] + event(f"three or more folds, {at_bound}") + else: + event("two folds" + (", a one-class training fold" if one_class else "")) # --- _class_balanced_weights: a class with no weight ------------------------- @@ -380,12 +463,18 @@ def test_balanced_weights_refuse_a_class_with_no_weight_by_name() -> None: @pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning") -def test_balanced_weights_refuse_a_class_whose_total_overflows() -> None: - """Its total was infinite, so dividing by it gave every row of the class zero weight.""" +def test_balanced_weights_leave_a_class_whose_total_overflows_as_it_was() -> None: + """Guard: a total that overflows still counts as weight, so the helper does not refuse it. + + Dividing by the infinite total gives the class's rows zero weight, as + before. A fit can reach this (see the guard below), so refusing it would + change that fit. + """ labels = np.array([0, 0, 1, 1]) weights = np.array([1e308, 1e308, 1.0, 1.0]) - with pytest.raises(ValueError, match="class 0 carries inf"): - _class_balanced_weights(labels, weights) + balanced = _class_balanced_weights(labels, weights) + assert _same_bits(balanced, _previous_class_balanced_weights(labels, weights)) + np.testing.assert_array_equal(balanced, [0.0, 0.0, 2.0, 2.0]) @st.composite @@ -396,7 +485,7 @@ def _labelled_weights(draw): ) if draw(st.booleans()): return labels, None - weight = st.one_of(st.just(0.0), st.floats(1e-6, 1e6)) + weight = st.one_of(st.just(0.0), st.floats(1e-6, 1e6), st.just(1e308)) return labels, np.asarray(draw(st.lists(weight, min_size=n, max_size=n))) @@ -407,23 +496,33 @@ def test_balanced_weights_keep_their_bits_and_refuse_exactly_the_weightless( ) -> None: """Where every class carries weight the result is the previous one, bit for bit. - Otherwise the helper refuses, naming a class with no weight. + That includes a class whose total overflows. Otherwise the helper refuses, + naming a class with no weight. """ labels, weights = case base = np.ones(len(labels)) if weights is None else weights - totals = {int(v): base[labels == v].sum() for v in np.unique(labels)} + with np.errstate(over="ignore"): + totals = {int(v): base[labels == v].sum() for v in np.unique(labels)} weightless = [v for v, total in totals.items() if not total > 0.0] - event("a weightless class" if weightless else "every class weighted") + overflowing = any(np.isinf(total) for total in totals.values()) if weightless: + event("a weightless class") with pytest.raises(ValueError, match="carries 0.0") as raised: - _class_balanced_weights(labels, weights) + with np.errstate(over="ignore"): + _class_balanced_weights(labels, weights) assert f"class {weightless[0]} carries" in str(raised.value) return + event("a class whose total overflows" if overflowing else "every class weighted") with warnings.catch_warnings(): warnings.simplefilter("error") - balanced = _class_balanced_weights(labels, weights) - previous = _previous_class_balanced_weights(labels, weights) + # An overflowing total gives its class zero weight, and if every class + # overflows the rescaling divides by zero: as before, so let it pass. + with np.errstate(all="ignore") if overflowing else contextlib.nullcontext(): + balanced = _class_balanced_weights(labels, weights) + previous = _previous_class_balanced_weights(labels, weights) assert _same_bits(balanced, previous) + if overflowing: + return class_totals = [balanced[labels == v].sum() for v in totals] np.testing.assert_allclose(class_totals, class_totals[0], rtol=1e-9) np.testing.assert_allclose(balanced.mean(), 1.0, rtol=1e-9) @@ -464,6 +563,42 @@ def test_a_sign_weighted_on_one_row_falls_back_to_the_in_sample_gate() -> None: assert fitted.gate_outcomes() == {"target": GateOutcome.WEIGHTLESS_FOLD} +def test_a_fit_whose_class_total_overflows_is_unchanged() -> None: + """Guard: a balanced cross-fit whose zero sign's weight total overflows fits as before. + + Every weight is finite, so the fit takes them, and every fold's training + rows carry both signs, so the gate balances them. The fit and its draws + match a fit with the previous helper patched in, bit for bit. + """ + rng = np.random.default_rng(3) + n = 120 + positive = rng.uniform(size=n) < 0.4 + table = pd.DataFrame( + { + "x": rng.normal(size=n), + "target": np.where(positive, rng.lognormal(1.0, 0.5, n), 0.0), + "weight": np.where(positive, 1.0, 1e308), + } + ) + model = RegimeGatedQRF( + n_estimators=4, + seed=5, + gate_calibration=GateCalibration.CROSS_FITTED_BALANCED, + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + fitted = model.fit(table, ["x"], ["target"], weights="weight") + draws = fitted.predict(table[["x"]]) + with mock.patch.object( + qrf, "_class_balanced_weights", _previous_class_balanced_weights + ): + before = model.fit(table, ["x"], ["target"], weights="weight") + before_draws = before.predict(table[["x"]]) + assert fitted.gate_outcomes() == before.gate_outcomes() + assert fitted.gate_outcomes()["target"] != GateOutcome.WEIGHTLESS_FOLD + pd.testing.assert_frame_equal(draws, before_draws, check_exact=True) + + @st.composite def _gate_cases(draw): """Two or three sign classes, each with at least five rows, and weights that are often zero.""" 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 19ce7723dd..15cfa0a4e7 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":"642a0c433c2426c0de5d104a9c0f320ae46d682828c0e42501fc817f75badf70","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"042948ba95d52a550eba31ac28f615d537a1c791b61722c8d1c05fecd1ff4f33","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"042948ba95d52a550eba31ac28f615d537a1c791b61722c8d1c05fecd1ff4f33"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"41c572c0b5d43fbc56594da0eeb90c8b4e9f17e2348de863c26ab65e722b64b0"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"235a12bc63b6df1fa8a8500fea1696e7e2fcbdcf65ecead77ea49f44278da732"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"358f5b6eae59a83e8ba750d0826bbae7f180e0b71c9a1e64d9ed75eb705681a3","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"3d85e760626ab88ddb06f88908b47abeb5918adffb25cd11b78dc17add85f918","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"3d85e760626ab88ddb06f88908b47abeb5918adffb25cd11b78dc17add85f918"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"9c50f2df3d92076531d8d2c5ee468824e283014ef56d50faba6db6da6dbdd44e"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"d39dd9deef2bd9066ff4e09075ea08f7612b99c36e7f1ade91b88087c52eb0ea"}},"seed":947} From 708d67e499183c1b5a52c1b0f7c1568c8fdf29d8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:36:16 -0500 Subject: [PATCH 4/5] Scope overflow claims in the fold-degenerate docstrings The round-1 Subfleet review (job 20261114-143433-fit-fold-r1) found the code fixes correct and valid input bit-identical, and flagged wording that overstates guarantees for weights whose totals overflow float64, which the fit accepts: - out_of_fold_proba's docstring promised a distribution in every row of every array a fold scores, and "as the training folds' shares do"; a fold whose training weights overflow gives NaN marginal rows (and sometimes NaN boosted and blend rows), unchanged from main. The docstring now says only what the fill guarantees: in a single-class fold each learner's rows equal the model's, so none is left at zero. - _class_balanced_weights' docstring, the changelog and the test module said an overflowing class's rows weigh zero. When every class's total overflows, every row's weight is NaN and the fit fails in scikit-learn ("Input sample_weight contains NaN."), on main as here; each now says so. Docstrings, comments and the changelog only: qrf.py, held_out.py and the test module are AST-equal to f3b489a1b with docstrings stripped. Repinned the attested fit.qrf hashes: repin, coverage (41/41), repin, --check clean, then graph_parity_repin fit.qrf; ruff format restores the double quotes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/fit-fold-degenerate-classes.fixed.md | 4 ++-- 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/held_out.py | 10 ++++------ packages/microcosm-fit/src/microcosm/fit/qrf.py | 4 +++- .../shared/test_fold_degenerate_classes.py | 10 ++++++---- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- 9 files changed, 28 insertions(+), 26 deletions(-) diff --git a/changelog.d/fit-fold-degenerate-classes.fixed.md b/changelog.d/fit-fold-degenerate-classes.fixed.md index 2fd47ae8cf..f2e60eb39d 100644 --- a/changelog.d/fit-fold-degenerate-classes.fixed.md +++ b/changelog.d/fit-fold-degenerate-classes.fixed.md @@ -1,4 +1,4 @@ Two fold-level cases in microcosm-fit no longer leave values that are not probabilities or weights. Output for every other input is unchanged: a differential run of a fixed workload through the old and new code matched in every value. -- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model and the training folds' shares already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). Each learner's array now scores wherever the model's does. A learner that no fold fitted, as when the target holds one class, still stays out of the result. For a target with two classes or more, folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows. -- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight. Before, it divided by that zero total and returned NaN weights. No fit reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, testing the same totals before it balances anything. A class whose total overflows to infinity still counts as carrying weight, and its rows still weigh zero, as before. +- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). In such a fold each learner's rows now equal the model's, so none is left at zero. A learner that no fold fitted, as when the target holds one class, still stays out of the result. For a target with two classes or more, folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows. +- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight. Before, it divided by that zero total and returned NaN weights. No fit reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, testing the same totals before it balances anything. A class whose total overflows to infinity still counts as carrying weight, and its rows still weigh zero, as before. If every class's total overflows, every row's weight is NaN and the fit fails in scikit-learn, also as before. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 4cbcd3143f..1a82e59839 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": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", - "protocol_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37" + "map_sha256": "e143f29b4d6954214521d705bb8447a6e86ff033bfc793f09d28fe9278c7668d", + "protocol_sha256": "4c1f3bbb4ef21d8a527732421efa55241878f7189cbdfd8ad9d2a9e1a32ca963" }, "failures": [], "observed": { - "map_sha256": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", - "protocol_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37" + "map_sha256": "e143f29b4d6954214521d705bb8447a6e86ff033bfc793f09d28fe9278c7668d", + "protocol_sha256": "4c1f3bbb4ef21d8a527732421efa55241878f7189cbdfd8ad9d2a9e1a32ca963" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", + "implementation_sha256": "4c1f3bbb4ef21d8a527732421efa55241878f7189cbdfd8ad9d2a9e1a32ca963", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", + "implementation_sha256": "4c1f3bbb4ef21d8a527732421efa55241878f7189cbdfd8ad9d2a9e1a32ca963", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364" + "spec_sha256": "25988583b169a3d17dc0fc59988d52b88252b92cc6669caa5d74ea425d03ffd6" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364" + "spec_sha256": "25988583b169a3d17dc0fc59988d52b88252b92cc6669caa5d74ea425d03ffd6" }, "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 8d121c4644..ee2542b5b4 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 @@ -393,8 +393,8 @@ # move both again; no valid input's draw changes. microcosm#1617's refusal # of a weightless class in the balanced gate's weights moves both again; # no fit reached it, and no draw changes. - "seed_map": "4e1c7d0aa93105ce8ad3c05bbc4a102938ba2b8ae373744dc5c0736ec75b2de8", - "seed_protocol": "7bdcdd7db2278c54c38cb87a825bfab675230cd406ebc406ea439f809ead3f37", + "seed_map": "e143f29b4d6954214521d705bb8447a6e86ff033bfc793f09d28fe9278c7668d", + "seed_protocol": "4c1f3bbb4ef21d8a527732421efa55241878f7189cbdfd8ad9d2a9e1a32ca963", "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 ef8c0bff41..cf2f183b93 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 @@ -27,7 +27,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The hierarchy value ranks move medicaid_take_up's attested bytes. # The fit input checks from the microimpute bug-parity audit move them too. assert first.spec_sha256 == ( - "d2c56d56aed52af2f5dd12078ebbf3a673bcdcaeeae03d69ab9e5c46a7cf69c6" + "d3235359336667ab58a2ce07619c52302ef7c694a24906ce0fe06db3fd70598f" ) 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 7daa7736db..9d1db101cb 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 @@ -355,7 +355,7 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "86326796d9b2569fa1d1d2be67fa936c8a5b5dc96e3999c57f9a9a9083a13364", + "spec_sha256": "25988583b169a3d17dc0fc59988d52b88252b92cc6669caa5d74ea425d03ffd6", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/held_out.py b/packages/microcosm-fit/src/microcosm/fit/held_out.py index 399981d05e..51211dafc8 100644 --- a/packages/microcosm-fit/src/microcosm/fit/held_out.py +++ b/packages/microcosm-fit/src/microcosm/fit/held_out.py @@ -113,12 +113,10 @@ def out_of_fold_proba( ``table[target]``. A fold whose training rows hold a single class fits no learner, and the - model gives that fold's rows the class with certainty, as the training - folds' shares do. Each learner's rows in that fold take the model's - probabilities, so every array holds a distribution in every row a fold - scores (:func:`categorical_scores` takes each one), and the model, the - learners and the constant are scored on the same rows, differing only - where a learner was fitted. When ``table[target]`` holds two classes or + model gives that fold's rows the class with certainty. Each learner's rows + in that fold take the model's probabilities, so none is left at zero, and + the model, the learners and the constant are scored on the same rows, + differing only where a learner was fitted. When ``table[target]`` holds two classes or more, folds from :func:`stratified_folds` after :func:`can_deal_folds` reach this only when they deal whole groups into exactly two folds. A learner that no fold fitted, as when ``table[target]`` holds one class, diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 64c460c61c..89d322dc10 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -921,7 +921,9 @@ def _class_balanced_weights( test on the same totals); otherwise the whole gate falls back to the in-sample gate (:attr:`GateOutcome.WEIGHTLESS_FOLD`), so no fit meets the refusal below. A class whose total overflows to infinity does carry - weight: its rows weigh zero here, and a fit can reach that. + weight, and a fit can reach that. Its rows weigh zero here, as before; + if every class's total overflows, the rescale divides by a zero sum and + every row's weight is NaN, as before. Raises: ValueError: If a class's rows carry no weight (a total that is not diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py index e3f76e6770..1a77999ce6 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_fold_degenerate_classes.py @@ -5,18 +5,20 @@ learner's rows in that fold used to stay at zero, which ``categorical_scores`` now refuses (microcosm#1543); before that it scored them at the log-loss floor. Those rows now take the model's probabilities: -certainty of the one class, as the constant gives too. ``_class_balanced_weights`` +certainty of the one class. ``_class_balanced_weights`` divides each class's weights by that class's total, so a class with no weight gave NaN; it now refuses the class by name. The cross-fitted gate never passed it such weights, because it falls back to the in-sample gate first (``GateOutcome.WEIGHTLESS_FOLD``), testing the same totals; the guards below pin that. A class whose total overflows to infinity does carry weight, so a fit can pass it to the helper; the helper leaves it as it was (its rows weigh -zero), and a guard pins that such a fit is unchanged. +zero, and if every class overflows every row's weight is NaN), and a guard +pins that such a fit is unchanged. The example tests that name a refusal or a filled row fail before the fixes; -the guards pass on both sides. The properties check that every array -``out_of_fold_proba`` returns is a distribution in every row, that the fix +the guards pass on both sides. The properties check that, on the small +tables they draw, every array ``out_of_fold_proba`` returns is a distribution +in every row, that the fix moves only rows that were all zeros, that folds dealt by household put the rarest class in every fold and, with three or more folds, leave two classes in every training fold, and that the balanced weights keep the previous formula's 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 15cfa0a4e7..776082a2e7 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":"358f5b6eae59a83e8ba750d0826bbae7f180e0b71c9a1e64d9ed75eb705681a3","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"3d85e760626ab88ddb06f88908b47abeb5918adffb25cd11b78dc17add85f918","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"3d85e760626ab88ddb06f88908b47abeb5918adffb25cd11b78dc17add85f918"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"9c50f2df3d92076531d8d2c5ee468824e283014ef56d50faba6db6da6dbdd44e"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"d39dd9deef2bd9066ff4e09075ea08f7612b99c36e7f1ade91b88087c52eb0ea"}},"seed":947} +{"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} From 391214aeb85c6c55bddc5cba93448b09b428b65e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:55:45 -0500 Subject: [PATCH 5/5] Limit out_of_fold_proba's "differing only" clause to the model and learners The round-2 Subfleet review (job 20261115-223630-fit-fold-r2) raised no P0 or P1. Its one P2: the docstring said the model, the learners and the constant differ only where a learner was fitted. In a single-class fold whose training weights overflow float64, no learner is fitted, yet the constant (training shares) is NaN while the model and the filled learners give the class with certainty. The clause now covers the model and the learners only, which holds by construction. Docstring only; held_out.py's bytes are attested nowhere, so no repin. Co-Authored-By: Claude Opus 5.5 --- packages/microcosm-fit/src/microcosm/fit/held_out.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/microcosm-fit/src/microcosm/fit/held_out.py b/packages/microcosm-fit/src/microcosm/fit/held_out.py index 51211dafc8..7f8eec3a1c 100644 --- a/packages/microcosm-fit/src/microcosm/fit/held_out.py +++ b/packages/microcosm-fit/src/microcosm/fit/held_out.py @@ -115,12 +115,12 @@ def out_of_fold_proba( A fold whose training rows hold a single class fits no learner, and the model gives that fold's rows the class with certainty. Each learner's rows in that fold take the model's probabilities, so none is left at zero, and - the model, the learners and the constant are scored on the same rows, - differing only where a learner was fitted. When ``table[target]`` holds two classes or - more, folds from :func:`stratified_folds` after :func:`can_deal_folds` - reach this only when they deal whole groups into exactly two folds. A - learner that no fold fitted, as when ``table[target]`` holds one class, - stays out of the result. + the model, the learners and the constant are scored on the same rows; the + model and the learners differ only where a learner was fitted. When + ``table[target]`` holds two classes or more, folds from + :func:`stratified_folds` after :func:`can_deal_folds` reach this only when + they deal whole groups into exactly two folds. A learner that no fold + fitted, as when ``table[target]`` holds one class, stays out of the result. """ weights = np.asarray(weights, dtype=np.float64) folds = np.asarray(folds)