Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a4ddad5c8e | |||
| 55dd971a1f |
@@ -13,8 +13,8 @@ WebApi.
|
||||
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
|
||||
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`), dbt's manifest (`read_queries`), and Persistance repositories (`resolve_repository`, `ReadOnlyRepository`, ML-04). |
|
||||
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the hashes of code, files, tables and models (`code_version`, `model_sha`), and `matches`, the one rule for "already done". |
|
||||
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), environment (ML-02), git commit and `log_model` with its `modelo_sha`. In PROD, only models whose class lives in a module. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). |
|
||||
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
|
||||
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), git commit and `log_model` with its `modelo_sha`. In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. |
|
||||
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
|
||||
@@ -22,14 +22,8 @@ WebApi.
|
||||
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
|
||||
| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). |
|
||||
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
|
||||
| `steps/report.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks/<scenario>/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it to one HTML page (`io/rendering.py`), and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. With Quarto, `QUARTO_BIN` and a Python with Jupyter (`QUARTO_PYTHON`). |
|
||||
| `io/rendering.py` | Runs a notebook and renders its page. Renderers are classes (`RENDERERS`, `register_renderer`): `quarto` and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
|
||||
| `pipelines/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
|
||||
| `io/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
|
||||
| `io/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. |
|
||||
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
|
||||
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
|
||||
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Training records its five routines (`sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`). Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
|
||||
| `steps/report.py`, `io/rendering.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks/<scenario>/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). |
|
||||
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
|
||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
|
||||
@@ -117,21 +117,6 @@ def _report_eda(args: argparse.Namespace) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _serve_notebooks(args: argparse.Namespace) -> int:
|
||||
"""The runner container's loop (`models.io.notebook_jobs.serve`)."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from models.io.notebook_jobs import JOBS_DIR_ENV, serve
|
||||
|
||||
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
|
||||
if not folder:
|
||||
print(f"no jobs folder: pass --jobs or set {JOBS_DIR_ENV}", file=sys.stderr)
|
||||
return 2
|
||||
serve(Path(folder), once=args.once)
|
||||
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)):
|
||||
@@ -419,14 +404,6 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
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.set_defaults(run=lambda args: _run(run, args))
|
||||
|
||||
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
|
||||
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
|
||||
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
|
||||
serve = notebook_actions.add_parser("serve", help="run each job left in the jobs folder, one at a time")
|
||||
serve.add_argument("--jobs", help="the jobs folder; NOTEBOOK_JOBS_DIR by default")
|
||||
serve.add_argument("--once", action="store_true", help="run the jobs waiting now and stop")
|
||||
serve.set_defaults(run=_serve_notebooks)
|
||||
return parser
|
||||
|
||||
|
||||
|
||||
@@ -124,65 +124,6 @@ def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dic
|
||||
"positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())}
|
||||
|
||||
|
||||
def _dates(frame: pd.DataFrame) -> dict:
|
||||
if frame.empty:
|
||||
return {"n": 0}
|
||||
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
|
||||
"last_index_date": str(frame["fecha_indice"].max())}
|
||||
|
||||
|
||||
def sampling(outcome: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
|
||||
"""MUESTREO: who could be used, and how they were split."""
|
||||
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
|
||||
"train_fraction": SETTINGS["train_fraction"], "members": len(outcome),
|
||||
"left_out_unknown_outcome": int((~outcome["known"]).sum()), "train": _dates(train), "test": _dates(test)}
|
||||
|
||||
|
||||
def missing_data(predictors: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
|
||||
"""DATOS_FALTANTES: how many lacked each predictor, and what was done about it."""
|
||||
def missing(frame: pd.DataFrame) -> dict:
|
||||
return {name: int((frame[name] == MISSING).sum()) for name in PREDICTORS}
|
||||
|
||||
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
|
||||
"members": missing(predictors), "train": missing(train), "test": missing(test)}
|
||||
|
||||
|
||||
def analytic_method(fit: Pipeline) -> dict:
|
||||
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
|
||||
logistic = fit.named_steps["logistic"]
|
||||
features = fit.named_steps["encode"].get_feature_names_out()
|
||||
return {"method": "regresión logística sobre los predictores codificados one-hot",
|
||||
"estimator": type(logistic).__name__, "settings": logistic.get_params(),
|
||||
"intercept": float(logistic.intercept_[0]),
|
||||
"coefficients": dict(zip(map(str, features), map(float, logistic.coef_[0])))}
|
||||
|
||||
|
||||
def class_balance(train: pd.DataFrame, test: pd.DataFrame, fit: Pipeline) -> dict:
|
||||
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
|
||||
weight = fit.named_steps["logistic"].class_weight
|
||||
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
|
||||
"train": {str(k): int(v) for k, v in train["y"].value_counts().sort_index().items()},
|
||||
"test": {str(k): int(v) for k, v in test["y"].value_counts().sort_index().items()}}
|
||||
|
||||
|
||||
def output_confidence(test: pd.DataFrame, predict: pd.Series) -> dict:
|
||||
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
|
||||
bins = pd.qcut(predict, q=min(SETTINGS.get("calibration_bins", 10), predict.nunique()), duplicates="drop")
|
||||
table = pd.DataFrame({"p": predict, "y": test["y"]}).groupby(bins, observed=True).agg(
|
||||
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
|
||||
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
|
||||
"brier": float(brier_score_loss(test["y"], predict)),
|
||||
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
|
||||
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
|
||||
|
||||
|
||||
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
|
||||
output_confidence: dict) -> dict:
|
||||
"""Each routine's record, by the kind it's stored under (ML-01a)."""
|
||||
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
|
||||
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
|
||||
|
||||
|
||||
class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
||||
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`
|
||||
for every member, whether their outcome is known or not."""
|
||||
@@ -195,16 +136,14 @@ class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
||||
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
|
||||
|
||||
|
||||
def registered_model(fit: Pipeline, evaluate: dict, routines: dict, lineage: dict, cohort_path: str,
|
||||
cohort_sha256: str, code_sha256: str, environment: str) -> str:
|
||||
def registered_model(fit: Pipeline, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str,
|
||||
code_sha256: str, environment: str) -> str:
|
||||
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content,
|
||||
and which build it is, from the kit or from dbt's rules."""
|
||||
cohort = cohort_reference(lineage, cohort_sha256)
|
||||
armado_id = int(lineage["armado_id"]) if cohort[COHORT_SOURCE_TAG] == "kit" else None
|
||||
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
|
||||
cohorte_armado_id=armado_id, cohort=cohort)
|
||||
for kind, record in routines.items():
|
||||
run.log_routine(kind, record)
|
||||
run.log_model(Cin2Logistic(fit))
|
||||
run.finish(metrics=evaluate, hyperparameters={
|
||||
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256,
|
||||
|
||||
@@ -13,7 +13,8 @@ Quién entra:
|
||||
una biopsia con grado en `grados_cancer`.
|
||||
|
||||
Predictores, todos conocidos a más tardar en el índice: el BI-RADS índice, la calidad de imagen de
|
||||
la mastografía más reciente y cuántas órdenes de estudio hubo antes.
|
||||
la mastografía más reciente y cuántas órdenes de estudio hubo antes. Es el patrón de
|
||||
`tea/cohortes/tamizaje.py`.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
"""Each domain's extraction ranker (`extraction.nlp.ranking.LearnedRanker`), versioned in the model registry as
|
||||
`<domain>-extraccion` like any other model (ML-01a, ML-01b, ML-02).
|
||||
|
||||
Every batch it learns from, whether an answer key or the corrections made while reviewing an import, becomes a new
|
||||
DEV version. That version continues from the latest one, and its run records the five routines of what it learned.
|
||||
Extraction uses the version in production when there is one, and otherwise the latest. `EXTRACTION_RANKER` changes
|
||||
that: `produccion` only takes a version in production, and `ninguno` turns the ranker off.
|
||||
|
||||
What it stores are weights over how candidates were found, never document text, and the routines carry counts only.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
import mlflow.artifacts
|
||||
import mlflow.pyfunc
|
||||
from extraction.nlp.ranking import TRUST_EXAMPLES, Example, LearnedRanker
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
SCENARIO = "extraccion"
|
||||
RANKER_PATH = "ranker/ranker.json"
|
||||
SELECTION_ENV = "EXTRACTION_RANKER"
|
||||
SOURCE_TAG = "ranker.fuente"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache: dict[tuple[str, str], LearnedRanker] = {}
|
||||
|
||||
|
||||
class RankerModel(mlflow.pyfunc.PythonModel):
|
||||
"""The ranker as a pyfunc: `predict` takes rows of named features (a DataFrame column `features` of dicts, or a
|
||||
list of dicts) and returns the probability that each candidate is the right value."""
|
||||
|
||||
def __init__(self, state: dict[str, Any]):
|
||||
self.state = state
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
ranker = LearnedRanker.from_dict(self.state)
|
||||
rows = model_input["features"].tolist() if hasattr(model_input, "columns") else list(model_input)
|
||||
return [ranker.probability(row) for row in rows]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Batch:
|
||||
"""What one learning step saw: the examples, and counts for its routine records."""
|
||||
|
||||
examples: Sequence[Example]
|
||||
source: str
|
||||
documents: int
|
||||
records: int
|
||||
# Per field, how many records had a right value that no candidate proposed.
|
||||
unreachable: dict[str, int]
|
||||
|
||||
|
||||
def _versions(client: MlflowClient, domain: str) -> list:
|
||||
try:
|
||||
return sorted(client.search_model_versions(f"name='{registered_name(domain, SCENARIO)}'"), key=lambda mv: int(mv.version))
|
||||
except MlflowException:
|
||||
return []
|
||||
|
||||
|
||||
def _selected(client: MlflowClient, domain: str, *, for_learning: bool = False):
|
||||
from models.io.registry import PRODUCTION_ALIAS
|
||||
|
||||
mode = os.environ.get(SELECTION_ENV, "auto").strip().lower()
|
||||
if mode == "ninguno" and not for_learning:
|
||||
return None
|
||||
if not for_learning:
|
||||
try:
|
||||
return client.get_model_version_by_alias(registered_name(domain, SCENARIO), PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
if mode == "produccion":
|
||||
return None
|
||||
versions = _versions(client, domain)
|
||||
return versions[-1] if versions else None
|
||||
|
||||
|
||||
def _load(client: MlflowClient, domain: str, mv) -> LearnedRanker:
|
||||
key = (domain, str(mv.version))
|
||||
if key not in _cache:
|
||||
state = mlflow.artifacts.load_dict(f"runs:/{mv.run_id}/{RANKER_PATH}")
|
||||
_cache[key] = LearnedRanker.from_dict(state, version=f"{SCENARIO}:{mv.version}")
|
||||
return _cache[key].copy()
|
||||
|
||||
|
||||
def current(domain: str) -> LearnedRanker | None:
|
||||
"""The ranker extraction should use for `domain`, or `None` to rank by confidence alone."""
|
||||
if os.environ.get(SELECTION_ENV, "").strip().lower() == "ninguno":
|
||||
return None
|
||||
client = MlflowClient()
|
||||
mv = _selected(client, domain)
|
||||
return _load(client, domain, mv) if mv is not None else None
|
||||
|
||||
|
||||
def learn(domain: str, batch: Batch) -> str | None:
|
||||
"""Continues the latest version with `batch` and registers the result as a new DEV version; returns it, or
|
||||
`None` when the batch has nothing to learn from."""
|
||||
from models.io.registry import registry
|
||||
|
||||
if not batch.examples:
|
||||
return None
|
||||
with _lock:
|
||||
client = MlflowClient()
|
||||
parent = _selected(client, domain, for_learning=True)
|
||||
ranker = _load(client, domain, parent) if parent is not None else LearnedRanker()
|
||||
before = _quality(ranker, batch.examples)
|
||||
ranker.learn(batch.examples)
|
||||
after = _quality(ranker, batch.examples)
|
||||
run = TrainingRun(domain=domain, scenario=SCENARIO, environment="DEV")
|
||||
client.set_tag(run.run_id, SOURCE_TAG, batch.source)
|
||||
state = ranker.to_dict()
|
||||
client.log_dict(run.run_id, state, RANKER_PATH)
|
||||
for kind, record in _routines(ranker, batch, parent, before, after).items():
|
||||
run.log_routine(kind, record)
|
||||
run.log_model(RankerModel(state))
|
||||
run.finish(
|
||||
metrics={"ejemplos": len(batch.examples), "ejemplos_acumulados": ranker.examples,
|
||||
**{f"{k}_antes": v for k, v in before.items()}, **{f"{k}_despues": v for k, v in after.items()}},
|
||||
hyperparameters={"tasa_aprendizaje": ranker.learning_rate, "l2": ranker.l2, "ejemplos_confianza_plena": TRUST_EXAMPLES},
|
||||
)
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def _quality(ranker: LearnedRanker, examples: Iterable[Example]) -> dict[str, float]:
|
||||
"""Brier score, log loss and accuracy at even odds of the ranker's probabilities on `examples`. Measured before
|
||||
learning from them, it is an honest estimate on data the ranker had not seen (prequential evaluation)."""
|
||||
examples = list(examples)
|
||||
brier = loss = right = 0.0
|
||||
for example in examples:
|
||||
p = ranker.probability(example.x)
|
||||
y = 1.0 if example.label else 0.0
|
||||
brier += (p - y) ** 2
|
||||
loss -= math.log(max(1e-12, p if example.label else 1.0 - p))
|
||||
right += float((p >= 0.5) == example.label)
|
||||
n = max(1, len(examples))
|
||||
return {"brier": round(brier / n, 4), "log_loss": round(loss / n, 4), "exactitud": round(right / n, 4)}
|
||||
|
||||
|
||||
def _routines(ranker: LearnedRanker, batch: Batch, parent, before: dict, after: dict) -> dict[str, dict[str, Any]]:
|
||||
by_field: dict[str, dict[str, int]] = {}
|
||||
for example in batch.examples:
|
||||
counts = by_field.setdefault(example.field, {"correctos": 0, "incorrectos": 0})
|
||||
counts["correctos" if example.label else "incorrectos"] += 1
|
||||
positives = sum(1 for e in batch.examples if e.label)
|
||||
negatives = len(batch.examples) - positives
|
||||
return {
|
||||
"MUESTREO": {
|
||||
"fuente": batch.source,
|
||||
"documentos": batch.documents,
|
||||
"registros": batch.records,
|
||||
"ejemplos": len(batch.examples),
|
||||
"criterio": "cada lectura propuesta de un campo cuyo valor correcto se conoce es un ejemplo",
|
||||
"por_campo": by_field,
|
||||
},
|
||||
"DATOS_FALTANTES": {
|
||||
"tratamiento": "un campo sin valor conocido no aporta ejemplos; uno que debe quedar vacío marca como incorrectas todas sus lecturas",
|
||||
"valor_correcto_sin_lectura": batch.unreachable,
|
||||
},
|
||||
"METODO_ANALITICO": {
|
||||
"metodo": "regresión logística en línea (AdaGrad con L2) sobre cómo se encontró cada lectura",
|
||||
"version_previa": parent.version if parent is not None else None,
|
||||
"ejemplos_acumulados": ranker.examples,
|
||||
"pesos_principales": dict(ranker.strongest()),
|
||||
},
|
||||
"BALANCE_CLASES": {
|
||||
"correctos": positives,
|
||||
"incorrectos": negatives,
|
||||
"ponderacion": "los correctos pesan incorrectos/correctos, hasta 5",
|
||||
},
|
||||
"CONFIANZA_SALIDA": {
|
||||
"antes_de_aprender": before,
|
||||
"despues_de_aprender": after,
|
||||
"confianza_en_el_modelo": round(ranker.trust, 3),
|
||||
"nota": "antes de aprender mide lecturas que el modelo no había visto",
|
||||
},
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
"""Copies what a notebook trained, in its job's own MLflow store, into the platform's (ML-02, ML-03).
|
||||
|
||||
The notebook wrote that store itself, so nothing in it is taken at its word. Only runs of the job's domain
|
||||
(`<domain>-<scenario>` experiments) come across; each becomes a new run tagged DEV, with the cohort reference of the
|
||||
build the job actually had, the notebook's run (`notebook.run_id`) and the model's hash computed here. Registered
|
||||
versions come across as DEV versions of their run, never with an alias, so a notebook can't put anything in
|
||||
production. Files are copied by walking the job folder without following symbolic links, and the store is opened
|
||||
from a copy, so nothing outside the job folder is ever read.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import Metric, Param
|
||||
|
||||
from models.io.lineage import MODEL_SHA_TAG, code_version, model_sha
|
||||
from models.io.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
|
||||
from models.io.tracking import MODEL_PATH, experiment_id
|
||||
|
||||
NOTEBOOK_RUN_TAG = "notebook.run_id"
|
||||
# Above this many bytes of files across a job's runs, nothing more is copied.
|
||||
MAX_IMPORT_BYTES_ENV = "NOTEBOOK_MAX_IMPORT_MB"
|
||||
MAX_IMPORT_MB = 500
|
||||
KEPT_SYSTEM_TAGS = ("mlflow.note.content",)
|
||||
|
||||
|
||||
def import_job(job: Path, notebook_run_id: str, domain: str, cohort: dict[str, str]) -> dict[str, Any]:
|
||||
"""Imports the job's runs and versions; returns what came across and what was left out, and why."""
|
||||
summary: dict[str, Any] = {"runs": [], "versions": [], "skipped": []}
|
||||
data = read_job_file(job, STORE_FILE)
|
||||
if not data:
|
||||
return summary
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-store-") as tmp:
|
||||
copy = Path(tmp) / STORE_FILE
|
||||
copy.write_bytes(data)
|
||||
local = MlflowClient(tracking_uri=f"sqlite:///{copy}", registry_uri=f"sqlite:///{copy}")
|
||||
target = MlflowClient()
|
||||
budget = int(os.environ.get(MAX_IMPORT_BYTES_ENV, MAX_IMPORT_MB)) * 1024 * 1024
|
||||
runs: dict[str, str] = {}
|
||||
for experiment in local.search_experiments():
|
||||
if not re.fullmatch(rf"{domain}-[\w-]{{1,100}}", experiment.name):
|
||||
summary["skipped"].append({"experiment": experiment.name, "reason": "no es un escenario del dominio"})
|
||||
continue
|
||||
for run in local.search_runs([experiment.experiment_id]):
|
||||
try:
|
||||
new_id, budget = _copy_run(local, target, job, run, experiment.name, notebook_run_id, cohort, budget)
|
||||
except JobError as error:
|
||||
summary["skipped"].append({"run": run.info.run_id, "reason": str(error)})
|
||||
continue
|
||||
runs[run.info.run_id] = new_id
|
||||
summary["runs"].append({"run_id": new_id, "experiment": experiment.name})
|
||||
for model in local.search_registered_models():
|
||||
for version in local.search_model_versions(f"name='{model.name}'"):
|
||||
if version.run_id not in runs or not model.name.startswith(f"{domain}-"):
|
||||
summary["skipped"].append({"version": f"{model.name}:{version.version}",
|
||||
"reason": "su corrida no se importó"})
|
||||
continue
|
||||
summary["versions"].append(_copy_version(target, model.name, runs[version.run_id], notebook_run_id))
|
||||
return summary
|
||||
|
||||
|
||||
def _artifact_dir(job: Path, run) -> Path:
|
||||
uri = run.info.artifact_uri
|
||||
path = Path(unquote(urlparse(uri).path)) if "://" in uri else Path(uri)
|
||||
if not inside(job, path):
|
||||
raise JobError(f"los archivos de la corrida están fuera de la carpeta del trabajo: {uri}")
|
||||
return path
|
||||
|
||||
|
||||
def _files(job: Path, folder: Path) -> list[Path]:
|
||||
"""The regular files under `folder`, refusing any symbolic link."""
|
||||
found = []
|
||||
for base, folders, files in os.walk(folder, followlinks=False):
|
||||
for name in folders + files:
|
||||
path = Path(base) / name
|
||||
if path.is_symlink() or not inside(job, path):
|
||||
raise JobError(f"enlace simbólico en los archivos de la corrida: {path.name}")
|
||||
if name in files:
|
||||
found.append(path)
|
||||
return found
|
||||
|
||||
|
||||
def _copy_run(local: MlflowClient, target: MlflowClient, job: Path, run, experiment: str, notebook_run_id: str,
|
||||
cohort: dict[str, str], budget: int) -> tuple[str, int]:
|
||||
folder = _artifact_dir(job, run)
|
||||
files = _files(job, folder) if folder.exists() else []
|
||||
size = sum(path.stat().st_size for path in files)
|
||||
if size > budget:
|
||||
raise JobError(f"sus archivos ({size // 1_000_000} MB) exceden el límite de {MAX_IMPORT_BYTES_ENV}")
|
||||
tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.") or k in KEPT_SYSTEM_TAGS}
|
||||
tags.update({**cohort, **code_version(), "domain": experiment.split("-", 1)[0],
|
||||
"scenario": experiment.split("-", 1)[1], "environment": "DEV", NOTEBOOK_RUN_TAG: notebook_run_id})
|
||||
tags.pop(MODEL_SHA_TAG, None)
|
||||
tags.pop("kit.armado_id", None)
|
||||
new = target.create_run(experiment_id(target, experiment), tags=tags, run_name=run.info.run_name)
|
||||
new_id = new.info.run_id
|
||||
params = [Param(k, v) for k, v in run.data.params.items()]
|
||||
metrics = [Metric(m.key, m.value, m.timestamp, m.step) for key in run.data.metrics
|
||||
for m in local.get_metric_history(run.info.run_id, key)]
|
||||
for start in range(0, max(len(params), len(metrics)), 100):
|
||||
target.log_batch(new_id, metrics=metrics[start:start + 100], params=params[start:start + 100])
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-files-") as staging:
|
||||
for path in files:
|
||||
destination = Path(staging) / path.relative_to(folder)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination, follow_symlinks=False)
|
||||
if files:
|
||||
target.log_artifacts(new_id, staging)
|
||||
if (Path(staging) / MODEL_PATH / "python_model.pkl").exists():
|
||||
target.set_tag(new_id, MODEL_SHA_TAG, model_sha(Path(staging) / MODEL_PATH))
|
||||
target.set_terminated(new_id, run.info.status if run.info.status in ("FINISHED", "FAILED") else "KILLED")
|
||||
return new_id, budget - size
|
||||
|
||||
|
||||
def _copy_version(target: MlflowClient, name: str, run_id: str, notebook_run_id: str) -> dict[str, str]:
|
||||
from mlflow import MlflowException
|
||||
|
||||
try:
|
||||
target.create_registered_model(name)
|
||||
except MlflowException as error:
|
||||
if error.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
run = target.get_run(run_id)
|
||||
keep = ("domain", "scenario", "environment", MODEL_SHA_TAG, "cohort.url", "cohort.source", "cohort.build",
|
||||
"cohort.file_sha256")
|
||||
tags = {k: run.data.tags[k] for k in keep if k in run.data.tags}
|
||||
tags[NOTEBOOK_RUN_TAG] = notebook_run_id
|
||||
has_model = MODEL_SHA_TAG in run.data.tags
|
||||
source = f"runs:/{run_id}/{MODEL_PATH}" if has_model else f"runs:/{run_id}"
|
||||
version = target.create_model_version(name, source=source, run_id=run_id, tags=tags)
|
||||
return {"name": name, "version": str(version.version), "run_id": run_id}
|
||||
@@ -1,268 +0,0 @@
|
||||
"""Where an uploaded notebook runs: a job folder, a runner and the executors that hand jobs to it (ML-04, ML-05).
|
||||
|
||||
A job is one folder named after the notebook's run, holding everything the notebook may see: the notebook
|
||||
(`notebook.ipynb`), a copy of the cohort build's file (`cohorte.parquet`), the chosen version's saved model
|
||||
(`model/`) and `job.json`. The notebook runs with that folder as its world: its MLflow is a throwaway store inside it
|
||||
(`mlflow.db`, `artefactos/`), and every database URL is an empty in-memory database. The runner writes the page
|
||||
(`page.html`) and `result.json`; what the notebook trained is imported afterwards by trusted code
|
||||
(`models.io.notebook_import`).
|
||||
|
||||
Executors are classes in `EXECUTORS`: `local` runs the job in this process, unsandboxed, for development;
|
||||
`contenedor` leaves it in `NOTEBOOK_JOBS_DIR` for the runner container (`python -m models notebooks serve`), which
|
||||
has no network and sees only that folder, and waits for its result. `NOTEBOOK_EXECUTOR` picks one; with
|
||||
`NOTEBOOK_JOBS_DIR` set the default is `contenedor`, otherwise `local`.
|
||||
|
||||
Whatever the notebook wrote is untrusted: files are read only through `read_job_file`, which refuses symbolic links
|
||||
and anything outside the job folder.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from models.io.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
|
||||
from models.notebook import COHORT_FILE_ENV, DOMAIN_ENV, MODEL_PATH_ENV, SCENARIO_ENV, VERSION_ENV
|
||||
|
||||
JOBS_DIR_ENV = "NOTEBOOK_JOBS_DIR"
|
||||
EXECUTOR_ENV = "NOTEBOOK_EXECUTOR"
|
||||
RUNNER_UID_ENV = "NOTEBOOK_RUNNER_UID"
|
||||
JOB_TIMEOUT_ENV = "NOTEBOOK_JOB_TIMEOUT"
|
||||
JOB_TIMEOUT = 6 * 3600
|
||||
POLL_SECONDS = 2
|
||||
|
||||
JOB_FILE, NOTEBOOK_FILE, COHORT_FILE, MODEL_DIR = "job.json", "notebook.ipynb", "cohorte.parquet", "model"
|
||||
STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos", "page.html", "result.json"
|
||||
CLAIM_DIR, WORK_DIR = "en_curso", "trabajo"
|
||||
KERNEL = "python3"
|
||||
# What a notebook inherits from the runner's environment; everything else is left out.
|
||||
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", "MODELS_GIT_COMMIT", CELL_TIMEOUT_ENV,
|
||||
"MLFLOW_DISABLE_TELEMETRY", "DO_NOT_TRACK", "MLFLOW_DISABLE_AGENT_HINT")
|
||||
DATABASE_ENVS = ("CACU_DATABASE_URL", "CAMA_DATABASE_URL", "TEA_DATABASE_URL", "GOVERNANCE_DATABASE_URL")
|
||||
EMPTY_DATABASE = "sqlite://"
|
||||
|
||||
|
||||
class JobError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _absolute(path: Path) -> str:
|
||||
"""The path as the job folder is reached, without resolving links on the way to it, so the trusted side and the
|
||||
notebook name its files the same way (`inside`)."""
|
||||
return os.path.abspath(path)
|
||||
|
||||
|
||||
def store_uri(job: Path) -> str:
|
||||
return f"sqlite:///{_absolute(job / STORE_FILE)}"
|
||||
|
||||
|
||||
def prepare_job(root: Path, run_id: str, notebook: dict, cohort_path: Path, *, domain: str, scenario: str,
|
||||
version: str | None, model_dir: Path | None = None) -> Path:
|
||||
"""Writes the job folder, complete or not at all: it's assembled beside the others and renamed into place, so the
|
||||
runner never picks up half a job."""
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
partial = Path(tempfile.mkdtemp(prefix=f".{run_id}-", dir=root))
|
||||
try:
|
||||
(partial / NOTEBOOK_FILE).write_text(json.dumps(with_kernel(notebook, KERNEL), ensure_ascii=False))
|
||||
shutil.copyfile(cohort_path, partial / COHORT_FILE)
|
||||
if model_dir is not None:
|
||||
shutil.copytree(model_dir, partial / MODEL_DIR)
|
||||
(partial / JOB_FILE).write_text(json.dumps({"run_id": run_id, "domain": domain, "scenario": scenario,
|
||||
"version": version}))
|
||||
_hand_over(partial)
|
||||
job = root / run_id
|
||||
partial.rename(job)
|
||||
except BaseException:
|
||||
shutil.rmtree(partial, ignore_errors=True)
|
||||
raise
|
||||
return job
|
||||
|
||||
|
||||
def _hand_over(folder: Path) -> None:
|
||||
"""Gives the job to the runner's user (`NOTEBOOK_RUNNER_UID`) when it isn't this one."""
|
||||
uid = os.environ.get(RUNNER_UID_ENV)
|
||||
os.chmod(folder, 0o755)
|
||||
if not uid or int(uid) == os.getuid():
|
||||
return
|
||||
for base, folders, files in os.walk(folder):
|
||||
for name in [base, *(os.path.join(base, f) for f in folders + files)]:
|
||||
os.chown(name, int(uid), int(uid), follow_symlinks=False)
|
||||
|
||||
|
||||
def notebook_env(job: Path) -> dict[str, str]:
|
||||
spec = json.loads((job / JOB_FILE).read_text())
|
||||
private = job / ".entorno"
|
||||
env = {name: os.environ[name] for name in PASSED_ENV if name in os.environ}
|
||||
env.update({name: EMPTY_DATABASE for name in DATABASE_ENVS})
|
||||
env.update({
|
||||
COHORT_FILE_ENV: _absolute(job / COHORT_FILE), DOMAIN_ENV: spec["domain"], SCENARIO_ENV: spec["scenario"],
|
||||
"MLFLOW_TRACKING_URI": store_uri(job), "MLFLOW_ARTIFACT_ROOT": _absolute(job / STORE_ARTIFACTS),
|
||||
"HOME": _absolute(private), "TMPDIR": _absolute(private / "tmp"), "IPYTHONDIR": _absolute(private / "ipython"),
|
||||
"JUPYTER_RUNTIME_DIR": _absolute(private / "jupyter"), "MPLCONFIGDIR": _absolute(private / "matplotlib"),
|
||||
})
|
||||
if spec.get("version"):
|
||||
env[VERSION_ENV] = str(spec["version"])
|
||||
if (job / MODEL_DIR).is_dir():
|
||||
env[MODEL_PATH_ENV] = _absolute(job / MODEL_DIR)
|
||||
return env
|
||||
|
||||
|
||||
def run_job(job: Path) -> bool:
|
||||
"""Runs the job's notebook and writes its page and `result.json`. Returns whether every cell ran."""
|
||||
env = notebook_env(job)
|
||||
for folder in ("HOME", "TMPDIR", "IPYTHONDIR", "JUPYTER_RUNTIME_DIR", "MPLCONFIGDIR"):
|
||||
Path(env[folder]).mkdir(parents=True, exist_ok=True)
|
||||
work = job / WORK_DIR
|
||||
work.mkdir(exist_ok=True)
|
||||
result: dict[str, Any] = {"ok": True, "error": None}
|
||||
page = None
|
||||
try:
|
||||
page = renderer().render(json.loads((job / NOTEBOOK_FILE).read_text()), "notebook", work, env)
|
||||
except RenderError as error:
|
||||
page, result = error.page, {"ok": False, "error": str(error)}
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
if page is not None:
|
||||
_write_atomically(job / PAGE_FILE, page)
|
||||
_write_atomically(job / RESULT_FILE, json.dumps(result, ensure_ascii=False))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _write_atomically(path: Path, text: str) -> None:
|
||||
partial = path.with_name(f".{path.name}.parcial")
|
||||
partial.write_text(text)
|
||||
partial.replace(path)
|
||||
|
||||
|
||||
def read_job_file(job: Path, relative: str) -> bytes | None:
|
||||
"""A file the job left, or `None` if it isn't there. `JobError` for a symbolic link or a path that leaves the job
|
||||
folder: those were planted to make the trusted side read its own files."""
|
||||
path = job / relative
|
||||
if not inside(job, path):
|
||||
raise JobError(f"{relative} sale de la carpeta del trabajo")
|
||||
try:
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as error:
|
||||
raise JobError(f"{relative} no es un archivo regular") from error
|
||||
with os.fdopen(descriptor, "rb") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
raise JobError(f"{relative} no es un archivo regular")
|
||||
return handle.read()
|
||||
|
||||
|
||||
def inside(job: Path, path: Path) -> bool:
|
||||
"""Whether `path` is within `job` with no symbolic link on the way."""
|
||||
base = Path(os.path.abspath(job))
|
||||
try:
|
||||
parts = Path(os.path.abspath(path)).relative_to(base).parts
|
||||
except ValueError:
|
||||
return False
|
||||
current = base
|
||||
for part in parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def result_of(job: Path) -> dict[str, Any] | None:
|
||||
data = read_job_file(job, RESULT_FILE)
|
||||
if data is None:
|
||||
return None
|
||||
try:
|
||||
result = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
return {"ok": False, "error": "result.json ilegible"}
|
||||
return {"ok": result.get("ok") is True, "error": str(result.get("error") or "")[:20000] or None}
|
||||
|
||||
|
||||
class NotebookExecutor(ABC):
|
||||
name: str
|
||||
sandboxed: bool
|
||||
|
||||
@abstractmethod
|
||||
def jobs_root(self) -> Path: ...
|
||||
|
||||
@abstractmethod
|
||||
def run(self, job: Path) -> None:
|
||||
"""Returns once the job has its `result.json`; `JobError` if it never gets one."""
|
||||
|
||||
|
||||
EXECUTORS: dict[str, type[NotebookExecutor]] = {}
|
||||
|
||||
|
||||
def register_executor(cls: type[NotebookExecutor]) -> type[NotebookExecutor]:
|
||||
EXECUTORS[cls.name] = cls
|
||||
return cls
|
||||
|
||||
|
||||
@register_executor
|
||||
class LocalExecutor(NotebookExecutor):
|
||||
"""Runs the job in this process's own kernel: nothing keeps the notebook from this machine's files or network."""
|
||||
|
||||
name, sandboxed = "local", False
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
return Path(os.environ.get(JOBS_DIR_ENV) or Path(tempfile.gettempdir()) / "notebook-jobs")
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
run_job(job)
|
||||
|
||||
|
||||
@register_executor
|
||||
class ContainerExecutor(NotebookExecutor):
|
||||
"""Leaves the job for the runner container and waits for its result (`NOTEBOOK_JOB_TIMEOUT`, 6 h by default)."""
|
||||
|
||||
name, sandboxed = "contenedor", True
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
if not os.environ.get(JOBS_DIR_ENV):
|
||||
raise JobError(f"{JOBS_DIR_ENV} no está configurado: no hay carpeta compartida con el contenedor de notebooks")
|
||||
return Path(os.environ[JOBS_DIR_ENV])
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
deadline = time.monotonic() + int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT))
|
||||
while time.monotonic() < deadline:
|
||||
if result_of(job) is not None:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
raise JobError("el contenedor de notebooks no terminó el trabajo a tiempo (¿está corriendo?)")
|
||||
|
||||
|
||||
def executor() -> NotebookExecutor:
|
||||
chosen = os.environ.get(EXECUTOR_ENV) or ("contenedor" if os.environ.get(JOBS_DIR_ENV) else "local")
|
||||
if chosen not in EXECUTORS:
|
||||
raise JobError(f"{EXECUTOR_ENV}={chosen!r}: use uno de {sorted(EXECUTORS)}")
|
||||
return EXECUTORS[chosen]()
|
||||
|
||||
|
||||
def claim(job: Path) -> bool:
|
||||
"""Takes a ready job for this runner; `False` if it isn't ready or another runner has it."""
|
||||
if not job.is_dir() or job.name.startswith(".") or not (job / JOB_FILE).exists() or (job / RESULT_FILE).exists():
|
||||
return False
|
||||
try:
|
||||
(job / CLAIM_DIR).mkdir()
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def serve(root: Path, *, once: bool = False) -> None:
|
||||
"""The runner's loop: runs each ready job in `root`, oldest first."""
|
||||
while True:
|
||||
for job in sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.stat().st_mtime):
|
||||
if claim(job):
|
||||
try:
|
||||
run_job(job)
|
||||
except Exception as error:
|
||||
_write_atomically(job / RESULT_FILE, json.dumps({"ok": False, "error": f"{type(error).__name__}: {error}"}))
|
||||
if once:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
+18
-26
@@ -16,6 +16,7 @@ the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import tempfile
|
||||
from collections.abc import Callable
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
@@ -25,13 +26,12 @@ from typing import Any, Protocol
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from core.governance.models import ModelPrediction
|
||||
import mlflow.artifacts
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name
|
||||
from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, TrainingRun, run_file, run_files
|
||||
from models.io.tracking import MODEL_PATH, TrainingRun, inspect_onnx_metadata, log_artifact_file
|
||||
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
PRODUCTION_ALIAS = "produccion"
|
||||
@@ -180,14 +180,19 @@ class ModelRegistry:
|
||||
for tag, uri in reports.items():
|
||||
self.client.set_model_version_tag(name, version, tag, uri or "")
|
||||
|
||||
def artifacts(self, domain: str, scenario: str, version: str) -> list[dict[str, Any]]:
|
||||
"""Every file the version's run stored, at any depth (`path`, `size` in bytes)."""
|
||||
return run_files(self.client, self.get(domain, scenario, version).run_id)
|
||||
|
||||
def artifact(self, domain: str, scenario: str, version: str, path: str) -> tuple[str, bytes]:
|
||||
"""ML-01b: one stored artifact as a file name and its bytes; a folder (the saved model) comes as a zip.
|
||||
`LookupError` for a path the run doesn't hold."""
|
||||
return run_file(self.client, self.get(domain, scenario, version).run_id, path)
|
||||
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
|
||||
log_artifact_file(self.client, mv.run_id, kind_value, path)
|
||||
|
||||
def _describe(self, mv) -> dict[str, Any]:
|
||||
run = self.client.get_run(mv.run_id)
|
||||
@@ -213,8 +218,7 @@ class ModelRegistry:
|
||||
"model_version": self.describe(domain, scenario, version),
|
||||
"cohorte_armado": armado,
|
||||
"cohorte_exclusiones": exclusiones,
|
||||
"artifacts": run_files(self.client, mv.run_id),
|
||||
"routines": self.routines(mv.run_id),
|
||||
"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)],
|
||||
}
|
||||
@@ -224,8 +228,7 @@ class ModelRegistry:
|
||||
run = self.client.get_run(mv.run_id)
|
||||
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
metrics = run.data.metrics
|
||||
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
|
||||
sha = mv.tags.get(MODEL_SHA_TAG, "")
|
||||
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(
|
||||
@@ -238,20 +241,9 @@ class ModelRegistry:
|
||||
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-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
|
||||
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
|
||||
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
|
||||
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
|
||||
]
|
||||
|
||||
def routines(self, run_id: str) -> dict[str, Any]:
|
||||
"""The routine records the run wrote while training (`TrainingRun.log_routine`), by kind."""
|
||||
found = {}
|
||||
for item in self.client.list_artifacts(run_id, ROUTINES_PATH):
|
||||
kind = Path(item.path).stem
|
||||
if not item.is_dir and kind in ArtifactKind.__members__:
|
||||
found[kind] = json.loads(mlflow.artifacts.load_text(f"runs:/{run_id}/{item.path}"))
|
||||
return found
|
||||
|
||||
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
|
||||
|
||||
+15
-118
@@ -1,8 +1,4 @@
|
||||
"""Runs a notebook and renders it to a self-contained HTML page.
|
||||
|
||||
Two renderers, one class each in `RENDERERS`: `quarto`, and `jupyter`, which runs the cells with `nbclient` and
|
||||
exports the page with `nbconvert` (the `notebooks` extra), so it needs nothing outside Python. `NOTEBOOK_RENDERER`
|
||||
picks one; otherwise Quarto when it's installed, else Jupyter.
|
||||
"""Renders a notebook to a self-contained HTML page with Quarto, running it first.
|
||||
|
||||
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
|
||||
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
|
||||
@@ -17,43 +13,13 @@ import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
QUARTO_ENV = "QUARTO_BIN"
|
||||
RENDERER_ENV = "NOTEBOOK_RENDERER"
|
||||
# Seconds a single cell may run under the Jupyter renderer.
|
||||
CELL_TIMEOUT_ENV = "NOTEBOOK_CELL_TIMEOUT"
|
||||
CELL_TIMEOUT = 1800
|
||||
|
||||
|
||||
class RenderError(RuntimeError):
|
||||
"""The notebook couldn't be run: a cell raised, the kernel is missing, or the renderer isn't installed. `page` is
|
||||
the page of the cells that did run, when the renderer could still make one."""
|
||||
|
||||
def __init__(self, message: str, page: str | None = None):
|
||||
super().__init__(message)
|
||||
self.page = page
|
||||
|
||||
|
||||
class NotebookRenderer(ABC):
|
||||
name: str
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def available(cls) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
"""Runs `notebook` in `folder` with exactly `env` as its environment and returns the page's HTML."""
|
||||
|
||||
|
||||
RENDERERS: dict[str, type[NotebookRenderer]] = {}
|
||||
|
||||
|
||||
def register_renderer(cls: type[NotebookRenderer]) -> type[NotebookRenderer]:
|
||||
RENDERERS[cls.name] = cls
|
||||
return cls
|
||||
"""Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed."""
|
||||
|
||||
|
||||
def quarto() -> str:
|
||||
@@ -63,90 +29,21 @@ def quarto() -> str:
|
||||
return found
|
||||
|
||||
|
||||
@register_renderer
|
||||
class QuartoRenderer(NotebookRenderer):
|
||||
name = "quarto"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
return bool(os.environ.get(QUARTO_ENV) or shutil.which("quarto"))
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
source = folder / f"{name}.ipynb"
|
||||
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
|
||||
kernel: str | None = None) -> Path:
|
||||
"""Runs and renders `notebook` (its JSON) as `name`, and writes the page to `output`."""
|
||||
command = quarto()
|
||||
if kernel:
|
||||
notebook = {**notebook, "metadata": {**notebook.get("metadata", {}),
|
||||
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
|
||||
with tempfile.TemporaryDirectory(prefix="render-") as folder:
|
||||
source = Path(folder) / f"{name}.ipynb"
|
||||
source.write_text(json.dumps(notebook, ensure_ascii=False))
|
||||
done = subprocess.run([quarto(), "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
|
||||
cwd=folder, env=env, capture_output=True, text=True)
|
||||
done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
|
||||
cwd=folder, env={**os.environ, **(env or {})}, capture_output=True, text=True)
|
||||
page = source.with_suffix(".html")
|
||||
if done.returncode or not page.exists():
|
||||
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
|
||||
return page.read_text()
|
||||
|
||||
|
||||
@register_renderer
|
||||
class JupyterRenderer(NotebookRenderer):
|
||||
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
|
||||
package's own interpreter once `ipykernel` is installed)."""
|
||||
|
||||
name = "jupyter"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
try:
|
||||
import nbclient # noqa: F401
|
||||
import nbconvert # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
import nbformat
|
||||
from nbclient import NotebookClient
|
||||
from nbclient.exceptions import CellExecutionError, DeadKernelError
|
||||
from nbconvert import HTMLExporter
|
||||
|
||||
node = nbformat.reads(json.dumps(notebook), as_version=4)
|
||||
kernel = node.metadata.get("kernelspec", {}).get("name") or "python3"
|
||||
timeout = int(os.environ.get(CELL_TIMEOUT_ENV, CELL_TIMEOUT))
|
||||
client = NotebookClient(node, timeout=timeout, kernel_name=kernel, resources={"metadata": {"path": str(folder)}})
|
||||
try:
|
||||
client.execute(env=env, cwd=str(folder))
|
||||
except (CellExecutionError, DeadKernelError, TimeoutError) as error:
|
||||
raise RenderError(f"{name}: {str(error)[-2000:]}", page=self._page(HTMLExporter, node)) from error
|
||||
except Exception as error:
|
||||
raise RenderError(f"{name}: el kernel {kernel!r} no pudo correr el notebook: {error}") from error
|
||||
return self._page(HTMLExporter, node)
|
||||
|
||||
@staticmethod
|
||||
def _page(exporter, node) -> str:
|
||||
body, _ = exporter(embed_images=True).from_notebook_node(node)
|
||||
return body
|
||||
|
||||
|
||||
def renderer() -> NotebookRenderer:
|
||||
"""The renderer `NOTEBOOK_RENDERER` names; otherwise Quarto if installed, else Jupyter."""
|
||||
if chosen := os.environ.get(RENDERER_ENV):
|
||||
if chosen not in RENDERERS:
|
||||
raise RenderError(f"{RENDERER_ENV}={chosen!r}: use one of {sorted(RENDERERS)}")
|
||||
return RENDERERS[chosen]()
|
||||
for cls in RENDERERS.values():
|
||||
if cls.available():
|
||||
return cls()
|
||||
raise RenderError(f"no notebook renderer is installed: install quarto or the 'notebooks' extra ({sorted(RENDERERS)})")
|
||||
|
||||
|
||||
def with_kernel(notebook: dict, kernel: str | None) -> dict:
|
||||
if not kernel:
|
||||
return notebook
|
||||
return {**notebook, "metadata": {**notebook.get("metadata", {}),
|
||||
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
|
||||
|
||||
|
||||
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
|
||||
kernel: str | None = None) -> Path:
|
||||
"""Runs and renders `notebook` (its JSON) as `name`, with this process's environment plus `env`, and writes the
|
||||
page to `output`."""
|
||||
with tempfile.TemporaryDirectory(prefix="render-") as folder:
|
||||
page = renderer().render(with_kernel(notebook, kernel), name, Path(folder), {**os.environ, **(env or {})})
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(page)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(page, output)
|
||||
return output
|
||||
|
||||
@@ -83,29 +83,6 @@ def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
|
||||
return rows
|
||||
|
||||
|
||||
def exported_builds(root: Path, domain: str) -> list[dict]:
|
||||
"""Every build of the domain's cohorts that has its file, newest first within each cohort and source, read from
|
||||
the files alone: `url`, `source`, `build`, `datos_as_of`, `n_members`."""
|
||||
rows = []
|
||||
folder = root / domain
|
||||
for cohort in sorted(p for p in folder.iterdir() if p.is_dir()) if folder.is_dir() else []:
|
||||
url = f"{domain}/{cohort.name}"
|
||||
for source, place in (("kit", cohort), ("dbt", cohort / "dbt")):
|
||||
for number in reversed(_numbers(place)):
|
||||
lineage = read_metadata(place / f"{number}.parquet")
|
||||
rows.append({"url": url, "source": source, "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
||||
"n_members": lineage.get("n_members") or lineage.get("n_miembros")})
|
||||
return rows
|
||||
|
||||
|
||||
def build_file(root: Path, url: str, source: str, build: int) -> Path:
|
||||
"""The file of one exported build; `LookupError` when it isn't there."""
|
||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||
if source not in ("kit", "dbt") or not path.exists():
|
||||
raise LookupError(f"no hay archivo de la construcción {source} {build} de {url}")
|
||||
return path
|
||||
|
||||
|
||||
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
|
||||
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
|
||||
without a file is described from `cohorts` (the domain's `cohort_repository`). `LookupError` if there's no such
|
||||
|
||||
+25
-47
@@ -3,12 +3,7 @@
|
||||
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.
|
||||
|
||||
Each routine around training (ML-01a: sampling, missing data, analytic
|
||||
method, class balance, output confidence) records what it did while the run
|
||||
is open, with `log_routine`: one JSON per routine under `rutinas/`, made of
|
||||
counts and settings, never rows. Turning a run into a registered
|
||||
stores the run, metrics and artifacts. Turning a run into a registered
|
||||
version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped
|
||||
methods instead of the fluent API's global active run, so two runs in one
|
||||
process never interfere.
|
||||
@@ -27,11 +22,9 @@ 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 io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -44,14 +37,32 @@ from models.io.storage import ReadOnlyRepository, resolve_repository
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
MODEL_PATH = "model"
|
||||
ROUTINES_PATH = "rutinas"
|
||||
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
|
||||
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
|
||||
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
|
||||
|
||||
|
||||
def routine_path(kind: ArtifactKind | str) -> str:
|
||||
return f"{ROUTINES_PATH}/{ArtifactKind(kind).value}.json"
|
||||
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
||||
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint (ML-01b, MLD-03), checked before it's
|
||||
logged. `onnx` is an optional dependency (`models[export]`).
|
||||
`{"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],
|
||||
}
|
||||
|
||||
|
||||
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
|
||||
@@ -62,34 +73,6 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str |
|
||||
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
|
||||
|
||||
|
||||
def run_files(client: MlflowClient, run_id: str, folder: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every file a run stored, at any depth: `path` and `size` in bytes."""
|
||||
files = []
|
||||
for item in client.list_artifacts(run_id, folder):
|
||||
files.extend(run_files(client, run_id, item.path) if item.is_dir else [{"path": item.path, "size": item.file_size}])
|
||||
return files
|
||||
|
||||
|
||||
def run_file(client: MlflowClient, run_id: str, path: str) -> tuple[str, bytes]:
|
||||
"""A stored file as its name and bytes, or a stored folder as `<name>.zip`. `LookupError` when the run holds
|
||||
nothing at `path`, which is matched against the run's own listing, never resolved on disk."""
|
||||
path = path.strip("/")
|
||||
files = [item["path"] for item in run_files(client, run_id)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
if path in files:
|
||||
local = Path(client.download_artifacts(run_id, path, tmp))
|
||||
return local.name, local.read_bytes()
|
||||
inside = [name for name in files if name.startswith(f"{path}/")]
|
||||
if not path or not inside:
|
||||
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
|
||||
client.download_artifacts(run_id, path, tmp)
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zipped:
|
||||
for name in inside:
|
||||
zipped.write(Path(tmp) / name, name)
|
||||
return f"{Path(path).name}.zip", archive.getvalue()
|
||||
|
||||
|
||||
def experiment_id(client: MlflowClient, name: str) -> str:
|
||||
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
|
||||
experiment = client.get_experiment_by_name(name)
|
||||
@@ -176,11 +159,6 @@ class TrainingRun:
|
||||
named for its kind."""
|
||||
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
|
||||
|
||||
def log_routine(self, kind: ArtifactKind | str, record: dict[str, Any]) -> None:
|
||||
"""ML-01a: what one routine did in this run, as it ran. A routine that was deliberately skipped records
|
||||
that too (for instance a class balance of "none"), so the run still says what happened."""
|
||||
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
||||
|
||||
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
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
"""What a notebook run from the platform works with (`models.pipelines.experiment`): the cohort build's file it was
|
||||
run on and, if one was chosen, a registered model version.
|
||||
|
||||
from models.notebook import experiment
|
||||
|
||||
exp = experiment()
|
||||
cohort = exp.cohort() # the build's rows, checked against the cohort contract
|
||||
model = exp.model() # the chosen version, loaded; None if none was chosen
|
||||
run = exp.training_run() # a DEV training run linked to this build's file (ML-02, ML-03)
|
||||
run.log_routine("MUESTREO", {...})
|
||||
run.log_model(MyModel(...))
|
||||
version = exp.register(run.finish(metrics={...}))
|
||||
|
||||
The notebook gets no database connection and no access to the platform's MLflow (ML-04, ML-05): the build's file
|
||||
is its data, and what it trains goes to a store of its own that the platform imports afterwards as DEV. Outside the
|
||||
platform, set `COHORT_FILE`, `MODELS_DOMAIN` and `MODELS_SCENARIO` (and `MODEL_VERSION`) to work the same way.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
COHORT_FILE_ENV = "COHORT_FILE"
|
||||
DOMAIN_ENV = "MODELS_DOMAIN"
|
||||
SCENARIO_ENV = "MODELS_SCENARIO"
|
||||
VERSION_ENV = "MODEL_VERSION"
|
||||
MODEL_PATH_ENV = "MODEL_PATH"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Experiment:
|
||||
domain: str
|
||||
scenario: str
|
||||
cohort_path: Path
|
||||
version: str | None = None
|
||||
|
||||
def cohort(self) -> pd.DataFrame:
|
||||
from models.io.storage import read_cohort
|
||||
|
||||
return read_cohort(self.cohort_path)
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
"""The build's own metadata: its cut-off, parameters, rules and attrition."""
|
||||
from models.io.storage import read_metadata
|
||||
|
||||
return read_metadata(self.cohort_path)
|
||||
|
||||
def model(self):
|
||||
"""The chosen version as an MLflow pyfunc (`.predict(cohort)`), or `None`. On the platform it's a copy of the
|
||||
version's saved model (`MODEL_PATH`); elsewhere it's loaded from the registry."""
|
||||
if self.version is None:
|
||||
return None
|
||||
import mlflow.pyfunc
|
||||
|
||||
if path := os.environ.get(MODEL_PATH_ENV):
|
||||
return mlflow.pyfunc.load_model(path)
|
||||
from models.io.registry import registry
|
||||
|
||||
return mlflow.pyfunc.load_model(registry.resolve(self.domain, self.scenario, self.version).model_uri)
|
||||
|
||||
def training_run(self, scenario: str | None = None):
|
||||
"""A DEV run of this domain, linked to the build's file. On the platform it goes to the job's own MLflow and
|
||||
is copied into the real one, as DEV, when the notebook ends (`models.io.notebook_import`)."""
|
||||
from models.io.lineage import cohort_reference, file_sha256
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
cohort = cohort_reference(self.lineage(), file_sha256(self.cohort_path))
|
||||
return TrainingRun(domain=self.domain, scenario=scenario or self.scenario, environment="DEV", cohort=cohort)
|
||||
|
||||
def register(self, run) -> str:
|
||||
"""Registers a finished run as a new DEV version of its scenario and returns the version."""
|
||||
from models.io.registry import registry
|
||||
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def experiment() -> Experiment:
|
||||
missing = [name for name in (COHORT_FILE_ENV, DOMAIN_ENV, SCENARIO_ENV) if not os.environ.get(name)]
|
||||
if missing:
|
||||
raise RuntimeError(f"this notebook wasn't run from the platform: {', '.join(missing)} not set")
|
||||
return Experiment(os.environ[DOMAIN_ENV], os.environ[SCENARIO_ENV], Path(os.environ[COHORT_FILE_ENV]),
|
||||
os.environ.get(VERSION_ENV) or None)
|
||||
@@ -1,207 +0,0 @@
|
||||
"""A notebook uploaded to the platform, run on a cohort build's file and kept as an MLflow run (ML-01a, ML-04, ML-05).
|
||||
|
||||
Each run belongs to the experiment `<domain>-<scenario>/experimentos` and is tagged with the notebook's name and
|
||||
content hash, the build's file (`models.io.lineage.cohort_reference`), the model version it was given, if any, the
|
||||
code version and where it ran (`sandbox`: `contenedor` or `local`). It holds the notebook as uploaded (`notebook/`),
|
||||
the page with its outputs (`report/`), what was imported from it (`importado.json`) and, when it failed,
|
||||
`error.txt`. `start` creates the run; `execute` runs the notebook through an executor and closes the run, so a caller
|
||||
can run it in the background and hand out the run's id at once.
|
||||
|
||||
The notebook runs in a job folder of its own (`models.io.notebook_jobs`) with the build's file as its only data and
|
||||
an MLflow store of its own; what it trained is copied into the platform's MLflow as DEV afterwards
|
||||
(`models.io.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view
|
||||
of the server's files, or this process for development.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import RunStatus
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, \
|
||||
cohort_reference, file_sha256, registered_name
|
||||
from models.io.notebook_import import import_job
|
||||
from models.io.notebook_jobs import JOB_TIMEOUT, JOB_TIMEOUT_ENV, PAGE_FILE, executor, prepare_job, read_job_file, \
|
||||
result_of
|
||||
from models.io.storage import read_metadata
|
||||
from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files
|
||||
from models.steps.report import notebook_sha256, without_outputs
|
||||
|
||||
EXPERIMENT_SUFFIX = "experimentos"
|
||||
KIND_TAG, KIND = "experiment", "notebook"
|
||||
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, VERSION_TAG = "notebook", "notebook.sha256", "model.version"
|
||||
DOMAIN_TAG, SCENARIO_TAG, SANDBOX_TAG = "domain", "scenario", "sandbox"
|
||||
ERROR_PATH, IMPORT_PATH = "error.txt", "importado.json"
|
||||
KEEP_JOBS_ENV = "NOTEBOOK_KEEP_JOBS"
|
||||
# A run still marked as running this long after its job's timeout was cut off (a restart, a killed worker).
|
||||
STALE_MARGIN = timedelta(minutes=30)
|
||||
|
||||
|
||||
def experiment_name(domain: str, scenario: str) -> str:
|
||||
return f"{registered_name(domain, scenario)}/{EXPERIMENT_SUFFIX}"
|
||||
|
||||
|
||||
def check_names(domain: str | None, scenario: str | None) -> None:
|
||||
if domain is not None and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario is not None and not re.fullmatch(r"[\w-]{1,100}", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
|
||||
|
||||
def notebook_name(filename: str) -> str:
|
||||
"""The name a notebook's files are stored under: its file name without folders or extension, in safe characters."""
|
||||
stem = Path(filename.replace("\\", "/")).name.removesuffix(".ipynb")
|
||||
return re.sub(r"[^\w.-]+", "_", stem).strip("._")[:80] or "notebook"
|
||||
|
||||
|
||||
def check_notebook(notebook: Any) -> dict:
|
||||
"""A Jupyter notebook (nbformat 4), or `ValueError` saying why not."""
|
||||
if not isinstance(notebook, dict) or not isinstance(notebook.get("cells"), list):
|
||||
raise ValueError("el archivo no es un notebook de Jupyter (.ipynb)")
|
||||
if notebook.get("nbformat") != 4:
|
||||
raise ValueError(f"solo se aceptan notebooks en formato 4, no {notebook.get('nbformat')!r}")
|
||||
return notebook
|
||||
|
||||
|
||||
def start(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> str:
|
||||
"""Creates the run, stores the notebook as uploaded and returns the run's id; the notebook hasn't run yet."""
|
||||
check_names(domain, scenario)
|
||||
check_notebook(notebook)
|
||||
name = notebook_name(name)
|
||||
client = MlflowClient()
|
||||
tags = {KIND_TAG: KIND, NOTEBOOK_TAG: name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook), DOMAIN_TAG: domain,
|
||||
SCENARIO_TAG: scenario, **cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path)),
|
||||
**code_version()}
|
||||
if version:
|
||||
tags[VERSION_TAG] = str(version)
|
||||
run = client.create_run(experiment_id(client, experiment_name(domain, scenario)), tags=tags, run_name=name)
|
||||
client.log_text(run.info.run_id, json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1),
|
||||
f"notebook/{name}.ipynb")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
def execute(run_id: str, notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> bool:
|
||||
"""Runs the notebook through the executor, imports what it trained, stores its page (the cells that ran, when it
|
||||
failed) and closes the run. Returns whether every cell ran."""
|
||||
client = MlflowClient()
|
||||
runner = executor()
|
||||
client.set_tag(run_id, SANDBOX_TAG, runner.name)
|
||||
job = None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-model-") as tmp:
|
||||
model = _model_copy(client, domain, scenario, version, Path(tmp))
|
||||
job = prepare_job(runner.jobs_root(), run_id, notebook, Path(cohort_path), domain=domain,
|
||||
scenario=scenario, version=version, model_dir=model)
|
||||
runner.run(job)
|
||||
result = result_of(job) or {"ok": False, "error": "el notebook terminó sin resultado"}
|
||||
if page := read_job_file(job, PAGE_FILE):
|
||||
client.log_text(run_id, page.decode("utf-8", "replace"), f"report/{name}.html")
|
||||
cohort = {k: v for k, v in client.get_run(run_id).data.tags.items() if k.startswith("cohort.")}
|
||||
client.log_dict(run_id, import_job(job, run_id, domain, cohort), IMPORT_PATH)
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
finally:
|
||||
if job is not None and not os.environ.get(KEEP_JOBS_ENV):
|
||||
shutil.rmtree(job, ignore_errors=True)
|
||||
if not result["ok"]:
|
||||
client.log_text(run_id, result["error"] or "falló", ERROR_PATH)
|
||||
client.set_terminated(run_id, RunStatus.to_string(RunStatus.FINISHED if result["ok"] else RunStatus.FAILED))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _model_copy(client: MlflowClient, domain: str, scenario: str, version: str | None, folder: Path) -> Path | None:
|
||||
"""The chosen version's saved model, downloaded for the job; `None` without a version or a saved model."""
|
||||
if not version:
|
||||
return None
|
||||
from models.io.registry import registry
|
||||
|
||||
resolved = registry.resolve(domain, scenario, version)
|
||||
if not resolved.modelo_sha:
|
||||
return None
|
||||
return Path(client.download_artifacts(resolved.run_id, MODEL_PATH, str(folder)))
|
||||
|
||||
|
||||
def run_notebook(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> tuple[str, bool]:
|
||||
run_id = start(notebook, name, cohort_path, domain, scenario, version)
|
||||
return run_id, execute(run_id, notebook, notebook_name(name), cohort_path, domain, scenario, version)
|
||||
|
||||
|
||||
def _status(run) -> str:
|
||||
status = run.info.status
|
||||
if status == "RUNNING":
|
||||
started = datetime.fromtimestamp(run.info.start_time / 1000, tz=timezone.utc)
|
||||
timeout = timedelta(seconds=int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT)))
|
||||
return "interrumpido" if datetime.now(timezone.utc) - started > timeout + STALE_MARGIN else "en_curso"
|
||||
return {"FINISHED": "terminado", "FAILED": "fallido", "KILLED": "interrumpido"}.get(status, status.lower())
|
||||
|
||||
|
||||
def _iso(epoch_millis: int | None) -> str | None:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat() if epoch_millis else None
|
||||
|
||||
|
||||
def _describe(run) -> dict[str, Any]:
|
||||
tags = run.data.tags
|
||||
return {"run_id": run.info.run_id, "notebook": tags.get(NOTEBOOK_TAG), "domain": tags.get(DOMAIN_TAG),
|
||||
"scenario": tags.get(SCENARIO_TAG), "version": tags.get(VERSION_TAG),
|
||||
"cohort": {"url": tags.get(COHORT_URL_TAG), "source": tags.get(COHORT_SOURCE_TAG),
|
||||
"build": tags.get(COHORT_BUILD_TAG)},
|
||||
"notebook_sha256": tags.get(NOTEBOOK_SHA_TAG), "sandbox": tags.get(SANDBOX_TAG), "status": _status(run),
|
||||
"started_at": _iso(run.info.start_time), "ended_at": _iso(run.info.end_time)}
|
||||
|
||||
|
||||
def experiments(domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Notebook runs, newest first; `scenario` needs `domain`."""
|
||||
check_names(domain, scenario)
|
||||
client = MlflowClient()
|
||||
pattern = f"{registered_name(domain, scenario) if scenario else (domain + '-%' if domain else '%')}/{EXPERIMENT_SUFFIX}"
|
||||
found = client.search_experiments(filter_string=f"name LIKE '{pattern}'")
|
||||
if not found:
|
||||
return []
|
||||
runs = client.search_runs([e.experiment_id for e in found], filter_string=f"tags.{KIND_TAG} = '{KIND}'",
|
||||
order_by=["attributes.start_time DESC"], max_results=500)
|
||||
return [_describe(run) for run in runs]
|
||||
|
||||
|
||||
def _run(client: MlflowClient, run_id: str):
|
||||
try:
|
||||
run = client.get_run(run_id)
|
||||
except Exception as error:
|
||||
raise LookupError(f"no existe la corrida {run_id!r}") from error
|
||||
if run.data.tags.get(KIND_TAG) != KIND:
|
||||
raise LookupError(f"la corrida {run_id!r} no es de un notebook")
|
||||
return run
|
||||
|
||||
|
||||
def describe(run_id: str) -> dict[str, Any]:
|
||||
"""One notebook run with its files and, if it failed, the error."""
|
||||
client = MlflowClient()
|
||||
run = _run(client, run_id)
|
||||
files = run_files(client, run_id)
|
||||
error = None
|
||||
if any(item["path"] == ERROR_PATH for item in files):
|
||||
error = run_file(client, run_id, ERROR_PATH)[1].decode("utf-8", "replace")
|
||||
return {**_describe(run), "artifacts": files, "error": error}
|
||||
|
||||
|
||||
def artifact(run_id: str, path: str) -> tuple[str, bytes]:
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
return run_file(client, run_id, path)
|
||||
|
||||
|
||||
def page(run_id: str) -> str | None:
|
||||
"""The rendered page, or `None` while there's none."""
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
pages = [item["path"] for item in run_files(client, run_id, "report") if item["path"].endswith(".html")]
|
||||
return run_file(client, run_id, pages[0])[1].decode("utf-8") if pages else None
|
||||
@@ -0,0 +1 @@
|
||||
"""TEA's scenarios and notebooks."""
|
||||
+6
-8
@@ -18,11 +18,11 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Running uploaded notebooks without Quarto (models.io.rendering.JupyterRenderer, models.pipelines.experiment).
|
||||
notebooks = [
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
||||
# models.io.tracking.inspect_onnx_metadata — writing/logging a checkpoint never
|
||||
# requires it, see that module's docstring.
|
||||
export = [
|
||||
"onnx>=1.15",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
@@ -40,8 +40,6 @@ exclude = ["**/notebooks"]
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"onnx>=1.15",
|
||||
"reportlab>=4.0",
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
|
||||
@@ -5,8 +5,7 @@ commands over it, repeating no step.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
||||
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2
|
||||
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow; `cacu_db` (conftest), an empty CaCu database for
|
||||
the promotion checks.
|
||||
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
@@ -157,21 +156,6 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
|
||||
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||
|
||||
|
||||
def test_training_records_each_routine_as_it_ran(cohort_file, cacu_db, mlflow_tracking):
|
||||
"""ML-01a: the run holds what sampling, missing data, the method, class balance and calibration actually did, in
|
||||
counts that add up to the split. Fails if a routine node stops being logged by `registered_model` or records
|
||||
something other than this training's own numbers."""
|
||||
version = train(cohort_file)
|
||||
routines = registry.routines(registry.get("cacu", "cin2_logistic", version).run_id)
|
||||
assert set(routines) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
|
||||
assert routines["MUESTREO"]["train"]["n"] == 14 and routines["MUESTREO"]["test"]["n"] == 6
|
||||
assert sum(routines["BALANCE_CLASES"]["train"].values()) == 14
|
||||
assert sum(b["n"] for b in routines["CONFIANZA_SALIDA"]["bins"]) == 6
|
||||
assert routines["METODO_ANALITICO"]["coefficients"]
|
||||
failed = {check.code for check in registry.checks("cacu", "cin2_logistic", version) if not check.passed}
|
||||
assert "ML-01a" not in failed and "ML-01b" not in failed
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
|
||||
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
|
||||
|
||||
+17
-27
@@ -1,4 +1,3 @@
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -45,44 +44,35 @@ def mlflow_tracking(tmp_path, monkeypatch):
|
||||
yield
|
||||
|
||||
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
"""A model whose class lives in a module, as a PROD run requires: it returns its input."""
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True):
|
||||
"""A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some)
|
||||
and, with `model`, a saved model."""
|
||||
from core.governance.enums import Environment
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id)
|
||||
for kind in ROUTINE_KINDS if routines is None else routines:
|
||||
run.log_routine(kind, {"method": "prueba", "n": 8})
|
||||
if model:
|
||||
run.log_model(Echo())
|
||||
return run.finish(metrics=metrics)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def production_ready(governance_db, cacu_db, mlflow_tracking):
|
||||
"""Factory: registers a PROD version whose run recorded every routine and its model, with the three reports,
|
||||
so it passes every promotion check; returns (domain, scenario, version)."""
|
||||
"""Factory: registers a PROD version that passes every promotion check,
|
||||
returns (domain, scenario, version)."""
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.io.registry import registry
|
||||
|
||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
||||
run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8})
|
||||
version = registry.register_run(
|
||||
run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
version = registry.register(
|
||||
domain=domain, scenario=scenario, environment=Environment.PROD,
|
||||
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
|
||||
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html",
|
||||
)
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
|
||||
return domain, scenario, version
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def tiny_onnx() -> bytes:
|
||||
import onnx.helper
|
||||
|
||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
|
||||
|
||||
|
||||
def armado(huella: str) -> int:
|
||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
"""Each domain's extraction ranker in the model registry
|
||||
(`models.io.extraction_ranker`): every batch it learns from is a new DEV
|
||||
version continuing the latest, with its five routine records and its saved
|
||||
model; extraction takes the version in production, else the latest, and
|
||||
`EXTRACTION_RANKER` can restrict or turn that off.
|
||||
|
||||
Fixtures: `mlflow_tracking` (a SQLite MLflow per test) and `_fresh_cache`
|
||||
(an empty ranker cache and no `EXTRACTION_RANKER`). Batches are built
|
||||
inline by `_batch` from candidates with the features an extractor gives
|
||||
them; no document is read.
|
||||
"""
|
||||
import json
|
||||
|
||||
import mlflow.artifacts
|
||||
import pytest
|
||||
from extraction.document import BBox
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue
|
||||
from extraction.nlp.ranking import examples_for
|
||||
|
||||
from models.io import extraction_ranker
|
||||
from models.io.extraction_ranker import Batch, current, learn
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINES_PATH
|
||||
|
||||
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
|
||||
|
||||
|
||||
def _batch(right: str = "LIEBG") -> Batch:
|
||||
evidence = Evidence("reporte.pdf", 1, "Diagnóstico: NIC I", BBox(0, 0, 1, 0.1).as_list())
|
||||
candidates = [
|
||||
ExtractedValue("LIEBG", 0.5, "etiqueta", "NIC I", evidence, {"assertion": "afirmado", "section": "resultado"}),
|
||||
ExtractedValue("LIEAG", 0.6, "texto_libre", "NIC II", evidence, {"assertion": "afirmado", "section": "general"}),
|
||||
]
|
||||
examples = examples_for([GRADO], {"bx_cin_grado": candidates}, {"bx_cin_grado": right})
|
||||
return Batch(examples, "revision", documents=1, records=1, unreachable={})
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_cache(monkeypatch):
|
||||
"""No ranker cached from another test, and the default selection."""
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.delenv(extraction_ranker.SELECTION_ENV, raising=False)
|
||||
|
||||
|
||||
def test_each_batch_is_a_new_dev_version_with_its_routines(mlflow_tracking):
|
||||
"""Fails if learning stops registering a DEV version, its run loses one
|
||||
of the five routine records or its saved model, which ML-01a and ML-01b
|
||||
require to promote it."""
|
||||
version = learn("cacu", _batch())
|
||||
described = registry.get("cacu", extraction_ranker.SCENARIO, version)
|
||||
assert described.tags["environment"] == "DEV"
|
||||
checks = {c.code: c.passed for c in registry.checks("cacu", extraction_ranker.SCENARIO, version)}
|
||||
assert checks["ML-01a"] and checks["ML-01b"]
|
||||
|
||||
|
||||
def test_routine_records_hold_counts_never_document_text(mlflow_tracking):
|
||||
"""What a ranker stores can be shared: weights and counts. Fails if a
|
||||
routine record or the ranker's state carries a raw reading or the line
|
||||
it came from."""
|
||||
version = learn("cacu", _batch())
|
||||
run_id = registry.get("cacu", extraction_ranker.SCENARIO, version).run_id
|
||||
stored = json.dumps(mlflow.artifacts.load_dict(f"runs:/{run_id}/{extraction_ranker.RANKER_PATH}"))
|
||||
for kind in ("MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"):
|
||||
stored += mlflow.artifacts.load_text(f"runs:/{run_id}/{ROUTINES_PATH}/{kind}.json")
|
||||
assert "NIC I" not in stored and "Diagnóstico" not in stored and "reporte.pdf" not in stored
|
||||
|
||||
|
||||
def test_learning_continues_from_the_latest_version(mlflow_tracking):
|
||||
"""Fails if a new batch starts from scratch instead of the latest
|
||||
version, which would forget every earlier correction."""
|
||||
learn("cacu", _batch())
|
||||
second = learn("cacu", _batch())
|
||||
ranker = current("cacu")
|
||||
assert ranker.version == f"{extraction_ranker.SCENARIO}:{second}"
|
||||
assert ranker.examples == 2 * len(_batch().examples)
|
||||
|
||||
|
||||
def test_extraction_takes_production_first_and_can_be_turned_off(mlflow_tracking, monkeypatch):
|
||||
"""With a version in production that one is used even when newer DEV
|
||||
versions exist; `produccion` refuses DEV-only registries and `ninguno`
|
||||
turns the ranker off. Fails if the selection order changes."""
|
||||
assert current("cacu") is None
|
||||
first = learn("cacu", _batch())
|
||||
learn("cacu", _batch())
|
||||
registry.client.set_registered_model_alias("cacu-extraccion", "produccion", first)
|
||||
assert current("cacu").version == f"{extraction_ranker.SCENARIO}:{first}"
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "ninguno")
|
||||
assert current("cacu") is None
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "produccion")
|
||||
assert current("tea") is None
|
||||
|
||||
|
||||
def test_an_empty_batch_registers_nothing(mlflow_tracking):
|
||||
"""Fails if a review without usable examples creates a version."""
|
||||
assert learn("cacu", Batch([], "revision", 0, 0, {})) is None
|
||||
assert registry.versions("cacu", extraction_ranker.SCENARIO) == []
|
||||
+16
-49
@@ -1,16 +1,4 @@
|
||||
"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and
|
||||
what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`).
|
||||
|
||||
Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model;
|
||||
`governance_db`, `cacu_db` and `mlflow_tracking` (from `conftest.py`); `trained_run` and `armado` (from `conftest.py`)
|
||||
build runs missing a routine or the model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from conftest import armado, trained_run
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.io.registry import PromotionBlocked, registry
|
||||
|
||||
@@ -21,7 +9,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
|
||||
with pytest.raises(PromotionBlocked) as blocked:
|
||||
registry.promote("cacu", "tamizaje", version)
|
||||
failed = {check.code for check in blocked.value.checks if not check.passed}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
|
||||
|
||||
|
||||
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
|
||||
@@ -47,44 +35,10 @@ def test_reports_can_be_attached_after_training(production_ready):
|
||||
registry.attach_reports(domain, scenario, version, metrics="{}")
|
||||
|
||||
|
||||
def test_lineage_lists_every_stored_file_and_each_routine_record(production_ready):
|
||||
"""The lineage lists files inside folders (the saved model) and reads back each routine's record. Fails if
|
||||
`run_files` stops descending into folders or `routines` stops reading `rutinas/`."""
|
||||
def test_artifacts_are_logged_to_the_run(production_ready):
|
||||
domain, scenario, version = production_ready("v1")
|
||||
lineage = registry.lineage(domain, scenario, version)
|
||||
paths = {item["path"] for item in lineage["artifacts"]}
|
||||
assert "model/MLmodel" in paths and "rutinas/MUESTREO.json" in paths
|
||||
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routines, model, failing", [
|
||||
([ArtifactKind.MUESTREO], True, "ML-01a"),
|
||||
(None, False, "ML-01b"),
|
||||
])
|
||||
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
|
||||
failing):
|
||||
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
|
||||
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
|
||||
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
|
||||
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
|
||||
interpretability_report_uri="i")
|
||||
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
|
||||
assert [check.code for check in failed] == [failing]
|
||||
if failing == "ML-01a":
|
||||
assert "DATOS_FALTANTES" in failed[0].detail
|
||||
|
||||
|
||||
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
|
||||
"""ML-01b: a stored file comes back as itself; the model folder as a zip of its files. Fails if `run_file`
|
||||
stops zipping folders or starts accepting a path the run doesn't list."""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
name, data = registry.artifact(domain, scenario, version, "rutinas/MUESTREO.json")
|
||||
assert name == "MUESTREO.json" and json.loads(data)["n"] == 8
|
||||
name, data = registry.artifact(domain, scenario, version, "model")
|
||||
assert name == "model.zip" and "model/MLmodel" in zipfile.ZipFile(io.BytesIO(data)).namelist()
|
||||
for wrong in ("../mlflow.db", "", "rutinas/OTRO.json"):
|
||||
with pytest.raises(LookupError):
|
||||
registry.artifact(domain, scenario, version, wrong)
|
||||
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
|
||||
|
||||
|
||||
def test_retire_and_lineage(production_ready):
|
||||
@@ -101,6 +55,19 @@ def test_retire_and_lineage(production_ready):
|
||||
registry.retire(domain, scenario, second)
|
||||
|
||||
|
||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||
from models.io.tracking import inspect_onnx_metadata
|
||||
|
||||
with pytest.raises(ValueError, match="ONNX"):
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "x.onnx"
|
||||
path.write_bytes(b"weights")
|
||||
inspect_onnx_metadata(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
|
||||
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
|
||||
with pytest.raises(ValueError):
|
||||
|
||||
@@ -19,11 +19,11 @@ def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
|
||||
|
||||
|
||||
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
|
||||
notes = tmp_path / "notas.json"
|
||||
notes.write_text("{}")
|
||||
checkpoint = tmp_path / "model.onnx"
|
||||
checkpoint.write_bytes(b"fake-onnx-bytes")
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
run.log_artifact(ArtifactKind.OTRO, notes, metadata={"origen": "prueba"})
|
||||
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
||||
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
|
||||
|
||||
mv = registry.get("cacu", "tamizaje", version)
|
||||
@@ -31,8 +31,8 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path)
|
||||
metrics = registry.client.get_run(mv.run_id).data.metrics
|
||||
assert metrics["auc"] == 0.81
|
||||
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.OTRO.value)]
|
||||
assert any(path.endswith("notas.json") for path in artifacts)
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
|
||||
assert any(path.endswith("model.onnx") for path in artifacts)
|
||||
|
||||
|
||||
def test_read_only_repository_blocks_writes(cacu_db):
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import onnx
|
||||
import onnx.helper
|
||||
import pytest
|
||||
|
||||
from models.io.tracking import inspect_onnx_metadata
|
||||
|
||||
|
||||
def _tiny_onnx_bytes() -> bytes:
|
||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
|
||||
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
||||
return model.SerializeToString()
|
||||
|
||||
|
||||
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
|
||||
path = tmp_path / "model.onnx"
|
||||
path.write_bytes(_tiny_onnx_bytes())
|
||||
|
||||
metadata = inspect_onnx_metadata(path)
|
||||
|
||||
assert metadata["available"] is True
|
||||
assert metadata["producer_name"] == "pytest-fixture"
|
||||
assert metadata["graph_inputs"] == ["x"]
|
||||
assert metadata["graph_outputs"] == ["y"]
|
||||
|
||||
|
||||
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
|
||||
"""A protobuf-valid but structurally broken graph (a node reading an
|
||||
input the graph never declares) must be rejected: `onnx.load` alone
|
||||
only parses the protobuf and would let this through."""
|
||||
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
graph = onnx.helper.make_graph([node], "broken", [], [y])
|
||||
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
||||
path = tmp_path / "model.onnx"
|
||||
path.write_bytes(model.SerializeToString())
|
||||
|
||||
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
|
||||
inspect_onnx_metadata(path)
|
||||
|
||||
|
||||
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
|
||||
import builtins
|
||||
|
||||
real_import = builtins.__import__
|
||||
|
||||
def fake_import(name, *args, **kwargs):
|
||||
if name == "onnx":
|
||||
raise ImportError("onnx not installed")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "__import__", fake_import)
|
||||
path = tmp_path / "model.onnx"
|
||||
path.write_bytes(b"irrelevant")
|
||||
assert inspect_onnx_metadata(path) == {
|
||||
"available": False,
|
||||
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
"""What this module covers: notebooks run on a cohort build's file as MLflow runs (`models.pipelines.experiment`), the
|
||||
job folder and its executors (`models.io.notebook_jobs`), the import of what a notebook trained
|
||||
(`models.io.notebook_import`), the API notebooks use inside (`models.notebook`) and the Jupyter renderer: what the
|
||||
notebook can reach, what the run keeps, a notebook that fails, a notebook that tries to reach past its job, the runner
|
||||
as the container runs it, and listing and reading runs back.
|
||||
|
||||
Fixtures: `cohort_file`, a dbt build's file of two members with its metadata; `jupyter`, the Jupyter renderer chosen
|
||||
and MLflow's artifacts kept under the test's folder; `mlflow_tracking` (conftest), a SQLite-backed MLflow. Notebooks
|
||||
are built inline with `_notebook`, naming a kernel the server doesn't have, as an author's would; they run in a real
|
||||
kernel, the platform's own (fails if `notebook_jobs.KERNEL` stops replacing it). `Echo` (conftest) is the saved
|
||||
model a notebook is given.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from models.io.registry import registry
|
||||
from models.pipelines import experiment
|
||||
|
||||
|
||||
def _notebook(*sources: str) -> dict:
|
||||
return {"cells": [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": [s]}
|
||||
for s in sources],
|
||||
"metadata": {"kernelspec": {"name": "un-kernel-local", "display_name": "local", "language": "python"}},
|
||||
"nbformat": 4, "nbformat_minor": 5}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, pac_id), "fecha": date(2025, 1, pac_id),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": f"S{pac_id}"} for pac_id in (1, 2)]
|
||||
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "3.parquet"
|
||||
path.parent.mkdir(parents=True)
|
||||
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "3", "datos_as_of": "2025-12-31"}
|
||||
pq.write_table(table.replace_schema_metadata(metadata), path)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jupyter(tmp_path, monkeypatch, mlflow_tracking):
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
monkeypatch.setenv("CACU_DATABASE_URL", f"sqlite:///{tmp_path / 'real-cacu.db'}")
|
||||
|
||||
|
||||
def test_a_notebook_reads_its_build_and_no_database(jupyter, cohort_file):
|
||||
"""The notebook gets the build's file through `models.notebook` and only an empty in-memory database, whatever the
|
||||
server's own URLs are. Fails if `notebook_env` starts passing the server's environment or the build's file stops
|
||||
reaching the kernel."""
|
||||
notebook = _notebook("import os\nfrom models.notebook import experiment\nexp = experiment()",
|
||||
"print('members', exp.cohort().pac_id.nunique(), os.environ['CACU_DATABASE_URL'] or 'none')")
|
||||
run_id, ok = experiment.run_notebook(notebook, "lee.ipynb", cohort_file, "cacu", "exploracion")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
page = experiment.page(run_id)
|
||||
assert "members 2 sqlite://" in page and "real-cacu" not in page
|
||||
|
||||
|
||||
def test_the_run_keeps_the_notebook_its_page_and_its_inputs(jupyter, cohort_file):
|
||||
"""The run is tagged with the notebook's hash and the build, and keeps the notebook as uploaded and its page.
|
||||
Fails if `start` stops tagging the inputs or storing the source."""
|
||||
run_id, _ = experiment.run_notebook(_notebook("print(1 + 1)"), "../../otro/suma.ipynb", cohort_file, "cacu", "exploracion")
|
||||
run = experiment.describe(run_id)
|
||||
assert run["status"] == "terminado" and run["notebook"] == "suma"
|
||||
assert run["cohort"] == {"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "3"}
|
||||
assert {a["path"] for a in run["artifacts"]} == {"notebook/suma.ipynb", "report/suma.html", "importado.json"}
|
||||
assert run["sandbox"] == "local"
|
||||
name, data = experiment.artifact(run_id, "notebook/suma.ipynb")
|
||||
assert json.loads(data)["cells"][0]["source"] == ["print(1 + 1)"]
|
||||
|
||||
|
||||
def test_a_failing_cell_fails_the_run_and_keeps_what_ran(jupyter, cohort_file):
|
||||
"""A cell that raises ends the run as failed with the error, and the page shows the cells up to it. Fails if
|
||||
`execute` loses the partial page or leaves the run open."""
|
||||
run_id, ok = experiment.run_notebook(_notebook("print('antes')", "1 / 0", "print('despues')"), "falla", cohort_file,
|
||||
"cacu", "exploracion")
|
||||
run = experiment.describe(run_id)
|
||||
assert not ok and run["status"] == "fallido" and "ZeroDivisionError" in run["error"]
|
||||
assert "antes" in experiment.page(run_id) and "despues" not in experiment.page(run_id).split("ZeroDivisionError")[0]
|
||||
|
||||
|
||||
def test_a_notebook_can_train_and_register_a_dev_version(jupyter, cohort_file):
|
||||
"""Through `models.notebook`, a notebook opens a DEV run linked to its build, records a routine and registers it;
|
||||
the import brings run and version into the platform's MLflow. Fails if `Experiment.training_run` stops linking
|
||||
the build, or `import_job` stops copying runs, their files or their versions."""
|
||||
notebook = _notebook("from models.notebook import experiment\nexp = experiment()\nrun = exp.training_run()\n"
|
||||
"run.log_routine('MUESTREO', {'n': 2})\nprint('version', exp.register(run.finish(metrics={'n': 2})))")
|
||||
run_id, ok = experiment.run_notebook(notebook, "entrena", cohort_file, "cacu", "prueba_nb")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
stored = registry.get("cacu", "prueba_nb", "1")
|
||||
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
|
||||
assert registry.routines(stored.run_id) == {"MUESTREO": {"n": 2}}
|
||||
assert stored.tags["notebook.run_id"] == run_id
|
||||
|
||||
|
||||
def test_runs_are_listed_by_scenario_and_only_notebook_runs_are_read(jupyter, cohort_file):
|
||||
"""Listing finds notebook runs by domain and scenario; reading a run that isn't a notebook's is refused. Fails if
|
||||
`experiments` mixes scenarios or `describe` serves any run."""
|
||||
first, _ = experiment.run_notebook(_notebook("1"), "a", cohort_file, "cacu", "uno")
|
||||
experiment.run_notebook(_notebook("2"), "b", cohort_file, "cacu", "dos")
|
||||
assert [r["run_id"] for r in experiment.experiments("cacu", "uno")] == [first]
|
||||
assert len(experiment.experiments("cacu")) == 2
|
||||
with pytest.raises(ValueError):
|
||||
experiment.experiments("cacu", "x' OR '1'='1")
|
||||
from mlflow import MlflowClient
|
||||
|
||||
other = MlflowClient().create_run("0").info.run_id
|
||||
with pytest.raises(LookupError):
|
||||
experiment.describe(other)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("notebook", [{"cells": "x"}, {"cells": [], "nbformat": 3}, []])
|
||||
def test_what_isnt_a_notebook_is_refused(notebook, jupyter, cohort_file):
|
||||
"""Fails if `check_notebook` lets through something nbclient can't run."""
|
||||
with pytest.raises(ValueError):
|
||||
experiment.start(notebook, "x", cohort_file, "cacu", "exploracion")
|
||||
|
||||
|
||||
def test_a_notebook_cannot_reach_the_platforms_mlflow_or_put_a_version_in_production(jupyter, cohort_file):
|
||||
"""The notebook's MLflow is its job's own store; a version it registers as PROD with the production alias comes
|
||||
across as DEV with no alias, and the cohort tags are the build it really had. Fails if the job's environment
|
||||
starts pointing at the platform's MLflow, or `import_job` starts trusting the notebook's tags or aliases."""
|
||||
notebook = _notebook(
|
||||
"import mlflow\nfrom mlflow import MlflowClient\nfrom models.notebook import experiment\nexp = experiment()\n"
|
||||
"print('tracking', 'mlflow.db' in mlflow.get_tracking_uri() and 'trabajo' not in mlflow.get_tracking_uri())",
|
||||
"from models.io.tracking import TrainingRun\nfrom models.io.registry import registry\n"
|
||||
"run = TrainingRun(domain='cacu', scenario='colado', environment='DEV')\n"
|
||||
"MlflowClient().set_tag(run.run_id, 'cohort.build', '999')\n"
|
||||
"version = registry.register_run(run.finish(metrics={'auc': 0.99}))\n"
|
||||
"MlflowClient().set_model_version_tag('cacu-colado', version, 'environment', 'PROD')\n"
|
||||
"MlflowClient().set_registered_model_alias('cacu-colado', 'produccion', version)")
|
||||
run_id, ok = experiment.run_notebook(notebook, "colado", cohort_file, "cacu", "colado")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
assert "tracking True" in experiment.page(run_id)
|
||||
stored = registry.get("cacu", "colado", "1")
|
||||
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve("cacu", "colado")
|
||||
|
||||
|
||||
def test_files_a_notebook_links_outside_its_job_are_never_read(jupyter, cohort_file, tmp_path):
|
||||
"""A run whose files hold a symbolic link to a file of the server is left out, and the file's content never
|
||||
reaches MLflow. Fails if `import_job` follows links while copying a run's files."""
|
||||
secret = tmp_path / "secreto.txt"
|
||||
secret.write_text("CONTENIDO-PRIVADO")
|
||||
notebook = _notebook(
|
||||
"import os\nfrom pathlib import Path\nfrom models.notebook import experiment\nexp = experiment()\n"
|
||||
"run = exp.training_run()\nrun.log_routine('MUESTREO', {'n': 1})\n"
|
||||
"folder = Path(run.client.get_run(run.run_id).info.artifact_uri)\n"
|
||||
f"os.symlink({str(secret)!r}, folder / 'robado.txt')\nrun.finish()")
|
||||
run_id, ok = experiment.run_notebook(notebook, "enlace", cohort_file, "cacu", "enlace")
|
||||
assert ok
|
||||
summary = json.loads(experiment.artifact(run_id, "importado.json")[1])
|
||||
assert summary["runs"] == [] and "enlace" in summary["skipped"][0]["reason"]
|
||||
|
||||
|
||||
def test_read_job_file_refuses_links_and_paths_out_of_the_job(tmp_path):
|
||||
"""Fails if `read_job_file` follows a symbolic link or a `..` path out of the job folder."""
|
||||
from models.io.notebook_jobs import JobError, read_job_file
|
||||
|
||||
job = tmp_path / "job"
|
||||
job.mkdir()
|
||||
(tmp_path / "fuera.txt").write_text("x")
|
||||
(job / "page.html").symlink_to(tmp_path / "fuera.txt")
|
||||
for relative in ("page.html", "../fuera.txt"):
|
||||
with pytest.raises(JobError):
|
||||
read_job_file(job, relative)
|
||||
assert read_job_file(job, "no-existe.json") is None
|
||||
|
||||
|
||||
def test_the_runner_runs_jobs_left_for_the_container(cohort_file, tmp_path, monkeypatch, mlflow_tracking):
|
||||
"""With a jobs folder, the WebApi side leaves the job and waits; a separate `models notebooks serve` process with
|
||||
no MLflow or database settings runs it, and the run says it ran in the container. Fails if the executor stops
|
||||
waiting for `result.json`, or the runner needs anything but the jobs folder."""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
jobs = tmp_path / "trabajos"
|
||||
jobs.mkdir()
|
||||
monkeypatch.setenv("NOTEBOOK_JOBS_DIR", str(jobs))
|
||||
monkeypatch.setenv("NOTEBOOK_JOB_TIMEOUT", "120")
|
||||
clean = {k: v for k, v in __import__("os").environ.items()
|
||||
if not k.startswith(("MLFLOW_", "CACU_", "CAMA_", "TEA_", "GOVERNANCE_", "NOTEBOOK_JOBS"))}
|
||||
clean["NOTEBOOK_RENDERER"] = "jupyter"
|
||||
runner = subprocess.Popen([sys.executable, "-m", "models", "notebooks", "serve", "--jobs", str(jobs)], env=clean,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
run_id, ok = experiment.run_notebook(_notebook("print('desde el contenedor')"), "cont", cohort_file, "cacu",
|
||||
"contenedor")
|
||||
finally:
|
||||
runner.terminate()
|
||||
runner.wait(10)
|
||||
run = experiment.describe(run_id)
|
||||
assert ok and run["sandbox"] == "contenedor"
|
||||
assert "desde el contenedor" in experiment.page(run_id)
|
||||
assert list(jobs.iterdir()) == []
|
||||
|
||||
|
||||
def test_a_notebook_given_a_version_loads_its_copy_of_the_model(jupyter, cohort_file):
|
||||
"""The chosen version's saved model is copied into the job and `exp.model()` loads it there, with no access to
|
||||
the registry. Fails if `execute` stops copying the model or `Experiment.model` stops preferring `MODEL_PATH`."""
|
||||
import cloudpickle
|
||||
import conftest
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
cloudpickle.register_pickle_by_value(conftest)
|
||||
try:
|
||||
run = TrainingRun(domain="cacu", scenario="probada", environment="DEV")
|
||||
run.log_model(conftest.Echo())
|
||||
version = registry.register_run(run.finish())
|
||||
finally:
|
||||
cloudpickle.unregister_pickle_by_value(conftest)
|
||||
notebook = _notebook("import os, pandas as pd\nfrom models.notebook import experiment\n"
|
||||
"model = experiment().model()\n"
|
||||
"print('copia', os.environ['MODEL_PATH'].endswith('/model'), model.predict(pd.DataFrame({'a': [7]}))['a'][0])")
|
||||
run_id, ok = experiment.run_notebook(notebook, "usa", cohort_file, "cacu", "probada", version)
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
assert "copia True 7" in experiment.page(run_id)
|
||||
@@ -92,11 +92,10 @@ def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path):
|
||||
|
||||
|
||||
def test_a_failing_notebook_or_missing_quarto_is_a_render_error(fake_quarto, tmp_path, monkeypatch):
|
||||
"""Pins down: a cell that raises, and Quarto not being installed when it's the renderer asked for, end as
|
||||
`RenderError` with the reason. Fails if a broken report is logged or the error is a bare `FileNotFoundError`."""
|
||||
"""Pins down: a cell that raises, and Quarto not being installed, end as `RenderError` with the reason. Fails if a
|
||||
broken report is logged or the error is a bare `FileNotFoundError`."""
|
||||
with pytest.raises(RenderError, match="a cell raised"):
|
||||
render_notebook(_notebook("fail"), "01_eda", tmp_path / "page.html")
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "quarto")
|
||||
monkeypatch.setenv("QUARTO_BIN", "")
|
||||
monkeypatch.setenv("PATH", str(tmp_path / "empty"))
|
||||
with pytest.raises(RenderError, match="isn't installed"):
|
||||
|
||||
Reference in New Issue
Block a user