training, registry: TrainingRun.log_model with modelo_sha, and registry.resolve

This commit is contained in:
2026-11-03 21:34:40 +00:00
parent dd94aba1eb
commit 0489475b86
3 changed files with 191 additions and 2 deletions
+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,
*,
+34 -2
View File
@@ -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:/<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, 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)