serving (MLflow), HK1K verification command and the tea-verify DaskJob

- serving: plans and biomarkers as MLflow "models from code" (standalone
  wrapper files), code_paths = only the module's package + contracts;
  plan.json artifact and plan params; biomarker models pin plan_uri and
  plan_hash. privacy: no study codes / dates / paths, binary artifacts
  refused, baselines from fewer than 5 children refused.
- verify: python -m tea_modulo.verify hk1k lists HK1K in a worker task, runs
  the pipeline remotely (line 50 Hz), checks the remote run equals a plain
  sequential run in one task, summarizes the posterior rhythm by age group
  (groups < 5 suppressed) and writes the summary under processed/usuarios/.
  Any input prefix but raw/eeg-helsinki/ is refused.
- deploy: Dockerfile.verify (dask:1.1 + antropy, fhir.resources, meegkit,
  pytest; tea-modulo from the local checkout), .dockerignore keeping .venv,
  eeg/ and any signal or patient file out, dask-verify.yaml (own 2x4-worker
  cluster, no eeg-data PVC, keys only on workers), verify.sh.

Tests: MLflow round trips on sqlite, model loads with only its own code in
a fresh interpreter, privacy refusals, verify guards.
This commit is contained in:
AlbertoPMDM
2026-11-18 20:24:03 -06:00
parent 038836a701
commit 4956f36d80
15 changed files with 723 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
"""
Plans and biomarkers as MLflow models, behind a privacy guard.
from tea_modulo.serving import log_plan, log_biomarker, load_plan, load_biomarker
"""
from tea_modulo.serving.models import (
load_biomarker,
load_plan,
log_biomarker,
log_plan,
)
from tea_modulo.serving.privacy import Forbidden
__all__ = ["log_plan", "log_biomarker", "load_plan", "load_biomarker", "Forbidden"]
@@ -0,0 +1,30 @@
"""
MLflow "model from code" for a trained tea_modulo biomarker. Standalone on
purpose: it imports nothing from tea_modulo at module level, so a logged model
needs only its own module's code (shipped in code_paths) and `contracts`.
predict(df with the feature columns + age_months) -> deviation table
(feature, value, age_months, outside, z, baseline).
"""
import importlib
import json
from pathlib import Path
import mlflow
import pandas as pd
class BiomarkerModel(mlflow.pyfunc.PythonModel):
def load_context(self, context):
folder = Path(context.artifacts["module"])
cfg = json.loads((folder / "module.json").read_text())
mod, _, attr = cfg["class"].partition(":")
self.module = getattr(importlib.import_module(mod), attr).load(folder)
self.config = cfg
def predict(self, context, model_input, params=None):
return self.module.predict(pd.DataFrame(model_input))
mlflow.models.set_model(BiomarkerModel())
@@ -0,0 +1,22 @@
"""
MLflow "model from code" for a preprocessing plan. Standalone: the plan
(plan.json) is the artifact; predict() returns it, one row per input row.
"""
import json
from pathlib import Path
import mlflow
import pandas as pd
class PlanModel(mlflow.pyfunc.PythonModel):
def load_context(self, context):
self.plan = json.loads(Path(context.artifacts["plan"]).read_text(encoding="utf-8"))
def predict(self, context, model_input, params=None):
n = max(1, len(model_input))
return pd.DataFrame({"plan": [json.dumps(self.plan)] * n, "hash": [self.plan.get("hash", "")] * n})
mlflow.models.set_model(PlanModel())
+138
View File
@@ -0,0 +1,138 @@
"""
Plans and biomarkers as MLflow pyfunc models.
pv = log_plan(plan, registered_name="tea-plan-director-cluster")
bv = log_biomarker(rhythm, plan_uri=f"models:/tea-plan-director-cluster/{pv.version}",
registered_name="tea-bio-posterior-rhythm")
plan_dict = load_plan("models:/tea-plan-director-cluster/1")
rhythm = load_biomarker("models:/tea-bio-posterior-rhythm/3")
mlflow.pyfunc.load_model(uri).predict(df) # df: features + age_months
A biomarker model carries only its own module's code plus `contracts`
(code_paths), its saved state (baseline.json, params.json) and a copy of the
plan it was trained with. Tags: plan_uri, plan_hash, module version, impl,
CONTRACT_VERSION. Nothing is logged before the privacy checks pass.
"""
from __future__ import annotations
import json
import shutil
import tempfile
from pathlib import Path
import mlflow
import pandas as pd
from tea_modulo.contracts import CONTRACT_VERSION
from . import privacy
PKG_ROOT = Path(__file__).resolve().parents[1] # .../tea_modulo
MODEL_CODE = Path(__file__).with_name("model_code")
def _stage_code(module_pkg: str, dest: Path) -> Path:
"""A copy of tea_modulo with only `contracts` and the module's package (+ parent __init__s)."""
root = dest / "tea_modulo"
(root).mkdir(parents=True)
shutil.copy(PKG_ROOT / "__init__.py", root / "__init__.py")
shutil.copytree(PKG_ROOT / "contracts", root / "contracts",
ignore=shutil.ignore_patterns("__pycache__"))
parts = module_pkg.split(".")[1:] # drop "tea_modulo"
cur_src, cur_dst = PKG_ROOT, root
for p in parts[:-1]:
cur_src, cur_dst = cur_src / p, cur_dst / p
cur_dst.mkdir(exist_ok=True)
shutil.copy(cur_src / "__init__.py", cur_dst / "__init__.py")
shutil.copytree(PKG_ROOT.joinpath(*parts), root.joinpath(*parts),
ignore=shutil.ignore_patterns("__pycache__"), dirs_exist_ok=True)
return root
def _package_of(module) -> str:
"""'tea_modulo.legacy.biomarkers.posterior_rhythm' for a module object."""
name = type(module).__module__
return name.rsplit(".", 1)[0] if name.endswith(".api") else name
def log_plan(plan, *, registered_name: str | None = None, run_name: str | None = None,
experiment: str = "tea-modulo-plans"):
d = plan.to_dict() if hasattr(plan, "to_dict") else dict(plan)
d.pop("bads", None)
d.pop("reasons", None)
privacy.check_text(json.dumps(d), registered_name or "", run_name or "")
mlflow.set_experiment(experiment)
with tempfile.TemporaryDirectory() as tmp, mlflow.start_run(run_name=run_name or d.get("name")):
mlflow.log_dict(d, "plan/plan.json")
mlflow.log_params({"plan.name": d.get("name"), "plan.hash": d.get("hash"),
"plan.line_hz": d.get("line_hz"),
**{f"step.{s['kind']}.{k}": v for s in d.get("steps", [])
for k, v in s.get("params", {}).items()},
"variants": ",".join(v["name"] for v in d.get("variants", []))})
mlflow.set_tags({"kind": "plan", "plan_hash": d.get("hash", ""),
"contract_version": CONTRACT_VERSION})
f = Path(tmp) / "plan.json"
f.write_text(json.dumps(d, indent=1), encoding="utf-8")
info = mlflow.pyfunc.log_model(name="plan", python_model=str(MODEL_CODE / "plan_model.py"),
artifacts={"plan": str(f)},
code_paths=[str(_stage_code("tea_modulo.contracts", Path(tmp) / "code"))],
input_example=pd.DataFrame({"edf_path": ["study.edf"]}),
registered_model_name=registered_name)
return _version(info, registered_name)
def log_biomarker(module, *, plan_uri: str = "", plan: dict | None = None,
registered_name: str | None = None, run_name: str | None = None,
n_reference: int | None = None, experiment: str = "tea-modulo-biomarkers",
input_example: pd.DataFrame | None = None):
privacy.check_text(registered_name or "", run_name or "", plan_uri)
if plan is None and plan_uri:
plan = load_plan(plan_uri)
pkg = _package_of(module)
mlflow.set_experiment(experiment)
with tempfile.TemporaryDirectory() as tmp:
state = Path(tmp) / "module"
state.mkdir()
module.save(state)
(state / "module.json").write_text(json.dumps(
{"class": f"{type(module).__module__}:{type(module).__name__}", "name": module.name,
"version": module.version, "impl": getattr(module, "impl", "modern")}))
if plan is not None:
(state / "plan.json").write_text(json.dumps(plan, indent=1))
privacy.check_files(state)
privacy.check_group(state, n_reference)
if input_example is None:
input_example = pd.DataFrame({**{f: [1.0] for f in module.features}, "age_months": [24.0]})
code = _stage_code(pkg, Path(tmp) / "code")
with mlflow.start_run(run_name=run_name or module.name):
mlflow.set_tags({"kind": "biomarker", "module": module.name, "module_version": module.version,
"impl": getattr(module, "impl", "modern"), "plan_uri": plan_uri,
"plan_hash": (plan or {}).get("hash", ""),
"contract_version": CONTRACT_VERSION})
info = mlflow.pyfunc.log_model(name="biomarker", python_model=str(MODEL_CODE / "biomarker_model.py"),
artifacts={"module": str(state)}, code_paths=[str(code)],
input_example=input_example,
registered_model_name=registered_name)
return _version(info, registered_name)
def load_plan(uri: str) -> dict:
"""The plan dict of a plan model (models:/name/version or runs:/...)."""
m = mlflow.pyfunc.load_model(uri)
return m.unwrap_python_model().plan
def load_biomarker(uri: str):
"""The trained biomarker module object of a biomarker model."""
return mlflow.pyfunc.load_model(uri).unwrap_python_model().module
def _version(info, registered_name):
if registered_name:
client = mlflow.MlflowClient()
vs = client.search_model_versions(f"name='{registered_name}'")
return max(vs, key=lambda v: int(v.version))
return info
+67
View File
@@ -0,0 +1,67 @@
"""
What may leave the computer for MLflow (rule carried over from
biomarcadores-tea/biomarcadores/registro.py, user decision 8 Oct 2026):
plans, group-level baseline parameters, code versions. Never per-child
values, study codes (eeg_###), dates or local paths, and never a group
smaller than MIN_GROUP children.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
# registro._PROHIBIDO, plus POSIX home paths
FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/|Escritorio", re.I)
MIN_GROUP = 5
class Forbidden(ValueError):
"""Something that must not leave the computer was about to be logged."""
def check_text(*texts):
for t in texts:
m = FORBIDDEN.search(str(t))
if m:
raise Forbidden(f"text with a study code, date or path ({m.group(0)[:12]!r}…) "
f"cannot go to MLflow")
def check_files(folder: Path):
"""Every text file a module saved, before it is logged as an artifact."""
for p in Path(folder).rglob("*"):
if p.is_file():
try:
check_text(p.read_text(encoding="utf-8"))
except UnicodeDecodeError:
raise Forbidden(f"{p.name}: binary artifacts are not allowed (only JSON / text)") from None
def group_size(baseline: dict | None) -> float | None:
"""Reference group size of a baseline dict, if its format is known."""
if not baseline:
return None
st = baseline.get("state")
if isinstance(st, dict) and "n" in st:
return float(st["n"])
curva = baseline.get("curva")
if isinstance(curva, dict) and curva.get("n_efectivo"):
vals = [v for v in curva["n_efectivo"] if v is not None]
return max(vals) if vals else 0.0 # Kish n_eff <= n
return None
def check_group(folder: Path, n_reference: int | None = None):
"""Refuse a trained baseline from fewer than MIN_GROUP children."""
n = n_reference
if n is None:
f = Path(folder) / "baseline.json"
if f.exists():
n = group_size(json.loads(f.read_text(encoding="utf-8")))
if n is None:
raise Forbidden("cannot tell the reference group size: pass n_reference")
if n < MIN_GROUP:
raise Forbidden(f"baseline from {n:g} children: fewer than {MIN_GROUP} would almost "
f"show each child's values")