Models read only cohorts with rows: a pandera check on every source, in training and in estimation

This commit is contained in:
2026-11-16 22:57:47 -06:00
parent 0d75ff6baa
commit 6fded849a2
7 changed files with 87 additions and 18 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ WebApi.
| `io/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. | | `io/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. |
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. | | `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. | | `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. | | `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` (which refuses a build with no rows or with a member, a date or an event missing: `MODEL_COHORT`, pandera) and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
| `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. | | `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. |
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. | | `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit, its metrics and the routine records every classifier shares (`sampling`, `analytic_method`, `class_balance`, `output_confidence`), gathered by `routines` with the scenario's `missing_data` (ML-01a). | | `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit, its metrics and the routine records every classifier shares (`sampling`, `analytic_method`, `class_balance`, `output_confidence`), gathered by `routines` with the scenario's `missing_data` (ML-01a). |
+5 -7
View File
@@ -12,6 +12,8 @@ import pandera.pandas as pandera
from hamilton.data_quality.base import DataValidator, ValidationResult from hamilton.data_quality.base import DataValidator, ValidationResult
from hamilton.function_modifiers import check_output_custom from hamilton.function_modifiers import check_output_custom
from models.io.contracts import failed_checks
class FrameCheck(DataValidator): class FrameCheck(DataValidator):
"""A pandera schema as a Hamilton validator whose message carries no data values.""" """A pandera schema as a Hamilton validator whose message carries no data values."""
@@ -31,13 +33,9 @@ class FrameCheck(DataValidator):
return "frame_check" return "frame_check"
def validate(self, dataset: Any) -> ValidationResult: def validate(self, dataset: Any) -> ValidationResult:
try: failed = failed_checks(self.schema, dataset)
self.schema.validate(dataset, lazy=True) if failed:
except pandera.errors.SchemaErrors as failed: return ValidationResult(False, f"{self.description()} doesn't hold: {failed}")
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
summary = "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return ValidationResult(False, f"{self.description()} doesn't hold: {summary}")
return ValidationResult(True, f"{self.description()}: holds") return ValidationResult(True, f"{self.description()}: holds")
+5 -4
View File
@@ -1,8 +1,9 @@
"""Estimating with any scenario's registered version: score a source's build and write the estimate, once. """Estimating with any scenario's registered version: score a source's build and write the estimate, once.
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order; now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order.
its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a A build with no rows, or with nulls where a member, a date or an event goes, is refused first (`storage.model_frame`).
Its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
classifier that's the positive class at its one horizon. The output has one row per member and horizon classifier that's the positive class at its one horizon. The output has one row per member and horizon
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference. (`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
""" """
@@ -19,7 +20,7 @@ from models.dags.training import Scenario
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import matches from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, read_metadata, write_once from models.io.storage import CohortSource, model_frame, read_metadata, write_once
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool: def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
@@ -48,7 +49,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
cohort = source.reference() cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort): if already_estimated(output_path, resolved.version, cohort):
return resolved, False return resolved, False
cohort_frame = source.frame() cohort_frame = model_frame(source)
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"]) horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)) probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
risks = estimate_frame(cohort_frame, probabilities, horizons) risks = estimate_frame(cohort_frame, probabilities, horizons)
+5 -2
View File
@@ -6,6 +6,8 @@ anything runs and nothing in the model imports MLflow:
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage", - `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage",
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file). source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
The frame is checked against `MODEL_COHORT` whatever its source: a build with no rows, or with a member, a date or
an event missing, stops the run before any node reads it.
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics"], ...)`: logs the fitted model in - `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics"], ...)`: logs the fitted model in
the open `TrainingRun` (`tracking`), records the metrics and the config, closes the run, and registers and describes the open `TrainingRun` (`tracking`), records the metrics and the config, closes the run, and registers and describes
the version (`registry`). Its value is the version's metadata. the version (`registry`). Its value is the version's metadata.
@@ -26,12 +28,13 @@ from hamilton import registry as hamilton_registry
from hamilton.io.data_adapters import DataLoader, DataSaver from hamilton.io.data_adapters import DataLoader, DataSaver
from models.io.registry import registered_name, registry from models.io.registry import registered_name, registry
from models.io.storage import model_frame
from models.io.tracking import TrainingRun, pinned from models.io.tracking import TrainingRun, pinned
@dataclasses.dataclass @dataclasses.dataclass
class CohortSourceLoader(DataLoader): class CohortSourceLoader(DataLoader):
"""A build's long frame, from whatever source reads it.""" """A build's long frame, from whatever source reads it, if a model may read it (`storage.model_frame`)."""
source: Any source: Any
@@ -44,7 +47,7 @@ class CohortSourceLoader(DataLoader):
return "cohort_source" return "cohort_source"
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]: def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
frame = self.source.frame() frame = model_frame(self.source)
return frame, {"source": type(self.source).__name__, "rows": len(frame)} return frame, {"source": type(self.source).__name__, "rows": len(frame)}
+24 -1
View File
@@ -5,7 +5,8 @@
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`). - A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member and horizon (`horizonte_anios`, years from the - An estimate's output (`ESTIMATE_COLUMNS`): one row per member and horizon (`horizonte_anios`, years from the
index date; 0 is the prevalence). index date; 0 is the prevalence).
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`). - The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`), and what a model may read
(`MODEL_COHORT`): a build's rows, and at least one.
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build, - The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of `(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
@@ -44,6 +45,12 @@ COHORT_FRAME = pandera.DataFrameSchema(
error="a member has more than one index date"), error="a member has more than one index date"),
name="cohort build") name="cohort build")
# A build with no rows is a valid file, and nothing a model can train on or score.
MODEL_COHORT = pandera.DataFrameSchema(
COHORT_FRAME.columns,
checks=[*COHORT_FRAME.checks, pandera.Check(lambda frame: len(frame) > 0, error="the build has no rows")],
name="cohort build a model reads")
ESTIMATE_FRAME = pandera.DataFrameSchema( ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)), {"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False), "fecha_indice": pandera.Column(nullable=False),
@@ -59,6 +66,10 @@ class CohortFileError(ValueError):
`COHORT_FRAME`.""" `COHORT_FRAME`."""
class UnusableCohortError(ValueError):
"""The rows a source gave a model break `MODEL_COHORT`: none at all, or a member, date or event missing."""
class EstimateError(ValueError): class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice at one horizon, a negative """An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice at one horizon, a negative
horizon, a probability outside 0..1.""" horizon, a probability outside 0..1."""
@@ -73,6 +84,18 @@ def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: typ
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
def failed_checks(schema: pandera.DataFrameSchema, frame: pd.DataFrame) -> str | None:
"""The checks `frame` fails, each with its column and how many rows failed it, never a value; `None` when it
satisfies `schema`."""
try:
schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
return "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return None
class CohortDefinitionError(ValueError): class CohortDefinitionError(ValueError):
"""The cohort's queries or their results don't follow the structure a build chains.""" """The cohort's queries or their results don't follow the structure a build chains."""
+13 -1
View File
@@ -31,7 +31,8 @@ import pyarrow.parquet as pq
from sqlalchemy.engine import make_url from sqlalchemy.engine import make_url
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
CohortFileError, CohortQueries, ExclusionRule, check_frame) CohortFileError, CohortQueries, ExclusionRule, MODEL_COHORT, UnusableCohortError,
check_frame, failed_checks)
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
@@ -295,6 +296,17 @@ class CohortSource(Protocol):
def reference(self) -> dict[str, str]: ... def reference(self) -> dict[str, str]: ...
def model_frame(source: CohortSource) -> pd.DataFrame:
"""The source's frame, if a model may read it (`MODEL_COHORT`): a build with no rows, or with a member, a date or
an event missing, is refused whether it came from the database or a file. The refusal names the failed checks and
how many rows failed each, never a value."""
frame = source.frame()
failed = failed_checks(MODEL_COHORT, frame)
if failed:
raise UnusableCohortError(f"{type(source).__name__} isn't a {MODEL_COHORT.name}: {failed}")
return frame
@dataclass @dataclass
class KitBuild: class KitBuild:
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's """Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
+34 -2
View File
@@ -1,5 +1,6 @@
"""What this module covers: `models.io.adapters` and the generic driver of `models.dags.training`: the loaders feed the """What this module covers: `models.io.adapters` and the generic driver of `models.dags.training`: the loaders feed the
graph from any cohort source, the saver logs, registers and describes a version from `fitted_model` and `metrics`, the graph from any cohort source and refuse a build with no rows or with nulls where a member, a date or an event goes,
the saver logs, registers and describes a version from `fitted_model` and `metrics`, the
registered model runs without this repository, metrics that aren't numbers fail the run and register nothing, and a registered model runs without this repository, metrics that aren't numbers fail the run and register nothing, and a
failing node's inputs never reach the log. failing node's inputs never reach the log.
@@ -24,7 +25,7 @@ from hamilton.io.materialization import from_
from mlflow.entities import RunStatus from mlflow.entities import RunStatus
from models.dags import training from models.dags import training
from models.io.contracts import COHORT_SCHEMA from models.io.contracts import COHORT_SCHEMA, UnusableCohortError
from models.io.registry import registry from models.io.registry import registry
from models.io.storage import CohortFile from models.io.storage import CohortFile
@@ -124,6 +125,37 @@ def test_the_loaders_feed_the_graph_from_a_source(cohort_file):
assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"} assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"}
class _FrameSource:
"""A source that gives the frame it holds, as a database read would, without `read_cohort`'s checks."""
def __init__(self, frame):
self._frame = frame
def frame(self):
return self._frame
@pytest.mark.parametrize("change, check", [
(lambda frame: frame.iloc[0:0], "the build has no rows"),
(lambda frame: frame.assign(fecha_indice=None), "fecha_indice: not_nullable failed 3 time"),
(lambda frame: frame.assign(tipo=[None, "citologia", "citologia"]), "tipo: not_nullable failed 1 time"),
])
def test_a_build_with_no_rows_or_with_nulls_never_reaches_a_node(cohort_file, change, check):
"""Pins down: the `cohort_source` loader refuses an empty frame, and one with a null index date or event type, from
a source that doesn't check its own rows, naming the check and the count but no member. Fails if the loader stops
validating `MODEL_COHORT`, the schema loses its no-rows check, or the refusal starts quoting values."""
def members(cohort: pd.DataFrame) -> int:
return len(cohort)
broken = _FrameSource(change(CohortFile(cohort_file).frame()))
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(members)).with_materializers(
from_.cohort_source(target="cohort", source=broken)).build()
with pytest.raises(UnusableCohortError, match=check) as refused:
dr.execute(["members"])
assert not any(str(member) in str(refused.value) for member in MEMBERS)
def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scenario, cohort_file, mlflow_tracking): def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scenario, cohort_file, mlflow_tracking):
"""Pins down: the saver logs the fitted model, records the metrics, the config and the `models` version, registers """Pins down: the saver logs the fitted model, records the metrics, the config and the `models` version, registers
the version with its build and describes it. Fails if the saver stops being reached from `registered_model`, or the version with its build and describes it. Fails if the saver stops being reached from `registered_model`, or