Files
tea/verification/mlflow_check.py
T
AlbertoPMDM 0ee5263419 verification mlflow: register plans and every biomarker, reload each in a fresh process
python -m verification mlflow [--uri] [--table]: both plans and the 9 biomarkers in
both implementations, registered as tea_modulo-test.*; falls back to a local store
(mlflow_local/, kept) when the server does not answer. The HK1K check registers
HK1K-trained baselines when TEA_MLFLOW_URI answers from the job.
2026-11-19 02:10:15 -06:00

186 lines
8.2 KiB
Python

"""
Registration check: preprocessing plans and every biomarker (legacy and modern)
logged and registered in MLflow, then loaded back in a fresh interpreter.
python -m verification mlflow [--uri http://10.0.10.41:5000] [--table hk1k.csv]
- --uri: the team's MLflow server. If it does not answer, a local store is used
instead (sqlite + artifacts under ./mlflow_local/), and its files are kept.
- Training data: a measured feature table (--table, or the tables the HK1K check
passes in); otherwise a synthetic table, tagged data=synthetic, which checks
only the registration path, not the baselines.
- Registered names: tea_modulo-test.plan.<plan>, tea_modulo-test.<impl>.<biomarker>,
in the experiment "tea_modulo · registro (prueba)".
- Each model is loaded in a new Python process; its predictions must equal the
in-memory module's.
MLflow receives parameters and baselines (group numbers) only; the privacy guard
refuses groups under 5 and texts with names, paths or dates.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import tempfile
import urllib.request
from pathlib import Path
DEFAULT_URI = "http://10.0.10.41:5000"
EXPERIMENT = "tea_modulo · registro (prueba)"
PREFIX = "tea_modulo-test"
LOCAL = Path("mlflow_local")
def reachable(uri: str, timeout: float = 5.0) -> bool:
if not uri.startswith("http"):
return True
try:
with urllib.request.urlopen(uri.rstrip("/") + "/health", timeout=timeout) as r:
return r.status == 200
except Exception: # noqa: BLE001
return False
def use_store(uri: str | None, fallback_local: bool = True) -> str | None:
"""Point MLflow at the server, or at a local store kept on disk when it does not answer
(None when it does not answer and fallback_local is off)."""
import mlflow
if uri and reachable(uri):
chosen = uri
elif not fallback_local:
return None
else:
LOCAL.mkdir(exist_ok=True)
chosen = f"sqlite:///{(LOCAL / 'mlflow.db').resolve()}"
os.environ["MLFLOW_ARTIFACT_ROOT"] = str((LOCAL / "artifacts").resolve())
mlflow.set_tracking_uri(chosen)
mlflow.set_registry_uri(chosen)
return chosen
def synthetic_table(features, n=60, seed=0):
"""Feature values that drift with age plus noise: enough for every baseline to fit."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed)
age = np.sort(rng.uniform(12, 48, n))
t = {"age_months": age}
for i, f in enumerate(features):
t[f] = np.abs(1.0 + 0.02 * (i + 1) * age + rng.normal(0, 0.3, n))
return pd.DataFrame(t)
def _fresh_predict(model_uri: str, rows_json: str, tracking_uri: str) -> list:
"""predict() of the model in a new Python process (nothing shared with this one)."""
code = ("import json,sys,mlflow,pandas as pd;"
f"mlflow.set_tracking_uri({tracking_uri!r});mlflow.set_registry_uri({tracking_uri!r});"
f"m=mlflow.pyfunc.load_model({model_uri!r});"
f"out=m.predict(pd.read_json(__import__('io').StringIO({rows_json!r})));"
"print(json.dumps(pd.DataFrame(out).astype(object).where(pd.DataFrame(out).notna(),None)"
".to_dict('records')))")
env = {**os.environ, "MLFLOW_DISABLE_AGENT_HINT": "1", "PYTHONWARNINGS": "ignore"}
with tempfile.TemporaryDirectory() as tmp:
r = subprocess.run([sys.executable, "-c", code], cwd=tmp, env=env, capture_output=True, text=True,
timeout=600)
if r.returncode:
raise RuntimeError(r.stderr.strip().splitlines()[-1] if r.stderr.strip() else "failed")
return json.loads(r.stdout.strip().splitlines()[-1])
def _same(a: list, b: list) -> bool:
import math
if len(a) != len(b):
return False
for x, y in zip(a, b):
for k in set(x) | set(y):
u, v = x.get(k), y.get(k)
if isinstance(u, float) and isinstance(v, float):
if not (math.isclose(u, v, rel_tol=1e-9, abs_tol=1e-12) or (u != u and v != v)):
return False
elif (u is None) != (v is None) or (u is not None and str(u) != str(v)):
return False
return True
def register_all(tables=None, *, uri: str | None = DEFAULT_URI, data_label: str = "synthetic",
impls=("legacy", "modern"), biomarkers=None, fallback_local: bool = True) -> dict:
"""Log + register plans and biomarkers, then reload each in a fresh process. Group results only."""
import mlflow
import pandas as pd
from tea_modulo.pipeline import Pipeline
from tea_modulo.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER
from tea_modulo.serving import load_plan, log_biomarker, log_plan
os.environ.setdefault("MLFLOW_DISABLE_AGENT_HINT", "1")
chosen = use_store(uri, fallback_local)
if chosen is None:
return {"tracking_uri": uri, "server_used": False, "ok": None, "skipped": "server not reachable"}
out = {"tracking_uri": chosen if chosen.startswith("http") else "local (mlflow_local/)",
"server_used": chosen.startswith("http"), "data": data_label, "plans": {}, "biomarkers": {}}
plan_uris = {}
for plan in (DIRECTOR_CLUSTER, DIRECTOR_CLI):
name = f"{PREFIX}.plan.{plan.name}"
try:
v = log_plan(plan, registered_name=name, experiment=EXPERIMENT)
muri = f"models:/{name}/{v.version}"
back = load_plan(muri)
plan_uris[plan.name] = muri
out["plans"][plan.name] = {"model": muri, "hash": plan.content_hash(),
"round_trip": back.get("hash") == plan.to_dict().get("hash")}
except Exception as e: # noqa: BLE001
out["plans"][plan.name] = {"error": f"{type(e).__name__}: {e}"[:300]}
plan_uri = plan_uris.get(DIRECTOR_CLUSTER.name, "")
for impl in impls:
pipe = Pipeline.default(impl=impl)
for b in (biomarkers or pipe.biomarker_names()):
name = f"{PREFIX}.{impl}.{b}"
res = {}
try:
mod = type(pipe.biomarker(b))()
t = (tables or {}).get(impl)
if t is None:
t = synthetic_table(mod.features)
cols = ["age_months", *[f for f in mod.features if f in t.columns]]
t = t[cols].dropna(subset=["age_months"])
mod.train(t)
res["n_reference"] = int(len(t))
v =log_biomarker(mod, plan_uri=plan_uri, registered_name=name, experiment=EXPERIMENT,
n_reference=len(t))
muri = f"models:/{name}/{v.version}"
mlflow.MlflowClient().set_model_version_tag(name, v.version, "data", data_label)
rows = t.dropna().head(3) if len(t.dropna()) else t.head(3)
local = mod.predict(rows)
local = json.loads(pd.DataFrame(local).astype(object).where(pd.DataFrame(local).notna(), None)
.to_json(orient="records"))
fresh = _fresh_predict(muri, rows.to_json(orient="records"), chosen)
res.update(model=muri, round_trip=_same(local, fresh), rows_checked=len(rows))
except Exception as e: # noqa: BLE001
res["error"] = f"{type(e).__name__}: {e}"[:300]
out["biomarkers"][f"{impl}.{b}"] = res
out["ok"] = (all(p.get("round_trip") for p in out["plans"].values())
and all(r.get("round_trip") for r in out["biomarkers"].values()))
return out
def main(argv=None) -> int:
import argparse
import pandas as pd
ap = argparse.ArgumentParser(prog="python -m verification mlflow")
ap.add_argument("--uri", default=os.environ.get("MLFLOW_TRACKING_URI", DEFAULT_URI))
ap.add_argument("--table", help="measured feature table (CSV, with age_months) to train on")
ap.add_argument("--data-label", default=None)
args = ap.parse_args(argv)
tables = None
label = "synthetic"
if args.table:
t = pd.read_csv(args.table)
tables, label = {"legacy": t, "modern": t}, args.data_label or Path(args.table).stem
out = register_all(tables, uri=args.uri, data_label=label)
print(json.dumps(out, indent=1))
return 0 if out["ok"] else 1