training: every run records the code's git commit; PROD logs only models defined in a module

This commit is contained in:
2026-11-04 00:49:19 +00:00
parent 0489475b86
commit f08b249eae
3 changed files with 94 additions and 7 deletions
+30 -2
View File
@@ -11,11 +11,17 @@ process never interfere.
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.
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 git commit of this package's repository and whether it had
uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
delivered images). A PROD run only logs models whose class lives in a module, at a
known commit, never one defined in a notebook.
"""
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Any
@@ -30,6 +36,25 @@ from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, reg
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
GIT_DIRTY_TAG = "models.git.dirty"
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
def code_version() -> dict[str, str]:
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
nothing is recorded."""
root = Path(__file__).resolve().parent
try:
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = os.environ.get(GIT_COMMIT_ENV)
return {GIT_COMMIT_TAG: commit} if commit else {}
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
def model_sha(model_dir: str | Path) -> str:
@@ -95,7 +120,7 @@ class TrainingRun:
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
)
self.run_id = run.info.run_id
self.modelo_sha: str | None = None
@@ -128,6 +153,9 @@ class TrainingRun:
example, so no patient data reaches MLflow."""
if self.modelo_sha is not None:
raise RuntimeError("this run already logged its model")
if self.environment is Environment.PROD and type(python_model).__module__ == "__main__":
raise ValueError("a PROD run only logs models whose class lives in a module; "
f"{type(python_model).__name__} was defined in a notebook or script")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / MODEL_PATH
mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature)