Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking

This commit is contained in:
2026-11-05 16:12:23 -06:00
parent 0fdab3651c
commit 9808701c46
35 changed files with 1710 additions and 719 deletions
-66
View File
@@ -1,66 +0,0 @@
"""A cohort build's Parquet file: its columns, and reading it as a frame.
Long format: one row per member and event, with the member's index date on every row. A model gets the whole
frame and computes its own outcome and predictors from it; it never reads the database.
"""
import os
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from sqlalchemy.engine import make_url
SCHEMA = pa.schema([
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
])
class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `SCHEMA`'s."""
def cohorts_root(database_url: str) -> Path:
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
if configured := os.environ.get("COHORTS_DIR"):
return Path(configured)
url = make_url(database_url)
if url.get_backend_name() != "sqlite" or not url.database:
raise ValueError("this database has no data folder: set COHORTS_DIR")
return Path(url.database.removeprefix("file:")).parent / "cohorts"
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
domain, cohort = url.split("/", 1)
return root / domain / cohort / f"{armado_id}.parquet"
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
"""The file of that build, or of the cohort's latest build that has a file."""
if armado_id is None:
builds = [int(file.stem) for file in cohort_path(root, url, 0).parent.glob("*.parquet") if file.stem.isdigit()]
if not builds:
raise FileNotFoundError(f"no exported builds of {url} under {root}")
armado_id = max(builds)
path = cohort_path(root, url, armado_id)
if not path.exists():
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
return path
def cohort_lineage(path: str | Path) -> dict[str, str]:
"""The lineage in the file's metadata, without reading any rows."""
metadata = pq.read_metadata(path).metadata
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
def read_cohort(path: str | Path) -> pd.DataFrame:
"""The build's rows, after checking the file's schema without reading them."""
schema = pq.read_schema(path)
if not schema.equals(SCHEMA, check_metadata=False):
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
return pd.read_parquet(path)
-50
View File
@@ -1,50 +0,0 @@
"""The contract through which a model is asked for the risk of a cohort build's members.
The caller hands the estimator the wide frame of a cohort build, `(columns, rows)`, with
`columns = ["pac_id", "fecha_indice", <variables>]`. The estimator returns one `Risk` per member and
horizon, and its `Provenance`: the keys that reconcile a batch with MLflow (MLflow keeps no rows and no
patients).
`Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`,
`evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what Persistance's `PROCEDENCIA` expects.
This module doesn't import the kit, Persistance or the orchestration: it receives lists.
"""
from dataclasses import asdict, dataclass
from typing import NamedTuple, Protocol, runtime_checkable
class Risk(NamedTuple):
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # years from the index date; 0 = prevalent
probabilidad: float # 0 to 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Provenance:
"""Which model the risks come from: the keys a batch stores."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def as_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class RiskEstimator(Protocol):
"""What every risk model the orchestration can call provides."""
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
outcome: str # what it predicts ("cin2_mas")
def provenance(self) -> Provenance: ...
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
+98
View File
@@ -0,0 +1,98 @@
"""The shapes of the data the pipelines read and write. Nothing here reads or writes.
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
every row.
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
- 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
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
Persistance's `PROCEDENCIA` expects.
"""
from dataclasses import asdict, dataclass
from datetime import date
from typing import NamedTuple, Protocol, runtime_checkable
import pandas as pd
import pyarrow as pa
COHORT_SCHEMA = pa.schema([
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
])
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s."""
class CohortDefinitionError(ValueError):
"""The cohort's queries or their results don't follow the structure a build chains."""
@dataclass(frozen=True)
class ExclusionRule:
name: str
description: str
order: int
sql: str
@dataclass(frozen=True)
class CohortQueries:
url: str
all_patients: str
index_date: str
rules: tuple[ExclusionRule, ...]
cutoff: date
parameters: dict
@dataclass(frozen=True)
class BuiltCohort:
"""The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step."""
study_population: pd.DataFrame
attrition: pd.DataFrame
class Risk(NamedTuple):
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # years from the index date; 0 = prevalent
probabilidad: float # 0 to 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Provenance:
"""Which model the risks come from: the keys a batch stores."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def as_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class RiskEstimator(Protocol):
"""What every risk model the orchestration can call provides."""
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
outcome: str # what it predicts ("cin2_mas")
def provenance(self) -> Provenance: ...
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
-34
View File
@@ -1,34 +0,0 @@
"""ONNX checkpoint inspection (ML-01b, MLD-03).
Writing/storing a checkpoint is `models.io.training.TrainingRun.log_artifact`,
which hands it to MLflow directly — nothing here manages storage paths.
`onnx` is an optional dependency (`models[export]`); without it
`inspect_onnx_metadata` returns `{"available": False}`.
"""
from pathlib import Path
from typing import Any
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
onnx.checker.check_model(model)
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
+72
View File
@@ -0,0 +1,72 @@
"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under,
the keys lineage is recorded with, the hashes that identify code, data and models, and the rule that an output already
exists when its recorded lineage matches what's expected.
"""
import hashlib
import os
import subprocess
from pathlib import Path
import pyarrow as pa
DOMAINS = ("cacu", "cama", "tea")
ARMADO_TAG = "kit.armado_id"
MODEL_SHA_TAG = "modelo_sha"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
GIT_DIRTY_TAG = "models.git.dirty"
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
def code_version() -> dict[str, str]:
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
nothing is recorded."""
root = Path(__file__).resolve().parent
try:
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = os.environ.get(GIT_COMMIT_ENV)
return {GIT_COMMIT_TAG: commit} if commit else {}
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
def model_sha(model_dir: str | Path) -> str:
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
out because it carries ids and dates, so the same model saved twice has the same sha."""
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
def file_sha256(*paths: str | Path) -> str:
"""The hash of these files' bytes, in this order."""
digest = hashlib.sha256()
for path in paths:
digest.update(Path(path).read_bytes())
return digest.hexdigest()
def table_sha256(table: pa.Table) -> str:
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
sink = pa.BufferOutputStream()
table = table.replace_schema_metadata(None)
with pa.ipc.new_stream(sink, table.schema) as stream:
stream.write_table(table)
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
def matches(recorded: dict, expected: dict) -> bool:
"""Whether an output's recorded lineage has every expected value: then it is already done."""
return all(str(recorded.get(key)) == str(value) for key, value in expected.items())
def require_match(recorded: dict, expected: dict, what: str) -> None:
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
if not matches(recorded, expected):
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
-132
View File
@@ -1,132 +0,0 @@
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
produced it. Callers go through `PredictionService` rather than calling
`model.predict(...)` directly.
"""
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
from core.governance.models import ModelPrediction
from mlflow import MlflowException
from persistance.governance import model_prediction_repository
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
class Predictor(Protocol):
"""What the service needs from a model."""
def predict(self, data: Any) -> Any: ...
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a model and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: Predictor,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con models.io.registry.registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
+155 -16
View File
@@ -1,7 +1,9 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own: the promotion checks tied to the cohort a version was
trained on and to the validation-report convention.
trained on and to the validation-report convention, and `PredictionService`,
which stores each single prediction with the version in production (MLD-4/5,
EL-04b).
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
@@ -11,26 +13,28 @@ Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
database). A version points to its build with the `kit.armado_id` tag, and
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
"""
import hashlib
import json
import re
import tempfile
from collections.abc import Callable
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any
from typing import Any, Protocol
from core.governance.enums import ArtifactKind, Environment
from core.governance.models import ModelPrediction
from mlflow import MlflowClient, MlflowException
from persistance.governance import model_prediction_repository
from sqlmodel import select
from models.io.export import inspect_onnx_metadata
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name
from models.io.tracking import MODEL_PATH, TrainingRun, inspect_onnx_metadata, log_artifact_file
DOMAINS = ("cacu", "cama", "tea")
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
ARMADO_TAG = "kit.armado_id"
MODEL_SHA_TAG = "modelo_sha"
@dataclass(frozen=True)
@@ -48,10 +52,6 @@ class PromotionBlocked(Exception):
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
@dataclass(frozen=True)
class ResolvedVersion:
"""The version a caller will use, with what it needs to load it and to say where risks came from.
@@ -141,12 +141,34 @@ class ModelRegistry:
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.io.training.TrainingRun` directly."""
from models.io.training import TrainingRun
"""For training code that runs elsewhere and reports over the API: a run with these metrics, registered.
In-process training opens its own `TrainingRun` and calls `register_run`."""
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports)
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
cohort link, `modelo_sha`, report URIs), and returns the version."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(run.domain, run.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
if run.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
if run.modelo_sha is not None:
version_tags[MODEL_SHA_TAG] = run.modelo_sha
version_tags.update({key: uri for key, uri in reports.items() if uri})
source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}"
return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version)
def set_description(self, domain: str, scenario: str, version: str, description: str) -> None:
self.client.update_model_version(registered_name(domain, scenario), version, description=description)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
@@ -169,7 +191,7 @@ class ModelRegistry:
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
log_artifact_file(self.client, mv.run_id, kind_value, path)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
@@ -280,3 +302,120 @@ def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
"armado_en": armado.armado_en.isoformat()},
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
class Predictor(Protocol):
"""What the service needs from a model."""
def predict(self, data: Any) -> Any: ...
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a model and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: Predictor,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
-14
View File
@@ -1,14 +0,0 @@
"""Finds a domain's Persistance repository by name, the same objects WebApi writes with."""
import importlib
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
+171
View File
@@ -0,0 +1,171 @@
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
manifest, and a domain's Persistance repositories.
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
repository is used, so a model folder reading its cohort file never loads the database layer.
"""
import importlib
import json
import os
import tempfile
from datetime import date
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from sqlalchemy.engine import make_url
from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
CohortQueries, ExclusionRule)
def cohorts_root(database_url: str) -> Path:
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
if configured := os.environ.get("COHORTS_DIR"):
return Path(configured)
url = make_url(database_url)
if url.get_backend_name() != "sqlite" or not url.database:
raise ValueError("this database has no data folder: set COHORTS_DIR")
return Path(url.database).parent / "cohorts"
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
domain, cohort = url.split("/", 1)
return root / domain / cohort / f"{armado_id}.parquet"
def dbt_build_path(root: Path, url: str, number: int) -> Path:
return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet"
def _numbers(folder: Path) -> list[int]:
return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit())
def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None:
"""The highest-numbered build of dbt's rules, or `None` if there's none."""
numbers = _numbers(dbt_build_path(root, url, 0).parent)
return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
"""The file of that build, or of the cohort's latest build that has a file."""
if armado_id is None:
builds = _numbers(cohort_path(root, url, 0).parent)
if not builds:
raise FileNotFoundError(f"no exported builds of {url} under {root}")
armado_id = max(builds)
path = cohort_path(root, url, armado_id)
if not path.exists():
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
return path
def read_cohort(path: str | Path) -> pd.DataFrame:
"""The build's rows, after checking the file's schema without reading them."""
schema = pq.read_schema(path)
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
return pd.read_parquet(path)
def write_once(table: pa.Table, path: Path) -> None:
"""The file appears complete or not at all: written beside it, then renamed."""
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
partial = Path(handle.name)
try:
pq.write_table(table, partial)
partial.replace(path)
finally:
partial.unlink(missing_ok=True)
def read_metadata(path: str | Path) -> dict[str, str]:
"""A Parquet file's own metadata, without reading any rows."""
metadata = pq.read_metadata(path).metadata or {}
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
def _one(nodes: list[dict], kind: str, url: str) -> dict:
found = [node for node in nodes if node["config"]["meta"]["kind"] == kind]
if len(found) != 1:
raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}")
return found[0]
def _compiled(node: dict) -> str:
if not node.get("compiled_code"):
raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`")
return node["compiled_code"]
def read_queries(manifest: str | Path, url: str) -> CohortQueries:
"""The cohort's compiled queries, with its exclusions in their `order`.
An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every
rule's excluded members, and the study population, independent of the order.
"""
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url]
if not nodes:
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
if not exclusions:
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
orders = [node["config"]["meta"]["order"] for node in exclusions]
if len(set(orders)) != len(orders):
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
for node in exclusions:
if read := steps & set(node["depends_on"]["nodes"]):
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
meta = population["config"]["meta"]
if "cutoff" not in meta:
raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta")
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
for node in exclusions)
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
def resolve_repository(domain: str, entity: str):
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
+41 -91
View File
@@ -1,9 +1,10 @@
"""Bookkeeping around a training run (ML-01..ML-05).
"""MLflow runs: what happened in one execution (ML-01..ML-05).
Does not train anything. It opens an MLflow run, records which cohort
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
stores the run, metrics and artifacts. Turning a run into a registered
version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped
methods instead of the fluent API's global active run, so two runs in one
process never interfere.
@@ -18,77 +19,55 @@ uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
delivered images). A PROD run only logs models whose class lives in a module, at a
known commit, never one defined in a notebook.
"""
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Any
import mlflow.pyfunc
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.repository import Repository
from mlflow import MlflowClient
from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name
from models.io.repositories import resolve_repository
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name
from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
GIT_DIRTY_TAG = "models.git.dirty"
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
def code_version() -> dict[str, str]:
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
nothing is recorded."""
root = Path(__file__).resolve().parent
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint (ML-01b, MLD-03), checked before it's
logged. `onnx` is an optional dependency (`models[export]`).
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = os.environ.get(GIT_COMMIT_ENV)
return {GIT_COMMIT_TAG: commit} if commit else {}
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
onnx.checker.check_model(model)
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
def model_sha(model_dir: str | Path) -> str:
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
out because it carries ids and dates, so the same model saved twice has the same sha."""
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository: Repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind."""
client.log_artifact(run_id, str(path), artifact_path=kind)
if metadata:
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
class TrainingRun:
@@ -142,10 +121,7 @@ class TrainingRun:
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
named for its kind."""
kind = ArtifactKind(kind)
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
@@ -165,39 +141,13 @@ class TrainingRun:
self.modelo_sha = sha
return sha
def finish(
self,
*,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""Logs metrics/params to the run, registers it as a new version of
`<domain>-<scenario>` tagged with `models.io.registry`'s promotion
inputs (environment, cohort link, report URIs), and returns the new
version string. Call once, after training (and artifact logging)
completes."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
def finish(self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None) -> "TrainingRun":
"""Logs metrics and parameters and closes the run. Registering it as a version is the registry's
(`models.io.registry.registry.register_run`)."""
for key, value in (metrics or {}).items():
self.client.log_metric(self.run_id, key, value)
for key, value in (hyperparameters or {}).items():
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
name = registered_name(self.domain, self.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
if self.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
if self.modelo_sha is not None:
version_tags[MODEL_SHA_TAG] = self.modelo_sha
version_tags.update({key: uri for key, uri in reports.items() if uri})
source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}"
model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags)
self.client.set_terminated(self.run_id)
return str(model_version.version)
return self