diff --git a/models/registry.py b/models/registry.py index cf104c5..60689a2 100644 --- a/models/registry.py +++ b/models/registry.py @@ -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, *, diff --git a/models/training.py b/models/training.py index e1305c7..cbdc847 100644 --- a/models/training.py +++ b/models/training.py @@ -9,20 +9,33 @@ 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://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, 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" + + +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: @@ -85,6 +98,7 @@ class TrainingRun: 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)) @@ -108,6 +122,21 @@ 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") + 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 +166,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) diff --git a/tests/test_model_versions.py b/tests/test_model_versions.py new file mode 100644 index 0000000..cb47c86 --- /dev/null +++ b/tests/test_model_versions.py @@ -0,0 +1,124 @@ +"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`) 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. +""" + +import mlflow.pyfunc +import pandas as pd +import pytest +from core.governance.enums import Environment +from mlflow import MlflowClient + +from models.registry import MODEL_SHA_TAG, registry +from models.training import 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/` 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://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:/` 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")