Feature/model proto #2

Merged
edgar merged 3 commits from feature/model-proto into dev 2026-11-04 11:29:46 -06:00
5 changed files with 438 additions and 4 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ WebApi.
| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. |
| `registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
+33
View File
@@ -30,6 +30,7 @@ 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)
@@ -51,6 +52,24 @@ 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.
`status` is the version's status when it was resolved (`produccion`, `candidata`, `desarrollo` or
`retirada`)."""
domain: str
scenario: str
version: str
run_id: str
status: str
modelo_sha: str | None
@property
def model_uri(self) -> str:
return f"models:/{registered_name(self.domain, self.scenario)}/{self.version}"
class ModelRegistry:
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
@@ -97,6 +116,20 @@ class ModelRegistry:
def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version))
def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion:
"""With no `version`, the one holding the `produccion` alias; with a version, that one, whatever
its status (to test or compare a candidate). The status travels with it: confirming risks only
accepts versions that were in production."""
if version is None:
try:
mv = self.client.get_model_version_by_alias(registered_name(domain, scenario), PRODUCTION_ALIAS)
except MlflowException as exc:
raise LookupError(f"({domain}, {scenario}) has no version in production") from exc
else:
mv = self.get(domain, scenario, version)
return ResolvedVersion(domain, scenario, str(mv.version), mv.run_id, self._status(mv),
mv.tags.get(MODEL_SHA_TAG))
def register(
self,
*,
+63 -3
View File
@@ -9,20 +9,58 @@ process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
tagged with the git commit of this package's repository and whether it had
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 models.base import resolve_repository
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name
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
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()
class ReadOnlyRepository:
@@ -82,9 +120,10 @@ class TrainingRun:
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
)
self.run_id = run.info.run_id
self.modelo_sha: str | None = None
if cohorte_armado_id is not None:
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
@@ -108,6 +147,24 @@ class TrainingRun:
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
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
`modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input
example, so no patient data reaches MLflow."""
if self.modelo_sha is not None:
raise RuntimeError("this run already logged its model")
if self.environment is Environment.PROD and type(python_model).__module__ == "__main__":
raise ValueError("a PROD run only logs models whose class lives in a module; "
f"{type(python_model).__name__} was defined in a notebook or script")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / MODEL_PATH
mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature)
sha = model_sha(path)
self.client.log_artifacts(self.run_id, str(path), MODEL_PATH)
self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha)
self.modelo_sha = sha
return sha
def finish(
self,
*,
@@ -137,7 +194,10 @@ class TrainingRun:
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})
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
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)
+158
View File
@@ -0,0 +1,158 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": "# CaCu · CIN2+ · 01 — Exploratory analysis of the cohort\n\nFirst notebook of the `cin2_logistic` scenario: **exploratory only**. It describes the surveillance cohort\n(`cacu/cohorte_vigilancia`) from its build's Parquet file: who is in, what was measured at the index sample, and\nwhat happened afterwards. No outcome is computed and no model is fitted here.\n\n**How it gets its data, as in the deployment**\n\n- The domain's database is `CACU_DATABASE_URL`; the cohort files live next to it, in `<data>/cohorts/`,\n or in `COHORTS_DIR` when the data folder is read-only (as in the deployments).\n- A build's file is written **once**: if it already exists for that build, it's read; if not, it's exported\n from the build's members and dbt's timeline view, then read. Running the notebook again rebuilds nothing.\n- Every read goes through the domain's repositories; the notebook never opens a session.\n- **Locally**, with no `CACU_DATABASE_URL`, it works on a copy of the DEV deployment's simulated data in\n `~/.cache/isssteleon-notebooks/`, outside the repository, kept between runs.\n\n**With real data:** commit this notebook without outputs, and don't share counts below the suppression threshold.\n\nKernel: *ISSSTELEON WebApi env: kit + Persistance + models*.",
"id": "cacu-cin2-01-00"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 1. Configuration",
"id": "cacu-cin2-01-01"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/notebooks/cacu/cin2_logistic → ../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[3] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
"id": "cacu-cin2-01-02"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 2. dbt's timeline view\n\nThe export reads each member's history from `cacu_linea_de_tiempo`, the view dbt creates at deployment. If the\ndatabase doesn't have it and it's a local copy, it's created here; in a deployment, it has to be deployed first.",
"id": "cacu-cin2-01-03"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "from persistance.aristas.plata import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohorte_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)",
"id": "cacu-cin2-01-04"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 3. The build's file: read it if it exists, export it once if not\n\nProvisional helpers: they will move into the code (a cycle step that exports each build, and the timeline\nquery over dbt's view in Persistance).",
"id": "cacu-cin2-01-05"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohorte_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"",
"id": "cacu-cin2-01-06"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "builds = pd.DataFrame([vars(b) for b in cohorte_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]",
"id": "cacu-cin2-01-07"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "build = cohorte_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)",
"id": "cacu-cin2-01-08"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "Running it again reuses the file: nothing is rebuilt and the file, and so its hash, stays the same.",
"id": "cacu-cin2-01-09"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "again, what = ensure(build)\nprint(what, \"| same file:\", again == path, \"| same sha256:\",\n hashlib.sha256(again.read_bytes()).hexdigest() == hashlib.sha256(path.read_bytes()).hexdigest())",
"id": "cacu-cin2-01-10"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 4. The cohort\n\nOne row per member, variable and date. `fecha_indice` is on every row; the index sample is the member's index\nevent (`fuente_tabla`, `fuente_id`), and its results are dated when they were **reported**, usually after the\nindex date.",
"id": "cacu-cin2-01-11"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "cohort = pd.read_parquet(path)\ncohort[\"dias\"] = (pd.to_datetime(cohort.fecha) - pd.to_datetime(cohort.fecha_indice)).dt.days\nmembers = cohort.groupby(\"pac_id\").fecha_indice.first()\nprint(f\"{len(cohort):,} rows · {members.size:,} members · index dates {members.min()} to {members.max()}\")\nmembers.pipe(pd.to_datetime).dt.to_period(\"Q\").value_counts().sort_index().rename(\"members by quarter of the index date\").to_frame().T",
"id": "cacu-cin2-01-12"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "cohort[\"momento\"] = pd.cut(cohort.dias, [-10**6, -1, 0, 10**6], labels=[\"before\", \"on the index date\", \"after\"])\ncohort.pivot_table(index=[\"clase\", \"tipo\"], columns=\"momento\", values=\"pac_id\", aggfunc=\"count\", observed=False, fill_value=0)",
"id": "cacu-cin2-01-13"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 5. At the index sample\n\nThe results of the member's own index cytology: its Bethesda category and its HPV result, matched by the source\nrow of the index event, not by date.",
"id": "cacu-cin2-01-14"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "sample = cohort[cohort.tipo == \"citologia\"].merge(members.rename(\"fi\"), left_on=\"pac_id\", right_index=True)\nsample = sample[sample.fecha == sample.fi].groupby(\"pac_id\").fuente_id.first().rename(\"muestra\")\nat_index = cohort.merge(sample, left_on=\"pac_id\", right_index=True)\nat_index = at_index[at_index.fuente_id == at_index.muestra]\nbaseline = at_index.pivot_table(index=\"pac_id\", columns=\"tipo\", values=\"valor_codigo\", aggfunc=\"first\")\nbaseline = baseline.reindex(members.index)\nprint(\"members without an HPV result at the index sample:\", f\"{baseline.vph.isna().mean():.1%}\")\npd.crosstab(baseline.bethesda.fillna(\"(none)\"), baseline.vph.fillna(\"(none)\"), margins=True)",
"id": "cacu-cin2-01-15"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 6. After the index\n\nFollow-up: how long it lasts, how many members had a biopsy and when, and the grades reported.",
"id": "cacu-cin2-01-16"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "after = cohort[cohort.dias > 0]\nfollow_up = after.groupby(\"pac_id\").dias.max().reindex(members.index).fillna(0)\nfirst_biopsy = after[after.tipo == \"biopsia\"].groupby(\"pac_id\").dias.min()\nprint(f\"follow-up (days to the last event): median {follow_up.median():.0f}, quartiles {follow_up.quantile(.25):.0f}–{follow_up.quantile(.75):.0f}\")\nprint(f\"members with a biopsy after the index: {first_biopsy.size:,} ({first_biopsy.size / members.size:.1%}); \"\n f\"days to the first one: median {first_biopsy.median():.0f}\")\nafter[after.tipo == \"biopsia\"].valor_codigo.fillna(\"(no grade)\").value_counts().rename(\"biopsy results after the index\").to_frame()",
"id": "cacu-cin2-01-17"
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "import matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 2, figsize=(11, 3.5))\nfollow_up.div(30.44).plot.hist(bins=30, ax=axes[0], title=\"Follow-up per member (months)\")\nfirst_biopsy.div(30.44).plot.hist(bins=30, ax=axes[1], title=\"Index to first biopsy (months)\")\nfor ax in axes:\n ax.set_ylabel(\"members\")\nplt.tight_layout()",
"id": "cacu-cin2-01-18"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Next\n\n- **02 — profiling and hypothesis tests**, and the outcome itself (prevalent CIN2+ and time to it), computed by\n the model from these rows, not by the cohort.\n- The helpers of sections 2 and 3 move into the code: the export into the cycle, and the timeline query over\n dbt's view into Persistance.",
"id": "cacu-cin2-01-19"
}
],
"metadata": {
"kernelspec": {
"display_name": "ISSSTELEON WebApi env: kit + Persistance + models (feature/model-proto)",
"language": "python",
"name": "isssteleon-webapi"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+183
View File
@@ -0,0 +1,183 @@
"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`), the
code version every run records (`code_version`), and choosing the version to use (`registry.resolve`).
Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready`
(from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a
pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a
logged model; `_git` asks git about this repository, to compare with what the run recorded.
"""
import subprocess
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
import pytest
from core.governance.enums import Environment
from mlflow import MlflowClient
from models import training
from models.registry import MODEL_SHA_TAG, registry
from models.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
class Constant(mlflow.pyfunc.PythonModel):
"""Returns `p` for every row."""
def __init__(self, p: float):
self.p = p
def predict(self, context, model_input: pd.DataFrame, params=None) -> list[float]:
return [self.p] * len(model_input)
def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[TrainingRun, str]:
"""A dev run of `cacu/<scenario>` that logs `model` (if any) and is registered; returns the run and
its version."""
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
if model is not None:
run.log_model(model)
return run, run.finish(metrics={"auc": 0.7})
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
"""Pins down: a run that logs a model registers `runs:/<run_id>/model`, and loading the version gives
back that model, tagged with its `modelo_sha` on the run and on the version.
Fails if `finish` registers the run instead of its model folder, or the sha isn't tagged.
"""
run, version = _train(Constant(0.25))
loaded = mlflow.pyfunc.load_model(registry.resolve("cacu", "tamizaje", version).model_uri)
mv = registry.get("cacu", "tamizaje", version)
assert list(loaded.predict(pd.DataFrame({"x": [1, 2]}))) == [0.25, 0.25]
assert mv.source == f"runs:/{run.run_id}/model"
assert mv.tags[MODEL_SHA_TAG] == run.modelo_sha
assert MlflowClient().get_run(run.run_id).data.tags[MODEL_SHA_TAG] == run.modelo_sha
def test_the_sha_is_the_model_not_the_run(mlflow_tracking):
"""Pins down: the same model logged in two runs has the same `modelo_sha`; a different model has
another one.
Fails if `model_sha` starts covering files with ids or dates (`MLmodel`), or stops covering the model.
"""
first, _ = _train(Constant(0.25))
second, _ = _train(Constant(0.25))
other, _ = _train(Constant(0.30))
assert first.modelo_sha == second.modelo_sha != other.modelo_sha
def test_a_run_logs_one_model(mlflow_tracking):
"""Pins down: a second `log_model` in the same run is refused.
Fails if a run could hold two models, so its version wouldn't say which one it is.
"""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_model(Constant(0.25))
with pytest.raises(RuntimeError, match="already logged"):
run.log_model(Constant(0.30))
def test_a_run_without_a_model_still_registers_the_run(mlflow_tracking):
"""Pins down: a run that doesn't log a model registers `runs:/<run_id>` with no `modelo_sha`, as
before `log_model` existed.
Fails if `finish` requires a model.
"""
run, version = _train()
resolved = registry.resolve("cacu", "tamizaje", version)
assert registry.get("cacu", "tamizaje", version).source == f"runs:/{run.run_id}"
assert resolved.modelo_sha is None
def test_without_a_version_resolve_takes_production(production_ready):
"""Pins down: with no version, `resolve` returns the one holding `produccion`, with that status; with
none in production it raises `LookupError`.
Fails if `resolve` falls back to the latest version instead of failing.
"""
domain, scenario, version = production_ready("v1")
with pytest.raises(LookupError, match="no version in production"):
registry.resolve(domain, scenario)
registry.promote(domain, scenario, version)
resolved = registry.resolve(domain, scenario)
assert (resolved.version, resolved.status) == (version, "produccion")
assert resolved.model_uri == f"models:/{domain}-{scenario}/{version}"
def test_an_explicit_version_is_returned_with_its_status(production_ready):
"""Pins down: with a version, `resolve` returns it whatever its status (a candidate can be tested),
and says which status it has; an unknown version raises `LookupError`.
Fails if an explicit version is refused for not being in production, or its status is lost.
"""
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2")
registry.promote(domain, scenario, first)
assert registry.resolve(domain, scenario, second).status == "candidata"
assert registry.resolve(domain, scenario, first).status == "produccion"
with pytest.raises(LookupError):
registry.resolve(domain, scenario, "99")
def _git(*args: str) -> str:
return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True,
check=True).stdout.strip()
def test_every_run_records_the_commit_of_the_code(mlflow_tracking):
"""Pins down: a run is tagged with the git commit of the `models` repository (MLflow's own tag name) and
whether tracked files had uncommitted changes; untracked files (notebooks, data) don't count.
Fails if the tags are dropped or renamed, or the dirty flag counts untracked files.
"""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
tags = MlflowClient().get_run(run.run_id).data.tags
assert tags[GIT_COMMIT_TAG] == _git("rev-parse", "HEAD")
assert tags[GIT_DIRTY_TAG] == str(bool(_git("status", "--porcelain", "--untracked-files=no"))).lower()
def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_tracking, monkeypatch):
"""Pins down: where git or the repository is missing (a delivered image), the commit is read from
`MODELS_GIT_COMMIT`, with no dirty flag; with neither, the run records no commit rather than a guess.
Fails if a missing repository raises, or a commit is invented.
"""
def no_git(*args, **kwargs):
raise FileNotFoundError("git")
monkeypatch.setattr(training.subprocess, "run", no_git)
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
assert tags[GIT_COMMIT_TAG] == "abc123" and GIT_DIRTY_TAG not in tags
monkeypatch.delenv(GIT_COMMIT_ENV)
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
assert GIT_COMMIT_TAG not in tags
def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking):
"""Pins down: a PROD run only logs a model whose class lives in a module; one defined in a notebook or
script (`__main__`) is refused, because its code has no commit to trace. A dev run accepts it.
Fails if the check is dropped, or starts refusing dev runs or module classes.
"""
InNotebook = type("InNotebook", (Constant,), {"__module__": "__main__"})
prod = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD, cohorte_armado_id=1)
with pytest.raises(ValueError, match="defined in a notebook"):
prod.log_model(InNotebook(0.25))
prod.log_model(Constant(0.25))
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).log_model(InNotebook(0.25))