Files
models/models/io/tracking.py
T
edgar d090bb0f9f Governance: each version stores the drawing of its dataflow as files of its own
Training stores the scenario's Hamilton graph as `diagramas/pipeline.dot` and, when Graphviz's `dot` is installed,
`diagramas/pipeline.svg`, listed next to the version's other files. Without the `graphviz` package there is no
drawing and training goes on.
2026-11-22 07:38:07 -06:00

248 lines
13 KiB
Python

"""MLflow runs: what happened in one execution (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.
Each routine around training (ML-01a: sampling, missing data, analytic
method, class balance, output confidence) records what it did while the run
is open, with `log_routine`: one JSON per routine under `rutinas/`, made of
counts and settings, never rows. Turning a run into a registered
version is `models.io.registry`'s. 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).
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
their own, and `find_run` finds one already made from the same inputs.
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
tagged with the installed `models` package's version. A PROD run only logs models
whose class lives in a module, never one defined in a notebook.
A model is a scikit-learn estimator (saved with MLflow's sklearn flavor, served
through `predict_proba`) or an `mlflow.pyfunc.PythonModel`. Classes of a package
registered with `cloudpickle.register_pickle_by_value` are stored with the model,
so it loads without this repository.
"""
import io
import json
import os
import tempfile
import zipfile
from importlib.metadata import version
from pathlib import Path
from typing import Any
import mlflow.pyfunc
import mlflow.sklearn
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes"
DIAGRAMS_PATH = "diagramas"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
def routine_path(kind: ArtifactKind | str) -> str:
return f"{ROUTINES_PATH}/{ArtifactKind(kind).value}.json"
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind."""
client.log_artifact(run_id, str(path), artifact_path=kind)
if metadata:
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
def run_files(client: MlflowClient, run_id: str, folder: str | None = None) -> list[dict[str, Any]]:
"""Every file a run stored, at any depth: `path` and `size` in bytes."""
files = []
for item in client.list_artifacts(run_id, folder):
files.extend(run_files(client, run_id, item.path) if item.is_dir else [{"path": item.path, "size": item.file_size}])
return files
def run_file(client: MlflowClient, run_id: str, path: str) -> tuple[str, bytes]:
"""A stored file as its name and bytes, or a stored folder as `<name>.zip`. `LookupError` when the run holds
nothing at `path`, which is matched against the run's own listing, never resolved on disk."""
path = path.strip("/")
files = [item["path"] for item in run_files(client, run_id)]
with tempfile.TemporaryDirectory() as tmp:
if path in files:
local = Path(client.download_artifacts(run_id, path, tmp))
return local.name, local.read_bytes()
inside = [name for name in files if name.startswith(f"{path}/")]
if not path or not inside:
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
client.download_artifacts(run_id, path, tmp)
archive = io.BytesIO()
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zipped:
for name in inside:
zipped.write(Path(tmp) / name, name)
return f"{Path(path).name}.zip", archive.getvalue()
def experiment_id(client: MlflowClient, name: str) -> str:
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
experiment = client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
found = client.get_experiment_by_name(experiment)
if found is None:
return None
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
return run.info.run_id
return None
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
try:
for kind, path in files.items():
log_artifact_file(client, run.info.run_id, kind, path)
except Exception:
client.set_terminated(run.info.run_id, "FAILED")
raise
client.set_terminated(run.info.run_id, "FINISHED")
return run.info.run_id
def pinned(requirements: list[str]) -> list[str]:
"""Each distribution at the version installed here: `scikit-learn` → `scikit-learn==1.7.2`."""
return [f"{name}=={version(name)}" for name in requirements]
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs name the cohort build they were trained on, so their metrics trace
back to that data (ML-03): `cohort`, the reference to its file
(`models.io.lineage.cohort_reference`), or `cohorte_armado_id`, a kit build
by number; dev runs may omit both.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
cohort: dict[str, str] | 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 and cohort is None:
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id o cohort).")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohorte_armado_id = cohorte_armado_id
self.cohort = dict(cohort or {})
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
)
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))
for tag, value in self.cohort.items():
self.client.set_tag(self.run_id, tag, value)
def _experiment_id(self) -> str:
return experiment_id(self.client, registered_name(self.domain, self.scenario))
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."""
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
def log_routine(self, kind: ArtifactKind | str, record: dict[str, Any]) -> None:
"""ML-01a: what one routine did in this run, as it ran. A routine that was deliberately skipped records
that too (for instance a class balance of "none"), so the run still says what happened."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
def log_analysis(self, name: str, record: dict[str, Any]) -> None:
"""What the run found about its cohort, a JSON file `analisis/<name>.json` that the version publishes: the
population results a dashboard draws, which are not a prediction of any member."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, default=str), f"{ANALYSIS_PATH}/{name}.json")
def log_report(self, name: str, page: str) -> None:
"""A page the run wrote about its cohort, `reportes/<name>.html` (self-contained: its scripts inside), which the
version keeps for whoever reviews it. Like `log_analysis`, aggregates only."""
self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html")
def log_diagram(self, name: str, dot: str, svg: str | None = None) -> None:
"""A drawing of the run's dataflow, `diagramas/<name>.dot` (Graphviz source) and, when Graphviz's `dot` could
draw it, `diagramas/<name>.svg`: each one more file of the version, listed and downloaded on its own."""
self.client.log_text(self.run_id, dot, f"{DIAGRAMS_PATH}/{name}.dot")
if svg is not None:
self.client.log_text(self.run_id, svg, f"{DIAGRAMS_PATH}/{name}.svg")
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
"""Saves `model` 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. `requirements` are what an environment needs to load it (`pinned`); without them
MLflow infers them from the environment, which in this repository means its whole lock."""
if self.modelo_sha is not None:
raise RuntimeError("this run already logged its model")
if self.environment is Environment.PROD and type(model).__module__ == "__main__":
raise ValueError("a PROD run only logs models whose class lives in a module; "
f"{type(model).__name__} was defined in a notebook or script")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / MODEL_PATH
if isinstance(model, mlflow.pyfunc.PythonModel):
mlflow.pyfunc.save_model(path=str(path), python_model=model, signature=signature,
pip_requirements=requirements)
else:
mlflow.sklearn.save_model(model, str(path), serialization_format="cloudpickle", signature=signature,
pyfunc_predict_fn="predict_proba", pip_requirements=requirements)
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) -> "TrainingRun":
"""Logs metrics and parameters and closes the run. Registering it as a version is the registry's
(`models.io.registry.registry.register_run`)."""
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))
self.client.set_terminated(self.run_id)
return self