TEA EEG baselines trained on a local cohort and moved between installations as a bundle of group numbers

This commit is contained in:
AlbertoPMDM
2026-11-20 09:36:41 -06:00
parent 7b8a4e8499
commit 70646e64b6
8 changed files with 553 additions and 17 deletions
+47
View File
@@ -152,6 +152,37 @@ def _tea_analyze(args: argparse.Namespace) -> int:
return 1 if s.failed else 0
def _tea_export_baselines(args: argparse.Namespace) -> int:
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, export
from models.tea.eeg.settings import settings
try:
done = export(settings(), args.out, environment=args.environment.upper(), production=args.production)
except BundleError as error:
print(f"not exported: {error}", file=sys.stderr)
return 1
for scenario, version in done.versions.items():
print(f"{scenario}: version {version}")
print(f"written: {done.path} (sha256 {done.sha256})")
return 0
def _tea_import_baselines(args: argparse.Namespace) -> int:
"""The age baselines of a bundle, registered (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, import_
from models.tea.eeg.settings import settings
try:
done = import_(settings(), args.bundle)
except BundleError as error:
print(f"not imported: {error}", file=sys.stderr)
return 1
for scenario, (version, new) in done.items():
print(f"{scenario}: {'imported as' if new else 'already registered as'} version {version}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
@@ -447,6 +478,11 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.add_argument("--reference-dir", help="tea eeg: train on the EDFs of this folder instead of the configured cohort")
run.add_argument("--reference-ages", help="tea eeg: CSV of `archivo` and `edad_meses` (or `edad_anos`); "
"without it, each EDF header's age")
run.add_argument("--reference-name", help="tea eeg: a name for that cohort (no names or dates of people)")
run.add_argument("--line-hz", type=float, help="tea eeg: the mains frequency where it was recorded (60)")
run.set_defaults(run=lambda args: _run(run, args))
tea = commands.add_parser("tea", help="TEA's EEG analysis")
@@ -459,6 +495,17 @@ def build_parser() -> argparse.ArgumentParser:
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
analyze.set_defaults(run=_tea_analyze)
export_baselines = tea_actions.add_parser(
"export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child")
export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)")
export_baselines.add_argument("--environment", choices=["dev", "prod"], default="prod")
export_baselines.add_argument("--production", action="store_true",
help="the versions in production, instead of the newest trained in --environment")
export_baselines.set_defaults(run=_tea_export_baselines)
import_baselines = tea_actions.add_parser(
"import-baselines", help="register the age baselines of a bundle; promotion still needs their reports")
import_baselines.add_argument("bundle", help="the bundle `export-baselines` wrote")
import_baselines.set_defaults(run=_tea_import_baselines)
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
+205
View File
@@ -0,0 +1,205 @@
"""Trained age baselines as a bundle: exported where they were trained, imported on each platform installation.
What the bundle holds, per scenario: the trained module's saved state (`params.json`, `baseline.json`), which
module it is (`module.json`), the preprocessing plan (`plan.json`), the routine records, the metrics, the
version's promotion tags and its description; and a manifest with each file's SHA-256. Group numbers only: the
library's privacy guard runs over every file before the bundle is written, and refuses a group under 5.
The import checks the manifest, accepts for each scenario only the library module the platform runs for it,
requires the module's hash to match the one recorded where it was trained, and registers it as a new version
with the same tags, routine records and metrics, so the registry's promotion checks read it as trained. A
version already holding that trained module is kept.
"""
import hashlib
import io
import json
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, GIT_COMMIT_TAG, MODEL_SHA_TAG
from models.io.lineage import registered_name
from models.io.tracking import ROUTINES_PATH, experiment_id
from models.tea.eeg import train
from models.tea.eeg.analyze import pipeline
from models.tea.eeg.settings import Settings
FORMAT = 1
MANIFEST = "manifest.json"
# The version tags a bundle carries: what promotion checks and what identifies the trained module. Report links
# and promotion dates belong to each installation.
TAGS = ("domain", "scenario", "environment", MODEL_SHA_TAG, COHORT_URL_TAG, COHORT_SOURCE_TAG, COHORT_BUILD_TAG,
"plan_hash", "module", "module_version", "phase", "baseline")
SOURCE_COMMIT_TAG = "origen.git_commit"
BUNDLE_TAG = "importado.paquete"
EPOCH = (1980, 1, 1, 0, 0, 0) # every zip entry's date, so the same baselines give the same bundle
class BundleError(ValueError):
"""A bundle that can't be exported or imported as it is, with the reason."""
@dataclass(frozen=True)
class Exported:
path: Path
sha256: str
versions: dict[str, str]
def _sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def state_sha(folder: Path) -> str:
"""The trained module's hash, as training records it (`train._module_state`): its saved JSON files."""
files = sorted(p for p in Path(folder).glob("*.json") if p.name in ("params.json", "baseline.json"))
return _sha(b"".join(f.name.encode() + f.read_bytes() for f in files))
def _version(client, scenario: str, environment: str, production: bool):
from models.io.registry import PRODUCTION_ALIAS
name = registered_name(train.DOMAIN, scenario)
if production:
try:
return client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except Exception: # noqa: BLE001 -- none in production
return None
return train.latest(scenario, environment)
def export(s: Settings, out: str | Path, *, environment: str = "PROD", production: bool = False) -> Exported:
"""Every scenario's baseline into one bundle at `out`: the version in production with `production`, otherwise
the newest trained in `environment`. Refuses a bundle missing a scenario, or holding something the privacy
guard refuses."""
import mlflow.artifacts
from mlflow import MlflowClient
from tea.serving.privacy import check_files, check_group, check_text
client = MlflowClient()
versions = {scenario: _version(client, scenario, environment, production) for scenario in s.scenarios}
missing = sorted(k for k, mv in versions.items() if mv is None)
if missing:
raise BundleError(f"no {'production' if production else environment} version of {', '.join(missing)}")
manifest = {"formato": FORMAT, "dominio": train.DOMAIN, "escenarios": {}}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for scenario, mv in versions.items():
folder = root / scenario
module_dir = folder / "module"
module_dir.mkdir(parents=True)
model = Path(mlflow.artifacts.download_artifacts(artifact_uri=f"models:/{mv.name}/{mv.version}",
dst_path=str(root / ".descargas" / scenario)))
saved = next((p.parent for p in model.rglob("module.json") if p.parent.name == "module"), None)
if saved is None:
raise BundleError(f"{scenario} version {mv.version}: its model has no trained module")
for file in ("params.json", "baseline.json", "module.json", "plan.json"):
if not (saved / file).exists():
raise BundleError(f"{scenario} version {mv.version}: its trained module has no {file}")
(module_dir / file).write_bytes((saved / file).read_bytes())
if state_sha(module_dir) != mv.tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario} version {mv.version}: its saved state isn't the one it was trained with")
routines = folder / ROUTINES_PATH
routines.mkdir()
for item in client.list_artifacts(mv.run_id, ROUTINES_PATH):
local = mlflow.artifacts.download_artifacts(run_id=mv.run_id, artifact_path=item.path,
dst_path=str(root / ".descargas"))
(routines / Path(item.path).name).write_text(Path(local).read_text())
run = client.get_run(mv.run_id)
metrics = dict(run.data.metrics)
tags = {k: mv.tags[k] for k in TAGS if k in mv.tags}
if run.data.tags.get(GIT_COMMIT_TAG):
tags[SOURCE_COMMIT_TAG] = run.data.tags[GIT_COMMIT_TAG]
check_group(module_dir, int(metrics.get("n_referencia", 0)) or None)
files = sorted(p for p in folder.rglob("*") if p.is_file())
manifest["escenarios"][scenario] = {
"version_origen": str(mv.version), "tags": tags, "metricas": metrics,
"descripcion": mv.description or "",
"archivos": {p.relative_to(root).as_posix(): _sha(p.read_bytes()) for p in files},
}
text = json.dumps(manifest, ensure_ascii=False, indent=1, sort_keys=True)
check_text(text)
(root / MANIFEST).write_text(text)
for scenario in versions:
check_files(root / scenario)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as z:
for p in sorted(q for q in root.rglob("*") if q.is_file() and ".descargas" not in q.parts):
z.writestr(zipfile.ZipInfo(p.relative_to(root).as_posix(), EPOCH), p.read_bytes())
out = Path(out)
out.write_bytes(buffer.getvalue())
return Exported(out, _sha(buffer.getvalue()), {k: str(mv.version) for k, mv in versions.items()})
def _unpack(data: bytes, root: Path) -> dict:
"""The bundle's files under `root`, each checked against the manifest; the manifest."""
with zipfile.ZipFile(io.BytesIO(data)) as z:
names = z.namelist()
for name in names:
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts:
raise BundleError(f"the bundle holds a path outside itself: {name}")
if MANIFEST not in names:
raise BundleError("the bundle has no manifest")
manifest = json.loads(z.read(MANIFEST))
if manifest.get("formato") != FORMAT or manifest.get("dominio") != train.DOMAIN:
raise BundleError("not a bundle of TEA's EEG baselines in a format this platform reads")
listed = {f: sha for entry in manifest["escenarios"].values() for f, sha in entry["archivos"].items()}
if set(listed) != set(names) - {MANIFEST}:
raise BundleError("the bundle's files aren't the ones its manifest lists")
for name, sha in listed.items():
content = z.read(name)
if _sha(content) != sha:
raise BundleError(f"{name} changed after the bundle was written")
target = root / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
return manifest
def import_(s: Settings, bundle: str | Path) -> dict[str, tuple[str, bool]]:
"""Registers every baseline of the bundle; by scenario, (version, whether it's new)."""
from mlflow import MlflowClient
from tea.serving import log_biomarker
data = Path(bundle).read_bytes()
bundle_sha = _sha(data)
pipe = pipeline(s)
out = {}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
manifest = _unpack(data, root)
unknown = sorted(set(manifest["escenarios"]) - set(s.scenarios))
if unknown:
raise BundleError(f"this platform has no scenario {', '.join(unknown)}")
for scenario, entry in manifest["escenarios"].items():
tags = dict(entry["tags"])
module_dir = root / scenario / "module"
sha = state_sha(module_dir)
if sha != tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario}: the module isn't the one recorded where it was trained")
biomarker, phase = s.scenarios[scenario]
if tags.get("module") != biomarker or (tags.get("phase") or None) != phase:
raise BundleError(f"{scenario}: the bundle says it's {tags.get('module')}, not {biomarker}")
cls = type(pipe.module(biomarker))
declared = json.loads((module_dir / "module.json").read_text()).get("class")
if declared != f"{cls.__module__}:{cls.__name__}":
raise BundleError(f"{scenario}: the bundle's module class isn't the one this platform runs")
existing = train.find_trained(scenario, {MODEL_SHA_TAG: sha, COHORT_BUILD_TAG: tags.get(COHORT_BUILD_TAG, ""),
"environment": tags.get("environment", "")})
if existing is not None:
out[scenario] = (str(existing.version), False)
continue
module = cls.load(module_dir)
name = registered_name(train.DOMAIN, scenario)
client = MlflowClient()
experiment_id(client, name)
n = int(entry["metricas"].get("n_referencia", 0)) or None
mv = log_biomarker(module, plan=json.loads((module_dir / "plan.json").read_text()), registered_name=name,
run_name=scenario, n_reference=n, experiment=name)
routines = {p.stem: json.loads(p.read_text()) for p in sorted((root / scenario / ROUTINES_PATH).glob("*.json"))}
train.record(client, name, str(mv.version), mv.run_id, tags={**tags, BUNDLE_TAG: bundle_sha},
routines=routines, metrics=entry["metricas"], description=entry["descripcion"])
out[scenario] = (str(mv.version), True)
return out
+12 -2
View File
@@ -2,7 +2,8 @@
A baseline isn't trained on a cohort build of the platform but on the reference cohort (`train.py`), so this
scenario runs its own steps (`run_steps`) in place of `run`'s cohort-file ones: training every scenario's baseline,
then promoting each through the registry's checks.
then promoting each through the registry's checks. `--reference-dir` trains on a folder of EEGs on this machine
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
"""
import argparse
import sys
@@ -20,9 +21,18 @@ def run_steps(args: argparse.Namespace) -> int:
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
return 2
environment = args.environment.upper()
s = SETTINGS
if getattr(args, "reference_dir", None):
from models.tea.eeg.reference import local
s = local(SETTINGS, folder=args.reference_dir, ages_table=args.reference_ages,
name=args.reference_name or "local", line_hz=args.line_hz or 60.0)
elif getattr(args, "reference_ages", None) or getattr(args, "line_hz", None):
print("--reference-ages and --line-hz go with --reference-dir", file=sys.stderr)
return 2
versions: dict[str, str] = {}
if args.train:
for scenario, (version, new) in train.train_all(SETTINGS, environment).items():
for scenario, (version, new) in train.train_all(s, environment).items():
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
versions[scenario] = version
if not args.promote:
+62
View File
@@ -0,0 +1,62 @@
"""A reference cohort on the training machine's own disk: the site's EEGs, which never leave it.
`local_studies` lists a folder's EDFs (at any depth) with the age of each child at the recording, within
`[reference] ages`. The age comes from the ages table when one is given (`archivo` and `edad_meses` or `edad_anos`
columns, one row per file name) and from each EDF's header (recording start minus birth date) otherwise. A file with
no age is left out. Paths stay in the listing on this machine; what leaves it is the trained baselines and the
listing's hash (`train.Listing`).
"""
import dataclasses
from pathlib import Path
import pandas as pd
from models.tea.eeg.settings import Settings
LOCAL = "local"
def local(s: Settings, *, folder: str | Path, ages_table: str | Path | None = None, name: str = "local",
line_hz: float = 60.0, ages: tuple[float, float] | None = None) -> Settings:
"""`s` with its reference cohort replaced by a folder on this machine."""
r = dataclasses.replace(s.reference, name=name, storage=LOCAL, prefix=str(Path(folder).resolve()),
ages_table=str(Path(ages_table).resolve()) if ages_table else "", line_hz=float(line_hz),
ages=tuple(ages) if ages else s.reference.ages)
return dataclasses.replace(s, reference=r)
def _table_ages(path: Path) -> dict[str, float]:
"""Age in months by file name, from a CSV with `archivo` and `edad_meses` (or `edad_anos`)."""
table = pd.read_csv(path)
if "archivo" not in table:
raise ValueError(f"{path.name}: the ages table needs an `archivo` column with each EDF's file name")
if "edad_meses" in table:
months = table["edad_meses"].astype(float)
elif "edad_anos" in table:
months = table["edad_anos"].astype(float) * 12
else:
raise ValueError(f"{path.name}: the ages table needs `edad_meses` or `edad_anos`")
return {str(f): round(float(m), 1) for f, m in zip(table["archivo"], months) if m == m}
def local_studies(s: Settings) -> list[tuple[str, float]]:
"""(path, age in months) of each EDF under the reference folder with an age inside `[reference] ages`."""
from tea.contracts import header_age_months
r = s.reference
folder = Path(r.prefix)
if not folder.is_dir():
raise FileNotFoundError(f"no folder {folder}")
by_name = _table_ages(Path(r.ages_table)) if r.ages_table else None
found = []
for path in sorted(p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() == ".edf"):
if by_name is not None:
age = by_name.get(path.name)
else:
try:
age = header_age_months(path, days_per_month=s.days_per_month)
except Exception: # noqa: BLE001 -- an unreadable header is a file with no age
age = None
if age is not None and r.ages[0] <= age <= r.ages[1]:
found.append((str(path), age))
return found
+1
View File
@@ -34,6 +34,7 @@ class Reference:
ages_table: str
line_hz: float
ages: tuple[float, float]
storage: str = "s3" # "s3": the cluster's S3, read in a worker; "local": a folder on this machine (`reference.py`)
@dataclass(frozen=True)
+26 -15
View File
@@ -52,10 +52,15 @@ class Listing:
def list_reference(s: Settings) -> list[tuple[str, float]]:
"""In a worker: (s3 path, age in months) of each reference EDF with an age inside `[reference] ages`."""
"""In a worker: (path, age in months) of each reference EDF with an age inside `[reference] ages`, from the
cluster's S3 or, for a cohort on this machine, from its folder (`reference.local_studies`)."""
from tea.pipeline.storage import s3
from models.tea.eeg.reference import LOCAL, local_studies
r = s.reference
if r.storage == LOCAL:
return local_studies(s)
fs = s3()
paths = fs.find(r.prefix)
tables = [p for p in paths if p.endswith(r.ages_table)]
@@ -153,11 +158,6 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
tags = {"domain": DOMAIN, "scenario": scenario, MODEL_SHA_TAG: sha,
COHORT_URL_TAG: f"{DOMAIN}/{REFERENCE_SOURCE}/{s.reference.name}", COHORT_SOURCE_TAG: REFERENCE_SOURCE,
**expected_tags(scenario, found, s, environment)}
for key, value in {**tags, **code_version()}.items():
client.set_tag(run_id, key, value)
for key, value in tags.items():
client.set_model_version_tag(name, version, key, value)
features = [c for c in data.columns if c != "age_months"]
present = {f: int(data[f].notna().sum()) for f in features}
params = getattr(module, "baseline_params", {}) or {}
@@ -179,21 +179,32 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
"edades_cubiertas_meses": list(covered) if covered else None,
"n_efectivo_minimo": n_min},
}
for kind, record in routines.items():
client.log_text(run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
client.log_metric(run_id, "n_referencia", len(data))
for feature, n in present.items():
client.log_metric(run_id, f"n.{feature}", n)
metrics = {"n_referencia": len(data), **{f"n.{feature}": n for feature, n in present.items()}}
if covered:
client.log_metric(run_id, "edad_min_cubierta", covered[0])
client.log_metric(run_id, "edad_max_cubierta", covered[1])
client.update_model_version(name, version, description=(
metrics.update(edad_min_cubierta=covered[0], edad_max_cubierta=covered[1])
description = (
f"Curva de referencia por edad de {biomarker}{f' en sueño {phase}' if phase else ''}, entrenada en "
f"{s.reference.name} ({len(data)} estudios de {s.reference.ages[0]:g} a {s.reference.ages[1]:g} meses). "
"Pendiente de validación clínica."))
"Pendiente de validación clínica.")
record(client, name, version, run_id, tags=tags, routines=routines, metrics=metrics, description=description)
return version
def record(client, name: str, version: str, run_id: str, *, tags: dict[str, str], routines: dict[str, dict],
metrics: dict[str, float], description: str) -> None:
"""What the registry's promotion checks read, on a version and its run: the tags (on both, with the code
version on the run), the routine records, the metrics and the description."""
for key, value in {**tags, **code_version()}.items():
client.set_tag(run_id, key, value)
for key, value in tags.items():
client.set_model_version_tag(name, version, key, value)
for kind, routine in routines.items():
client.log_text(run_id, json.dumps(routine, ensure_ascii=False, indent=1, default=str), routine_path(kind))
for key, value in metrics.items():
client.log_metric(run_id, key, value)
client.update_model_version(name, version, description=description)
def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Listing | None = None,
studies: list[ReferenceStudy] | None = None) -> dict[str, tuple[str, bool]]:
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same