Layout: per-domain folders, io, steps and pipelines, and one command line

This commit is contained in:
2026-11-04 12:48:41 -06:00
parent ec85cae5aa
commit 2d22409e1f
36 changed files with 164 additions and 200 deletions
+1
View File
@@ -0,0 +1 @@
"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes."""
+50
View File
@@ -0,0 +1,50 @@
"""The contract through which a model is asked for the risk of a cohort build's members.
The caller hands the estimator the wide frame of a cohort build, `(columns, rows)`, with
`columns = ["pac_id", "fecha_indice", <variables>]`. The estimator returns one `Risk` per member and
horizon, and its `Provenance`: the keys that reconcile a batch with MLflow (MLflow keeps no rows and no
patients).
`Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`,
`evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what Persistance's `PROCEDENCIA` expects.
This module doesn't import the kit, Persistance or the orchestration: it receives lists.
"""
from dataclasses import asdict, dataclass
from typing import NamedTuple, Protocol, runtime_checkable
class Risk(NamedTuple):
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # years from the index date; 0 = prevalent
probabilidad: float # 0 to 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Provenance:
"""Which model the risks come from: the keys a batch stores."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def as_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class RiskEstimator(Protocol):
"""What every risk model the orchestration can call provides."""
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
outcome: str # what it predicts ("cin2_mas")
def provenance(self) -> Provenance: ...
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
+34
View File
@@ -0,0 +1,34 @@
"""ONNX checkpoint inspection (ML-01b, MLD-03).
Writing/storing a checkpoint is `models.io.training.TrainingRun.log_artifact`,
which hands it to MLflow directly — nothing here manages storage paths.
`onnx` is an optional dependency (`models[export]`); without it
`inspect_onnx_metadata` returns `{"available": False}`.
"""
from pathlib import Path
from typing import Any
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
onnx.checker.check_model(model)
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
+132
View File
@@ -0,0 +1,132 @@
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
produced it. Callers go through `PredictionService` rather than calling
`model.predict(...)` directly.
"""
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
from core.governance.models import ModelPrediction
from mlflow import MlflowException
from persistance.governance import model_prediction_repository
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
class Predictor(Protocol):
"""What the service needs from a model."""
def predict(self, data: Any) -> Any: ...
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a model and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: Predictor,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con models.io.registry.registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
+282
View File
@@ -0,0 +1,282 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own: the promotion checks tied to the cohort a version was
trained on and to the validation-report convention.
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
of its versions, never stored here and read from MLflow on every call.
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
database). A version points to its build with the `kit.armado_id` tag, and
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
"""
import re
import tempfile
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.governance import model_prediction_repository
from sqlmodel import select
from models.io.export import inspect_onnx_metadata
DOMAINS = ("cacu", "cama", "tea")
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
ARMADO_TAG = "kit.armado_id"
MODEL_SHA_TAG = "modelo_sha"
@dataclass(frozen=True)
class PromotionCheck:
code: str
requirement: str
passed: bool
detail: str = ""
class PromotionBlocked(Exception):
def __init__(self, checks: list[PromotionCheck]):
self.checks = checks
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
@dataclass(frozen=True)
class ResolvedVersion:
"""The version a caller will use, with what it needs to load it and to say where risks came from.
`status` is the version's status when it was resolved (`produccion`, `candidata`, `desarrollo` or
`retirada`)."""
domain: str
scenario: str
version: str
run_id: str
status: str
modelo_sha: str | None
@property
def model_uri(self) -> str:
return f"models:/{registered_name(self.domain, self.scenario)}/{self.version}"
class ModelRegistry:
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
def __init__(self, client: MlflowClient | None = None):
self._client = client
@property
def client(self) -> MlflowClient:
return self._client or MlflowClient()
def get(self, domain: str, scenario: str, version: str):
try:
return self.client.get_model_version(registered_name(domain, scenario), version)
except MlflowException as exc:
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
"""Every version, newest first. `scenario` needs `domain`; `domain`
alone matches every scenario of that domain (MLflow's own
`search_registered_models` LIKE filter); neither matches everything."""
if domain and domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
if scenario and not re.fullmatch(r"[\w-]+", scenario):
raise ValueError(f"escenario inválido: {scenario!r}")
if domain and scenario:
names = [registered_name(domain, scenario)]
elif domain:
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
else:
return [self._describe(mv) for mv in self.client.search_model_versions()]
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
def _status(self, mv) -> str:
try:
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
if str(production.version) == str(mv.version):
return "produccion"
except MlflowException:
pass
if mv.tags.get("retirada_en"):
return "retirada"
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version))
def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion:
"""With no `version`, the one holding the `produccion` alias; with a version, that one, whatever
its status (to test or compare a candidate). The status travels with it: confirming risks only
accepts versions that were in production."""
if version is None:
try:
mv = self.client.get_model_version_by_alias(registered_name(domain, scenario), PRODUCTION_ALIAS)
except MlflowException as exc:
raise LookupError(f"({domain}, {scenario}) has no version in production") from exc
else:
mv = self.get(domain, scenario, version)
return ResolvedVersion(domain, scenario, str(mv.version), mv.run_id, self._status(mv),
mv.tags.get(MODEL_SHA_TAG))
def register(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.io.training.TrainingRun` directly."""
from models.io.training import TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(domain, scenario)
for tag, uri in reports.items():
self.client.set_model_version_tag(name, version, tag, uri or "")
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
"""Logs an artifact file to the run behind an already-registered
version (ML-01a/b), e.g. a checkpoint exported after training.
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
rejected (400) instead of silently stored."""
mv = self.get(domain, scenario, version)
kind_value = kind.value if hasattr(kind, "value") else str(kind)
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / filename
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
return {
"name": mv.name,
"version": str(mv.version),
"run_id": mv.run_id,
"tags": dict(mv.tags),
"metrics": dict(run.data.metrics),
"created_at": _iso(mv.creation_timestamp),
"status": self._status(mv),
}
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
return self._describe(self.get(domain, scenario, version))
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
"""Everything a version came from and produced: its cohort build (with
its attrition), logged artifacts and predictions."""
mv = self.get(domain, scenario, version)
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
return {
"model_version": self.describe(domain, scenario, version),
"cohorte_armado": armado,
"cohorte_exclusiones": exclusiones,
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
}
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
mv = self.get(domain, scenario, version)
run = self.client.get_run(mv.run_id)
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
metrics = run.data.metrics
artifacts = self.client.list_artifacts(mv.run_id)
return [
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
PromotionCheck(
"ML-03",
"enlazada al armado de cohorte con el que se entrenó",
armado is not None,
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
]
def promote(self, domain: str, scenario: str, version: str):
"""Makes this the production version of its scenario, tagging the
previous one `retirada_en`. Promotion is always a manual step
(MLD-01/01b)."""
checks = self.checks(domain, scenario, version)
if not all(check.passed for check in checks):
raise PromotionBlocked(checks)
name = registered_name(domain, scenario)
try:
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
if str(previous.version) != str(version):
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
except MlflowException:
pass
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
return self.get(domain, scenario, version)
def retire(self, domain: str, scenario: str, version: str):
"""Withdraws a version from production; its scenario has no active
model until another one is promoted, so predictions stop."""
name = registered_name(domain, scenario)
try:
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
active = None
if active is None or str(active.version) != str(version):
raise ValueError("la versión no está en producción")
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
return self.get(domain, scenario, version)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _iso(epoch_millis: int) -> str:
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
registry = ModelRegistry()
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
"""The kit cohort build a version was trained on, and its attrition steps."""
if not armado_id:
return None, []
cohortes = import_module(f"persistance.{domain}").cohorte_repository
armado = cohortes.get(int(armado_id))
if armado is None:
return None, []
exclusion = cohortes.cohortes.CohorteExclusion
pasos = cohortes.leer(lambda sesion: sesion.exec(
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
"armado_en": armado.armado_en.isoformat()},
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
+14
View File
@@ -0,0 +1,14 @@
"""Finds a domain's Persistance repository by name, the same objects WebApi writes with."""
import importlib
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
+203
View File
@@ -0,0 +1,203 @@
"""Bookkeeping around a training run (ML-01..ML-05).
Does not train anything. It opens an MLflow run, records which cohort
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
methods instead of the fluent API's global active run, so two runs in one
process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
tagged with the git commit of this package's repository and whether it had
uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
delivered images). A PROD run only logs models whose class lives in a module, at a
known commit, never one defined in a notebook.
"""
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Any
import mlflow.pyfunc
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.repository import Repository
from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name
from models.io.repositories import resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
GIT_DIRTY_TAG = "models.git.dirty"
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
def code_version() -> dict[str, str]:
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
nothing is recorded."""
root = Path(__file__).resolve().parent
try:
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = os.environ.get(GIT_COMMIT_ENV)
return {GIT_COMMIT_TAG: commit} if commit else {}
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
def model_sha(model_dir: str | Path) -> str:
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
out because it carries ids and dates, so the same model saved twice has the same sha."""
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository: Repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs require `cohorte_armado_id`, the indicator kit cohort build they were
trained on, so their metrics trace back to that data (ML-03); dev runs may
omit it.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
):
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
environment = Environment(environment)
if environment is Environment.PROD and cohorte_armado_id is None:
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohorte_armado_id = cohorte_armado_id
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
)
self.run_id = run.info.run_id
self.modelo_sha: str | None = None
if cohorte_armado_id is not None:
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
return ReadOnlyRepository(resolve_repository(self.domain, entity))
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
named for its kind."""
kind = ArtifactKind(kind)
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
`modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input
example, so no patient data reaches MLflow."""
if self.modelo_sha is not None:
raise RuntimeError("this run already logged its model")
if self.environment is Environment.PROD and type(python_model).__module__ == "__main__":
raise ValueError("a PROD run only logs models whose class lives in a module; "
f"{type(python_model).__name__} was defined in a notebook or script")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / MODEL_PATH
mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature)
sha = model_sha(path)
self.client.log_artifacts(self.run_id, str(path), MODEL_PATH)
self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha)
self.modelo_sha = sha
return sha
def finish(
self,
*,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""Logs metrics/params to the run, registers it as a new version of
`<domain>-<scenario>` tagged with `models.io.registry`'s promotion
inputs (environment, cohort link, report URIs), and returns the new
version string. Call once, after training (and artifact logging)
completes."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
for key, value in (metrics or {}).items():
self.client.log_metric(self.run_id, key, value)
for key, value in (hyperparameters or {}).items():
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
name = registered_name(self.domain, self.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
if self.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
if self.modelo_sha is not None:
version_tags[MODEL_SHA_TAG] = self.modelo_sha
version_tags.update({key: uri for key, uri in reports.items() if uri})
source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}"
model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags)
self.client.set_terminated(self.run_id)
return str(model_version.version)