Files
models/models/prediction.py
T

128 lines
4.8 KiB
Python

"""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
from core.governance.models import ModelPrediction
from mlflow import MlflowException
from persistance.governance import model_prediction_repository
from models.base import ScreeningModel
from models.registry import PRODUCTION_ALIAS, registered_name, registry
@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 `ScreeningModel` 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: ScreeningModel,
*,
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.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