updating nlp policies; more robust recognition beyond rules

This commit is contained in:
Roberto Treviño Cervantes
2026-11-13 11:52:51 -06:00
parent 1b45bc61d7
commit 11e768893e
3 changed files with 278 additions and 0 deletions
+1
View File
@@ -27,6 +27,7 @@ WebApi.
| `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. |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
+180
View File
@@ -0,0 +1,180 @@
"""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",
},
}
+97
View File
@@ -0,0 +1,97 @@
"""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) == []