Files
ISSSTELEON/Persistance/persistance/registry.py
T
alberto fdce3a5f49 Generic model bundles: export and import
Export (GET /models/{domain}/export) writes a deterministic zip of chosen versions with a manifest of SHA-256s, after the domain guard (TEA: n_reference >= 5, no study codes, dates or paths). Import (POST /models/{domain}/import, Dagster job import_bundle) stages the upload, checks its SHA-256 and that the operator listed it in $DATA_DIR/bundles/trusted (403 otherwise), verifies every file against the manifest and registers new candidate versions with lineage tags; duplicates are skipped.

Checks: ruff, import-linter, openapi diff; compose: 43 passed (test_bundles, test_runs, test_bundle, test_core_bundle_guard); ng build clean.
2026-11-28 09:24:40 -06:00

210 lines
7.7 KiB
Python

"""Model versions, in MLflow's registry. Each version keeps its reports as artifacts under
`reports/`; the `champion` alias, the version risk batches come from, moves only to a
version that has all three. Where MLflow is comes from MLFLOW_TRACKING_URI."""
import tempfile
from dataclasses import dataclass
from importlib.metadata import version as installed
from pathlib import Path
import mlflow
from mlflow import MlflowClient
REPORTS = ("technical_validation", "interpretability", "clinical_validation")
CHAMPION = "champion"
EXPERIMENT = "isssteleon"
# What a version needs to load, pinned to what trained it. Declared, so MLflow doesn't import
# the model in a subprocess to guess them (minutes, outside a uv project).
REQUIREMENTS = ("mlflow-skinny", "numpy", "pandas", "scipy", "scikit-learn", "joblib",
"cloudpickle") # fmt: skip
class MissingReports(ValueError):
pass
def register(
name: str,
python_model,
params: dict,
metrics: dict,
reports: dict,
tags: dict[str, str] | None = None,
) -> int:
"""A new version of `name`: the model, its parameters and metrics, and its reports."""
mlflow.set_experiment(EXPERIMENT)
with mlflow.start_run(run_name=name):
mlflow.log_params(params)
mlflow.log_metrics({k: float(v) for k, v in metrics.items() if v is not None})
if tags:
mlflow.set_tags(tags)
for report, data in reports.items():
mlflow.log_dict(data, f"reports/{report}.json")
info = mlflow.pyfunc.log_model(
name="model", python_model=python_model, registered_model_name=name,
pip_requirements=[f"{p}=={installed(p)}" for p in REQUIREMENTS],
) # fmt: skip
return int(info.registered_model_version)
def reports(name: str, version: int) -> dict[str, str]:
"""The reports a version has: report name -> artifact path."""
client = MlflowClient()
run = client.get_model_version(name, str(version)).run_id
found = {Path(a.path).stem: a.path for a in client.list_artifacts(run, "reports")}
return {k: v for k, v in found.items() if k in REPORTS}
def report(name: str, version: int, report: str) -> tuple[str, bytes] | None:
"""A version's report as stored: its file name and content; None when it has none."""
path = reports(name, version).get(report)
if path is None:
return None
run = MlflowClient().get_model_version(name, str(version)).run_id
with tempfile.TemporaryDirectory() as tmp:
local = mlflow.artifacts.download_artifacts(run_id=run, artifact_path=path, dst_path=tmp)
return Path(path).name, Path(local).read_bytes()
def add_report(name: str, version: int, report: str, filename: str, content: bytes) -> None:
"""A report added to a version after training (the clinical validation)."""
if report not in REPORTS:
raise ValueError(f"no report {report!r}; reports are {list(REPORTS)}")
run = MlflowClient().get_model_version(name, str(version)).run_id
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / f"{report}{Path(filename).suffix}"
path.write_bytes(content)
MlflowClient().log_artifact(run, str(path), "reports")
def promote(name: str, version: int) -> None:
"""Make a version the champion, if it has all three reports."""
if missing := [r for r in REPORTS if r not in reports(name, version)]:
raise MissingReports(f"{name} v{version} has no {', '.join(missing)}")
MlflowClient().set_registered_model_alias(name, CHAMPION, str(version))
def versions(name: str) -> list[dict]:
client = MlflowClient()
out = []
for found in client.search_model_versions(f"name = '{name}'"):
v = client.get_model_version(name, found.version) # the search leaves aliases out
run = client.get_run(v.run_id)
out.append({
"version": int(v.version), "created": v.creation_timestamp, "aliases": v.aliases,
"metrics": run.data.metrics, "params": run.data.params,
"reports": sorted(reports(name, int(v.version))),
}) # fmt: skip
return sorted(out, key=lambda v: v["version"])
def champion(name: str):
"""(version, model) of the champion, or None when no version was promoted."""
try:
found = MlflowClient().get_model_version_by_alias(name, CHAMPION)
except mlflow.exceptions.MlflowException:
return None
return int(found.version), mlflow.pyfunc.load_model(f"models:/{name}@{CHAMPION}")
def names(prefix: str) -> list[str]:
"""Registered models whose name starts with `prefix` (a domain: `cacu.`)."""
found = MlflowClient().search_registered_models(f"name LIKE '{prefix}%'")
return sorted(m.name for m in found)
def champion_version(name: str) -> int | None:
try:
found = MlflowClient().get_model_version_by_alias(name, CHAMPION)
except mlflow.exceptions.MlflowException:
return None
return int(found.version)
def latest_version(name: str) -> int | None:
found = MlflowClient().search_model_versions(f"name = '{name}'")
return max((int(v.version) for v in found), default=None)
def content_hashes(name: str) -> set[str]:
client = MlflowClient()
return {
tags["bundle.content_sha256"]
for v in client.search_model_versions(f"name = '{name}'")
if "bundle.content_sha256" in (tags := client.get_run(v.run_id).data.tags)
}
@dataclass(frozen=True)
class Snapshot:
name: str
version: int
created: int
params: dict[str, str]
metrics: dict[str, float]
tags: dict[str, str]
reports: dict[str, tuple[str, bytes]]
model: dict[str, bytes]
def snapshot(name: str, version: int) -> Snapshot:
client = MlflowClient()
try:
found = client.get_model_version(name, str(version))
except mlflow.exceptions.MlflowException as e:
if e.error_code != "RESOURCE_DOES_NOT_EXIST":
raise
raise ValueError(f"no {name} version {version}") from e
run = client.get_run(found.run_id).data
saved_reports = {
key: item for key in reports(name, version) if (item := report(name, version, key))
}
with tempfile.TemporaryDirectory() as tmp:
root = Path(
mlflow.artifacts.download_artifacts(
artifact_uri=f"models:/{name}/{version}", dst_path=tmp
)
)
model = {
p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()
}
return Snapshot(
name,
version,
found.creation_timestamp,
run.params,
run.metrics,
{k: v for k, v in run.tags.items() if not k.startswith("mlflow.")},
saved_reports,
model,
)
def restore(
name: str,
model_dir: Path,
params: dict[str, str],
metrics: dict[str, float],
reports: dict[str, tuple[str, bytes]],
tags: dict[str, str],
) -> int:
mlflow.set_experiment(EXPERIMENT)
with mlflow.start_run(run_name=name), tempfile.TemporaryDirectory() as tmp:
mlflow.log_params(params)
mlflow.log_metrics(metrics)
mlflow.set_tags(tags)
for report, (filename, content) in reports.items():
path = Path(tmp) / f"{report}{Path(filename).suffix}"
path.write_bytes(content)
mlflow.log_artifact(str(path), "reports")
loaded = mlflow.pyfunc.load_model(str(model_dir))
try:
python_model = loaded.unwrap_python_model()
except mlflow.exceptions.MlflowException as e:
raise ValueError("this model cannot be re-registered") from e
info = mlflow.pyfunc.log_model(
name="model", python_model=python_model, registered_model_name=name,
pip_requirements=[f"{p}=={installed(p)}" for p in REQUIREMENTS],
) # fmt: skip
return int(info.registered_model_version)