206 lines
11 KiB
Python
206 lines
11 KiB
Python
"""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
|