463 lines
22 KiB
Python
463 lines
22 KiB
Python
"""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, 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
|
|
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
|
|
of its versions, never stored here and read from MLflow on every call.
|
|
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
|
|
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, Protocol
|
|
|
|
from core.governance.enums import ArtifactKind, Environment
|
|
from core.governance.models import ModelPrediction
|
|
import mlflow.artifacts
|
|
from mlflow import MlflowClient, MlflowException
|
|
from persistance.governance import model_prediction_repository
|
|
from sqlmodel import select
|
|
|
|
from models.io.lineage import (
|
|
ARMADO_TAG,
|
|
COHORT_BUILD_TAG,
|
|
COHORT_SOURCE_TAG,
|
|
COHORT_URL_TAG,
|
|
DOMAINS,
|
|
MODEL_SHA_TAG,
|
|
registered_name,
|
|
)
|
|
from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, TrainingRun, run_file, run_files
|
|
|
|
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
|
PRODUCTION_ALIAS = "produccion"
|
|
REFERENCE_SOURCE = "referencia" # `cohort.source` of a version trained on a cohort outside the platform
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PromotionCheck:
|
|
code: str
|
|
requirement: str
|
|
passed: bool
|
|
detail: str = ""
|
|
|
|
|
|
class PromotionBlocked(Exception):
|
|
def __init__(self, checks: list[PromotionCheck]):
|
|
self.checks = checks
|
|
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
|
|
super().__init__(f"la versión no cumple: {failed}")
|
|
|
|
|
|
@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`."""
|
|
|
|
def __init__(self, client: MlflowClient | None = None):
|
|
self._client = client
|
|
|
|
@property
|
|
def client(self) -> MlflowClient:
|
|
return self._client or MlflowClient()
|
|
|
|
def get(self, domain: str, scenario: str, version: str):
|
|
try:
|
|
return self.client.get_model_version(registered_name(domain, scenario), version)
|
|
except MlflowException as exc:
|
|
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
|
|
|
|
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
|
"""Every version, newest first. `scenario` needs `domain`; `domain`
|
|
alone matches every scenario of that domain (MLflow's own
|
|
`search_registered_models` LIKE filter); neither matches everything."""
|
|
if domain and domain not in DOMAINS:
|
|
raise ValueError(f"dominio desconocido: {domain!r}")
|
|
if scenario and not re.fullmatch(r"[\w-]+", scenario):
|
|
raise ValueError(f"escenario inválido: {scenario!r}")
|
|
if domain and scenario:
|
|
names = [registered_name(domain, scenario)]
|
|
elif domain:
|
|
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
|
|
else:
|
|
return [self._describe(mv) for mv in self.client.search_model_versions()]
|
|
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
|
|
|
|
def _status(self, mv) -> str:
|
|
try:
|
|
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
|
|
if str(production.version) == str(mv.version):
|
|
return "produccion"
|
|
except MlflowException:
|
|
pass
|
|
if mv.tags.get("retirada_en"):
|
|
return "retirada"
|
|
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
|
|
|
|
def status(self, domain: str, scenario: str, version: str) -> str:
|
|
return self._status(self.get(domain, scenario, version))
|
|
|
|
def in_production(self, domain: str) -> list[str]:
|
|
"""The scenarios of `domain` with a version holding the `produccion` alias, by name."""
|
|
if domain not in DOMAINS:
|
|
raise ValueError(f"dominio desconocido: {domain!r}")
|
|
prefix = registered_name(domain, "")
|
|
models = self.client.search_registered_models(filter_string=f"name LIKE '{prefix}%'")
|
|
return sorted(m.name.removeprefix(prefix) for m in models if PRODUCTION_ALIAS in (m.aliases or {}))
|
|
|
|
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,
|
|
*,
|
|
domain: str,
|
|
scenario: str,
|
|
environment: Environment | str,
|
|
cohorte_armado_id: int | None = None,
|
|
metrics: dict[str, Any] | None = None,
|
|
hyperparameters: dict[str, Any] | None = None,
|
|
**reports: str | None,
|
|
) -> str:
|
|
"""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 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 and cohort file, `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)
|
|
version_tags.update(run.cohort)
|
|
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."""
|
|
unknown = set(reports) - set(REPORT_TAGS)
|
|
if unknown:
|
|
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
|
name = registered_name(domain, scenario)
|
|
for tag, uri in reports.items():
|
|
self.client.set_model_version_tag(name, version, tag, uri or "")
|
|
|
|
def artifacts(self, domain: str, scenario: str, version: str) -> list[dict[str, Any]]:
|
|
"""Every file the version's run stored, at any depth (`path`, `size` in bytes)."""
|
|
return run_files(self.client, self.get(domain, scenario, version).run_id)
|
|
|
|
def artifact(self, domain: str, scenario: str, version: str, path: str) -> tuple[str, bytes]:
|
|
"""ML-01b: one stored artifact as a file name and its bytes; a folder (the saved model) comes as a zip.
|
|
`LookupError` for a path the run doesn't hold."""
|
|
return run_file(self.client, self.get(domain, scenario, version).run_id, path)
|
|
|
|
def _describe(self, mv) -> dict[str, Any]:
|
|
run = self.client.get_run(mv.run_id)
|
|
return {
|
|
"name": mv.name,
|
|
"version": str(mv.version),
|
|
"run_id": mv.run_id,
|
|
"tags": dict(mv.tags),
|
|
"metrics": dict(run.data.metrics),
|
|
"created_at": _iso(mv.creation_timestamp),
|
|
"status": self._status(mv),
|
|
}
|
|
|
|
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
|
return self._describe(self.get(domain, scenario, version))
|
|
|
|
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
|
"""Everything a version came from and produced: its cohort build (with
|
|
its attrition), logged artifacts and predictions."""
|
|
mv = self.get(domain, scenario, version)
|
|
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
|
return {
|
|
"model_version": self.describe(domain, scenario, version),
|
|
"cohorte_armado": armado,
|
|
"cohorte_exclusiones": exclusiones,
|
|
"artifacts": run_files(self.client, mv.run_id),
|
|
"routines": self.routines(mv.run_id),
|
|
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
|
|
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
|
|
}
|
|
|
|
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
|
|
mv = self.get(domain, scenario, version)
|
|
run = self.client.get_run(mv.run_id)
|
|
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
|
dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None
|
|
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
|
|
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
|
|
metrics = run.data.metrics
|
|
# ML-01a: the training run is itself the registered routine; its records (`TrainingRun.log_routine`) are
|
|
# reported, not required, since not every model has each of `ROUTINE_KINDS` (a prevalence-incidence mixture
|
|
# has no class balance or classifier calibration).
|
|
recorded = [kind.value for kind in ROUTINE_KINDS if kind.value in self.routines(mv.run_id)]
|
|
sha = mv.tags.get(MODEL_SHA_TAG, "")
|
|
if armado is not None:
|
|
cohort_detail = f"huella {armado['huella'][:12]}"
|
|
elif dbt_build is not None:
|
|
cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}"
|
|
elif reference:
|
|
cohort_detail = f"cohorte de referencia {mv.tags.get(COHORT_URL_TAG)}, listado {reference[:12]}"
|
|
else:
|
|
cohort_detail = "sin cohorte"
|
|
return [
|
|
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
|
|
PromotionCheck(
|
|
"ML-03",
|
|
"enlazada al armado de cohorte con el que se entrenó",
|
|
armado is not None or dbt_build is not None or bool(reference),
|
|
cohort_detail,
|
|
),
|
|
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
|
|
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
|
|
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
|
|
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
|
|
PromotionCheck("ML-01a", "rutina registrada por la corrida de entrenamiento", bool(run.info.run_id),
|
|
f"corrida {run.info.run_id[:12]}; registros de rutina: {len(recorded)} de {len(ROUTINE_KINDS)}"
|
|
+ (f" ({', '.join(recorded)})" if recorded else "")),
|
|
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
|
|
]
|
|
|
|
def routines(self, run_id: str) -> dict[str, Any]:
|
|
"""The routine records the run wrote while training (`TrainingRun.log_routine`), by kind."""
|
|
found = {}
|
|
for item in self.client.list_artifacts(run_id, ROUTINES_PATH):
|
|
kind = Path(item.path).stem
|
|
if not item.is_dir and kind in ArtifactKind.__members__:
|
|
found[kind] = json.loads(mlflow.artifacts.load_text(f"runs:/{run_id}/{item.path}"))
|
|
return found
|
|
|
|
def promote(self, domain: str, scenario: str, version: str):
|
|
"""Makes this the production version of its scenario, tagging the
|
|
previous one `retirada_en`. Promotion is always a manual step
|
|
(MLD-01/01b)."""
|
|
checks = self.checks(domain, scenario, version)
|
|
if not all(check.passed for check in checks):
|
|
raise PromotionBlocked(checks)
|
|
name = registered_name(domain, scenario)
|
|
try:
|
|
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
if str(previous.version) != str(version):
|
|
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
|
|
except MlflowException:
|
|
pass
|
|
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
|
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
|
|
return self.get(domain, scenario, version)
|
|
|
|
def retire(self, domain: str, scenario: str, version: str):
|
|
"""Withdraws a version from production; its scenario has no active
|
|
model until another one is promoted, so predictions stop."""
|
|
name = registered_name(domain, scenario)
|
|
try:
|
|
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
except MlflowException:
|
|
active = None
|
|
if active is None or str(active.version) != str(version):
|
|
raise ValueError("la versión no está en producción")
|
|
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
|
|
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
|
return self.get(domain, scenario, version)
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
|
|
def _iso(epoch_millis: int) -> str:
|
|
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
|
|
|
|
|
|
registry = ModelRegistry()
|
|
|
|
|
|
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
|
|
"""The kit cohort build a version was trained on, and its attrition steps."""
|
|
if not armado_id:
|
|
return None, []
|
|
cohortes = import_module(f"persistance.{domain}").cohort_repository
|
|
armado = cohortes.get(int(armado_id))
|
|
if armado is None:
|
|
return None, []
|
|
exclusion = cohortes.cohortes.CohorteExclusion
|
|
pasos = cohortes.read(lambda sesion: sesion.exec(
|
|
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
|
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
|
|
"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
|