From 0ee526341916c1cefd8ab93ba71d01986681ac1b Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Thu, 19 Nov 2026 02:10:15 -0600 Subject: [PATCH] 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. --- .dockerignore | 2 + .gitignore | 1 + deploy/dask-verify.yaml | 1 + verification/__main__.py | 7 +- verification/hk1k.py | 11 +++ verification/mlflow_check.py | 185 +++++++++++++++++++++++++++++++++++ 6 files changed, 205 insertions(+), 2 deletions(-) create mode 100644 verification/mlflow_check.py diff --git a/.dockerignore b/.dockerignore index 3fcd549..205c222 100644 --- a/.dockerignore +++ b/.dockerignore @@ -15,3 +15,5 @@ eeg/ **/*.eeg **/*_metadata.json biomarcadores-tea/experimentos/**/salidas/ +mlflow_local/ +**/mlflow_local/ diff --git a/.gitignore b/.gitignore index 85c6766..68153c7 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ __pycache__/ datos/ salidas/ mlruns/ +mlflow_local/ diff --git a/deploy/dask-verify.yaml b/deploy/dask-verify.yaml index 44eaf71..141e75a 100644 --- a/deploy/dask-verify.yaml +++ b/deploy/dask-verify.yaml @@ -31,6 +31,7 @@ spec: - {name: OMP_NUM_THREADS, value: "1"} - {name: OPENBLAS_NUM_THREADS, value: "1"} - {name: MKL_NUM_THREADS, value: "1"} + - {name: TEA_MLFLOW_URI, value: "http://10.0.10.41:5000"} resources: requests: {memory: 6Gi, cpu: "2"} limits: {memory: 6Gi} diff --git a/verification/__main__.py b/verification/__main__.py index c167e18..921a995 100644 --- a/verification/__main__.py +++ b/verification/__main__.py @@ -1,4 +1,5 @@ """python -m verification {hk1k|issste} --out processed/usuarios//tea-verify/ + python -m verification mlflow [--uri http://10.0.10.41:5000] [--table features.csv] Cluster checks of tea_modulo. They live outside the package (not in the wheel): they are for testing only, and run from the tea-verify image (PYTHONPATH=/opt/tea-modulo).""" @@ -8,13 +9,15 @@ import sys def main(argv=None) -> int: argv = list(sys.argv[1:] if argv is None else argv) - if not argv or argv[0] not in ("hk1k", "issste"): + if not argv or argv[0] not in ("hk1k", "issste", "mlflow"): print(__doc__, file=sys.stderr) return 2 if argv[0] == "hk1k": from verification import hk1k as check - else: + elif argv[0] == "issste": from verification import issste as check + else: + from verification import mlflow_check as check return check.main(argv[1:]) diff --git a/verification/hk1k.py b/verification/hk1k.py index 17c7bcd..d77349d 100644 --- a/verification/hk1k.py +++ b/verification/hk1k.py @@ -70,6 +70,8 @@ def main(argv=None) -> int: ap.add_argument("--check-n", type=int, default=4, help="studies re-run sequentially for the equality check") ap.add_argument("--impl", nargs="+", default=["legacy", "modern"]) ap.add_argument("--biomarkers", nargs="+", default=list(ALL_BIOMARKERS)) + ap.add_argument("--mlflow-uri", default=os.environ.get("TEA_MLFLOW_URI", ""), + help="register plans and HK1K-trained biomarkers there (skipped if it does not answer)") args = ap.parse_args(argv) addr = scheduler_address() @@ -101,6 +103,15 @@ def main(argv=None) -> int: if {"legacy", "modern"} <= set(tables): summary["modern_vs_legacy"] = compare(tables["legacy"], tables["modern"]) summary["reference"] = _reference() + if args.mlflow_uri and tables: + from verification.mlflow_check import register_all + ok = {i: t[(t.valid == 1) & (t.error == "")] for i, t in tables.items()} + try: + summary["mlflow"] = register_all(ok, uri=args.mlflow_uri, impls=tuple(ok), + data_label=f"hk1k-{summary['commit'] or 'local'}", + fallback_local=False) + except Exception as e: # noqa: BLE001 + summary["mlflow"] = {"error": f"{type(e).__name__}: {e}"[:300]} text = json.dumps(summary, indent=1, default=str) print(text) key = client.submit(write_summary, text, args.out, diff --git a/verification/mlflow_check.py b/verification/mlflow_check.py new file mode 100644 index 0000000..475ba78 --- /dev/null +++ b/verification/mlflow_check.py @@ -0,0 +1,185 @@ +""" +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., tea_modulo-test.., + 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