drop cohort builder plumbing; use kit cohorte_armado builds for MLflow lineage
This commit is contained in:
+2
-10
@@ -29,16 +29,8 @@ class ScreeningModel(ABC):
|
||||
return resolve_repository(self.domain, entity)
|
||||
|
||||
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
|
||||
"""Every row of `entity` as plain dicts, paged through the
|
||||
repository so a large table is never loaded in one go."""
|
||||
repository = self.repository(entity)
|
||||
offset = 0
|
||||
while True:
|
||||
page = repository.list(limit=batch_size, offset=offset, **filters)
|
||||
yield from (row.model_dump() for row in page)
|
||||
if len(page) < batch_size:
|
||||
return
|
||||
offset += batch_size
|
||||
"""Every row of `entity` as plain dicts, read in batches."""
|
||||
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
|
||||
|
||||
@abstractmethod
|
||||
def train(self, data: Any = None) -> None:
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
"""Cohort construction, versioning and exclusion tracking (EL-01..EL-07,
|
||||
TRIPOD+AI 20a). A `CohortBuilder` turns a domain's clinical episodes into a
|
||||
frozen, hashed cohort (`CohortVersion` + `CohortMember`) that training
|
||||
reads instead of the live tables, which may change later.
|
||||
|
||||
- `build()` (training time, EL-04a) applies every `ExclusionCriterion`,
|
||||
logs each exclusion with its reason (EL-05) and the per-criterion counts
|
||||
(EL-07).
|
||||
- `evaluate_applicability()` (production, EL-04b) checks one new row
|
||||
against the criteria marked `applicable_in_production` only; criteria
|
||||
that need future follow-up are never among them. It writes nothing.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from models.base import resolve_repository
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_member_repository,
|
||||
cohort_version_repository,
|
||||
)
|
||||
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortMember, CohortVersion
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExclusionCriterion:
|
||||
code: str
|
||||
reason_code: str
|
||||
predicate: Callable[[dict[str, Any]], bool]
|
||||
"""Returns True when the row should be EXCLUDED."""
|
||||
applicable_in_production: bool = False
|
||||
"""EL-04b: whether this criterion is also checked on new rows in
|
||||
production. Leave False for criteria that depend on future follow-up,
|
||||
which can only be evaluated when building the training table."""
|
||||
|
||||
|
||||
def compute_version_hash(*, criteria_version: str, criterion_codes: Sequence[str], episode_ids: Sequence[int]) -> str:
|
||||
"""EL-02/EL-03: deterministic hash of the criteria version, the
|
||||
criterion codes applied and the source episode ids. A change in any of
|
||||
them, such as new patients or a longer analysis period, yields a new
|
||||
version."""
|
||||
payload = json.dumps(
|
||||
{
|
||||
"criteria_version": criteria_version,
|
||||
"criterion_codes": sorted(criterion_codes),
|
||||
"episode_ids": sorted(episode_ids),
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class CohortBuilder:
|
||||
"""Builds the cohort for one clinical scenario (one model per scenario,
|
||||
one cohort table per model). Subclasses set `criteria` and may override
|
||||
`fetch_episodes` (EL-01)."""
|
||||
|
||||
domain: str
|
||||
scenario: str
|
||||
criteria_version: str
|
||||
criteria: Sequence[ExclusionCriterion] = ()
|
||||
|
||||
def fetch_episodes(self) -> list[dict[str, Any]]:
|
||||
"""Episode rows as plain dicts (EL-01). The default pages through
|
||||
`persistance.<domain>.episodio_clinico_repository`; override it when
|
||||
a scenario needs extra joins to build its features."""
|
||||
repository = resolve_repository(self.domain, "episodio_clinico")
|
||||
episodes: list[dict[str, Any]] = []
|
||||
offset = 0
|
||||
while True:
|
||||
page = repository.list(limit=500, offset=offset)
|
||||
episodes.extend(row.model_dump() for row in page)
|
||||
if len(page) < 500:
|
||||
break
|
||||
offset += 500
|
||||
return episodes
|
||||
|
||||
def build(self, *, description: str | None = None) -> CohortVersion:
|
||||
episodes = self.fetch_episodes()
|
||||
n_source = len(episodes)
|
||||
|
||||
excluded_ids: set[int] = set()
|
||||
exclusion_rows: list[CohortExclusion] = []
|
||||
exclusion_counts: dict[tuple[str, str], int] = {}
|
||||
|
||||
for episode in episodes:
|
||||
episode_id = episode.get("episodio_id")
|
||||
for criterion in self.criteria:
|
||||
if episode_id in excluded_ids:
|
||||
break
|
||||
if criterion.predicate(episode):
|
||||
excluded_ids.add(episode_id)
|
||||
exclusion_rows.append(
|
||||
CohortExclusion(
|
||||
cohort_version_id=0, # filled in once the CohortVersion exists
|
||||
pac_id_hospital=episode.get("pac_id_hospital", ""),
|
||||
episodio_id=episode_id,
|
||||
criterion_code=criterion.code,
|
||||
reason_code=criterion.reason_code,
|
||||
)
|
||||
)
|
||||
key = (criterion.code, criterion.reason_code)
|
||||
exclusion_counts[key] = exclusion_counts.get(key, 0) + 1
|
||||
|
||||
included = [e for e in episodes if e.get("episodio_id") not in excluded_ids]
|
||||
|
||||
version_hash = compute_version_hash(
|
||||
criteria_version=self.criteria_version,
|
||||
criterion_codes=[c.code for c in self.criteria],
|
||||
episode_ids=[e.get("episodio_id") for e in episodes if e.get("episodio_id") is not None],
|
||||
)
|
||||
|
||||
cohort_version = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain=self.domain,
|
||||
scenario=self.scenario,
|
||||
criteria_version=self.criteria_version,
|
||||
version_hash=version_hash,
|
||||
source_table=f"{self.domain}.episodioclinico",
|
||||
description=description,
|
||||
n_source=n_source,
|
||||
n_included=len(included),
|
||||
)
|
||||
)
|
||||
|
||||
for row in exclusion_rows:
|
||||
row.cohort_version_id = cohort_version.cohort_version_id
|
||||
if exclusion_rows:
|
||||
with cohort_exclusion_repository.open_session() as session:
|
||||
for row in exclusion_rows:
|
||||
session.add(row)
|
||||
session.commit()
|
||||
|
||||
if exclusion_counts:
|
||||
with cohort_exclusion_count_repository.open_session() as session:
|
||||
for (criterion_code, reason_code), count in exclusion_counts.items():
|
||||
session.add(
|
||||
CohortExclusionCount(
|
||||
cohort_version_id=cohort_version.cohort_version_id,
|
||||
criterion_code=criterion_code,
|
||||
reason_code=reason_code,
|
||||
count=count,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
|
||||
if included:
|
||||
with cohort_member_repository.open_session() as session:
|
||||
for episode in included:
|
||||
session.add(
|
||||
CohortMember(
|
||||
cohort_version_id=cohort_version.cohort_version_id,
|
||||
pac_id_hospital=episode.get("pac_id_hospital", ""),
|
||||
episodio_id=episode.get("episodio_id"),
|
||||
feature_snapshot=json.dumps(episode, default=str, sort_keys=True),
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
|
||||
return cohort_version
|
||||
|
||||
def evaluate_applicability(self, row: dict[str, Any]) -> bool:
|
||||
"""EL-04b: production gate. Returns False if any criterion marked
|
||||
`applicable_in_production` would exclude the row. Writes nothing;
|
||||
exclusion logs belong to the training-time build (EL-04a)."""
|
||||
return not any(c.predicate(row) for c in self.criteria if c.applicable_in_production)
|
||||
|
||||
|
||||
COHORT_BUILDERS: dict[tuple[str, str], type[CohortBuilder]] = {}
|
||||
|
||||
|
||||
def register_cohort_builder(cls: type[CohortBuilder]) -> type[CohortBuilder]:
|
||||
"""Registers a scenario's builder so the API can list and run it:
|
||||
|
||||
@register_cohort_builder
|
||||
class TamizajeCaCu(CohortBuilder):
|
||||
domain, scenario, criteria_version = "cacu", "tamizaje", "v1"
|
||||
criteria = [ExclusionCriterion("EDAD", "fuera_de_rango", lambda e: ..., applicable_in_production=True)]
|
||||
"""
|
||||
COHORT_BUILDERS[(cls.domain, cls.scenario)] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def describe_builder(cls: type[CohortBuilder]) -> dict[str, Any]:
|
||||
return {
|
||||
"domain": cls.domain,
|
||||
"scenario": cls.scenario,
|
||||
"criteria_version": cls.criteria_version,
|
||||
"criteria": [
|
||||
{"code": c.code, "reason_code": c.reason_code, "applicable_in_production": c.applicable_in_production}
|
||||
for c in cls.criteria
|
||||
],
|
||||
}
|
||||
+12
-11
@@ -22,6 +22,9 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlmodel import select
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from core.ocr import OcrEstatus
|
||||
@@ -208,18 +211,16 @@ def run_pending_extractions(
|
||||
from core.governance.models import ExtractionRun
|
||||
|
||||
summary = OcrRunSummary()
|
||||
pk_name = next(iter(repository.model.__table__.primary_key.columns)).name
|
||||
candidates = repository.list(limit=limit)
|
||||
model = repository.model
|
||||
primary_key = list(model.__table__.primary_key.columns)
|
||||
estatus = getattr(model, spec.estatus_field)
|
||||
with_report = getattr(model, spec.blob_field).is_not(None)
|
||||
done = estatus == OcrEstatus.REALIZADO.value
|
||||
with repository.open_session() as session:
|
||||
for row in candidates:
|
||||
pk_value = getattr(row, pk_name)
|
||||
tracked = session.get(repository.model, pk_value)
|
||||
if tracked is None or getattr(tracked, spec.blob_field, None) is None:
|
||||
continue
|
||||
if getattr(tracked, spec.estatus_field, None) == OcrEstatus.REALIZADO:
|
||||
summary.skipped_already_done += 1
|
||||
continue
|
||||
|
||||
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
|
||||
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
|
||||
for tracked in session.exec(pending).all():
|
||||
pk_value = getattr(tracked, primary_key[0].name)
|
||||
started_at = datetime.now(timezone.utc)
|
||||
try:
|
||||
result = extractor.extract(getattr(tracked, spec.blob_field))
|
||||
|
||||
+24
-25
@@ -1,27 +1,26 @@
|
||||
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
|
||||
produced it. WebApi's `/predict` routes go through `PredictionService`
|
||||
rather than calling `model.predict(...)` directly.
|
||||
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
|
||||
|
||||
from mlflow import MlflowException
|
||||
|
||||
from core.governance.models import ModelPrediction
|
||||
from models.base import ScreeningModel
|
||||
from models.cohort import CohortBuilder
|
||||
from models.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||
from mlflow import MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||
|
||||
|
||||
@dataclass
|
||||
class Interpretability:
|
||||
"""MLD-03: campos mínimos que toda estimación debe poder reportar para
|
||||
interpretabilidad clínica. Todos opcionales: cada modelo llena los que
|
||||
apliquen a su método (p. ej. odds_ratio en una regresión logística,
|
||||
hazard_ratio en un modelo de supervivencia)."""
|
||||
"""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
|
||||
@@ -46,10 +45,9 @@ class PredictionService:
|
||||
"""Runs a `ScreeningModel` and records its predictions against the
|
||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
||||
|
||||
If `cohort_builder` is given, each row is checked with
|
||||
`evaluate_applicability` (EL-04b). Inapplicable rows are still scored
|
||||
but stored with `applicability_passed=False`, unless
|
||||
`reject_inapplicable` is set.
|
||||
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__(
|
||||
@@ -58,13 +56,13 @@ class PredictionService:
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
cohort_builder: CohortBuilder | None = None,
|
||||
aplicable: Callable[[dict], bool] | None = None,
|
||||
reject_inapplicable: bool = False,
|
||||
):
|
||||
self.model = model
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.cohort_builder = cohort_builder
|
||||
self.aplicable = aplicable
|
||||
self.reject_inapplicable = reject_inapplicable
|
||||
|
||||
def active_model_version(self):
|
||||
@@ -86,26 +84,27 @@ class PredictionService:
|
||||
) -> 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; WebApi maps it to 501.
|
||||
propagated unchanged.
|
||||
"""
|
||||
applicability_passed = True
|
||||
if self.cohort_builder is not None:
|
||||
row = data if isinstance(data, dict) else {}
|
||||
applicability_passed = self.cohort_builder.evaluate_applicability(row)
|
||||
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 before looking up the version so an unimplemented model
|
||||
# surfaces as NotImplementedError even with no ModelVersion seeded.
|
||||
# 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 — "
|
||||
"promueve una con models.registry.registry.promote antes de predecir"
|
||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
||||
"promueva una con models.registry.registry.promote antes de predecir"
|
||||
)
|
||||
|
||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
|
||||
+53
-57
@@ -1,25 +1,35 @@
|
||||
"""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 our cohort versioning and
|
||||
validation-report convention.
|
||||
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, read from MLflow on every call.
|
||||
`models.cohort`'s own `CohorteArmadoBase`/`EvaluacionRiesgoLoteBase` reference
|
||||
MLflow the same way: by `mlflow_run_id`, never by copying its rows.
|
||||
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 mlflow import MlflowException, MlflowClient
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from core.governance.enums import Environment
|
||||
from persistance.governance import cohort_exclusion_count_repository, cohort_version_repository, model_prediction_repository
|
||||
from models.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"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -42,10 +52,7 @@ def registered_name(domain: str, scenario: str) -> str:
|
||||
|
||||
|
||||
class ModelRegistry:
|
||||
"""`registry` below is a module-level singleton, so `client` is resolved
|
||||
fresh on every access instead of cached at construction time — otherwise
|
||||
it would permanently bind to whatever `MLFLOW_TRACKING_URI` was set at
|
||||
import time, ignoring any later change (every test sets its own)."""
|
||||
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
|
||||
|
||||
def __init__(self, client: MlflowClient | None = None):
|
||||
self._client = client
|
||||
@@ -54,8 +61,6 @@ class ModelRegistry:
|
||||
def client(self) -> MlflowClient:
|
||||
return self._client or MlflowClient()
|
||||
|
||||
# -- reading --------------------------------------------------------------
|
||||
|
||||
def get(self, domain: str, scenario: str, version: str):
|
||||
try:
|
||||
return self.client.get_model_version(registered_name(domain, scenario), version)
|
||||
@@ -66,6 +71,10 @@ class ModelRegistry:
|
||||
"""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:
|
||||
@@ -88,15 +97,13 @@ class ModelRegistry:
|
||||
def status(self, domain: str, scenario: str, version: str) -> str:
|
||||
return self._status(self.get(domain, scenario, version))
|
||||
|
||||
# -- registering --------------------------------------------------------------
|
||||
|
||||
def register(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohort_version_id: int | None = None,
|
||||
cohorte_armado_id: int | None = None,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
@@ -105,7 +112,7 @@ class ModelRegistry:
|
||||
In-process training uses `models.training.TrainingRun` directly."""
|
||||
from models.training import TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohort_version_id=cohort_version_id)
|
||||
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:
|
||||
@@ -119,15 +126,9 @@ class ModelRegistry:
|
||||
|
||||
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.
|
||||
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."""
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from core.governance.enums import ArtifactKind
|
||||
from models.export import inspect_onnx_metadata
|
||||
|
||||
mv = self.get(domain, scenario, version)
|
||||
kind_value = kind.value if hasattr(kind, "value") else str(kind)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -153,39 +154,32 @@ class ModelRegistry:
|
||||
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 (hash and
|
||||
exclusion counts), logged artifacts and predictions."""
|
||||
"""Everything a version came from and produced: its cohort build (with
|
||||
its attrition), logged artifacts and predictions."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
cohort_version_id = mv.tags.get("cohort_version_id")
|
||||
cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None
|
||||
exclusions = (
|
||||
cohort_exclusion_count_repository.list(limit=500, cohort_version_id=cohort.cohort_version_id) if cohort else []
|
||||
)
|
||||
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
return {
|
||||
"model_version": self.describe(domain, scenario, version),
|
||||
"cohort_version": cohort.model_dump() if cohort else None,
|
||||
"cohort_exclusions": [count.model_dump() for count in exclusions],
|
||||
"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)],
|
||||
}
|
||||
|
||||
# -- promotion --------------------------------------------------------------------
|
||||
|
||||
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)
|
||||
cohort_version_id = mv.tags.get("cohort_version_id")
|
||||
cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None
|
||||
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 a la versión de cohorte con la que se entrenó",
|
||||
cohort is not None,
|
||||
f"hash {cohort.version_hash[:12]}" if cohort else "sin cohorte",
|
||||
"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", "")),
|
||||
@@ -214,7 +208,7 @@ class ModelRegistry:
|
||||
|
||||
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 (503)."""
|
||||
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)
|
||||
@@ -226,28 +220,30 @@ class ModelRegistry:
|
||||
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
def compare(self, domain: str, scenario: str, a: str, b: str) -> dict[str, Any]:
|
||||
"""Metric-by-metric difference (b - a) between two versions."""
|
||||
ma = self.client.get_run(self.get(domain, scenario, a).run_id).data.metrics
|
||||
mb = self.client.get_run(self.get(domain, scenario, b).run_id).data.metrics
|
||||
rows = []
|
||||
for name in sorted(set(ma) | set(mb)):
|
||||
va, vb = ma.get(name), mb.get(name)
|
||||
delta = vb - va if va is not None and vb is not None else None
|
||||
rows.append({"metric": name, "a": va, "b": vb, "delta": delta})
|
||||
return {"a": self.describe(domain, scenario, a), "b": self.describe(domain, scenario, b), "metrics": rows}
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _iso(epoch_millis: int) -> str:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
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])
|
||||
|
||||
+35
-27
@@ -1,28 +1,29 @@
|
||||
"""Bookkeeping around a training run (ML-01..ML-05).
|
||||
|
||||
Does not train anything. It opens an MLflow run, records which cohort
|
||||
version 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
|
||||
itself owns run tracking, metrics and artifact storage — this class only
|
||||
adds the project-specific tags `finish()` needs for `models.registry`'s
|
||||
promotion checks.
|
||||
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.
|
||||
|
||||
Uses `MlflowClient`'s run-scoped methods (`log_metric(run_id, ...)`, not the
|
||||
fluent `mlflow.log_metric(...)`) rather than MLflow's global active-run
|
||||
stack, so an unfinished run from one `TrainingRun` can never block another
|
||||
one started elsewhere in the same process.
|
||||
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
|
||||
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.base import resolve_repository
|
||||
from models.registry import REPORT_TAGS, registered_name
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.repository import Repository
|
||||
|
||||
from models.base import resolve_repository
|
||||
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
|
||||
|
||||
class ReadOnlyRepository:
|
||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
||||
@@ -47,15 +48,16 @@ class ReadOnlyRepository:
|
||||
def __getattr__(self, name: str):
|
||||
if name in self._WRITE_METHODS:
|
||||
raise PermissionError(
|
||||
f"ML-04: un TrainingRun solo tiene permiso de lectura — '{name}' no está disponible en ReadOnlyRepository."
|
||||
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 `cohort_version_id` so their metrics can be traced to the
|
||||
data that produced them (ML-03); dev runs may omit it.
|
||||
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__(
|
||||
@@ -64,16 +66,18 @@ class TrainingRun:
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohort_version_id: int | None = None,
|
||||
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 cohort_version_id is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar un cohort_version_id.")
|
||||
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.cohort_version_id = cohort_version_id
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
@@ -81,13 +85,16 @@ class TrainingRun:
|
||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
|
||||
)
|
||||
self.run_id = run.info.run_id
|
||||
if cohort_version_id is not None:
|
||||
self.client.set_tag(self.run_id, "cohort_version_id", str(cohort_version_id))
|
||||
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)
|
||||
return experiment.experiment_id if experiment else self.client.create_experiment(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`."""
|
||||
@@ -124,11 +131,12 @@ class TrainingRun:
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
self.client.create_registered_model(name)
|
||||
except MlflowException:
|
||||
pass
|
||||
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.cohort_version_id is not None:
|
||||
version_tags["cohort_version_id"] = str(self.cohort_version_id)
|
||||
if self.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
|
||||
self.client.set_terminated(self.run_id)
|
||||
|
||||
Reference in New Issue
Block a user