Files
models/models/training.py
T

176 lines
7.6 KiB
Python

"""Bookkeeping around a training run (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
methods instead of the fluent API's global active run, so two runs in one
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`; one that doesn't registers the run itself.
"""
import hashlib
import json
import os
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, MODEL_SHA_TAG, REPORT_TAGS, registered_name
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
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)
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs require `cohorte_armado_id`, the indicator kit cohort build they were
trained on, so their metrics trace back to that data (ML-03); dev runs may
omit it.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
):
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
environment = Environment(environment)
if environment is Environment.PROD and cohorte_armado_id is None:
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohorte_armado_id = cohorte_armado_id
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
)
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))
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
return ReadOnlyRepository(resolve_repository(self.domain, entity))
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")
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")
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,
*,
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.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)}")
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)