Training, estimating and running on dbt cohort builds: runs and versions record the cohort file they used
This commit is contained in:
+34
-10
@@ -32,20 +32,30 @@ def _cohort_file(args: argparse.Namespace, model):
|
||||
"""The build's exported file; `None` and a message on stderr if it's missing."""
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, find_cohort_file
|
||||
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
|
||||
|
||||
url = model.SETTINGS["cohort"]
|
||||
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
return find_cohort_file(root, model.SETTINGS["cohort"], args.armado)
|
||||
if args.source == "kit":
|
||||
return find_cohort_file(root, url, args.armado)
|
||||
if args.armado is not None:
|
||||
if not (path := dbt_build_path(root, url, args.armado)).exists():
|
||||
raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
if not (latest := latest_dbt_build(root, url)):
|
||||
raise FileNotFoundError(f"no exported dbt builds of {url} under {root}")
|
||||
return latest[1]
|
||||
except (FileNotFoundError, ValueError) as error:
|
||||
print(f"{error}: export it with `python -m models cohorts export {model.SETTINGS['cohort'].replace('/', ' ')}`", file=sys.stderr)
|
||||
print(f"{error}: export it with `{command}`", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Trains the model on the build's file, always as a new version."""
|
||||
if args.environment == "prod" and args.armado is None:
|
||||
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
|
||||
return 1
|
||||
if not (path := _cohort_file(args, model)):
|
||||
@@ -98,8 +108,12 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
parser.error("name at least one step: --export, --train, --promote, --estimate")
|
||||
if args.estimate and not args.output:
|
||||
parser.error("--estimate needs --output")
|
||||
if args.train and args.environment == "prod" and args.armado is None:
|
||||
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
||||
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if args.export and args.source == "dbt" and not args.manifest:
|
||||
parser.error("--export with --source dbt needs --manifest")
|
||||
if args.export and args.source == "dbt" and args.armado is not None:
|
||||
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
|
||||
if args.train and args.version:
|
||||
parser.error("--version names an existing version: it can't go with --train")
|
||||
if not (model := _model_module(args, "model")):
|
||||
@@ -107,7 +121,10 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
|
||||
if args.export:
|
||||
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
|
||||
export = argparse.Namespace(domain=args.domain, cohort=cohort, source="kit", build=args.armado, manifest=None)
|
||||
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
|
||||
manifest=args.manifest)
|
||||
if args.source == "dbt":
|
||||
export.build = None
|
||||
if code := _cohort_export(export):
|
||||
return code
|
||||
if not (args.train or args.promote or args.estimate):
|
||||
@@ -234,7 +251,9 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
|
||||
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
||||
train.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
train.set_defaults(run=lambda args: _train(train, args))
|
||||
|
||||
@@ -242,7 +261,9 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
||||
estimate.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
||||
estimate.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
estimate.add_argument("--version", help="the model version; the one in production by default")
|
||||
estimate.set_defaults(run=_estimate)
|
||||
|
||||
@@ -253,10 +274,13 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
|
||||
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
|
||||
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
|
||||
run.add_argument("--armado", type=int, help="the build's armado_id; the latest by default")
|
||||
run.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
||||
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
run.add_argument("--output", help="the Parquet file --estimate writes")
|
||||
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))
|
||||
return parser
|
||||
|
||||
|
||||
@@ -7,31 +7,32 @@ import pyarrow as pa
|
||||
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.contracts import ESTIMATE_COLUMNS
|
||||
from models.io.lineage import matches
|
||||
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
|
||||
from models.io.registry import ResolvedVersion, registered_name, registry
|
||||
from models.io.storage import read_cohort, read_metadata, write_once
|
||||
|
||||
|
||||
def already_estimated(output_path: Path, version: str, armado_id: str) -> bool:
|
||||
"""Whether the output file already holds this version's scores of this build."""
|
||||
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, "armado_id": armado_id})
|
||||
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
|
||||
"""Whether the output file already holds this version's scores of this build's file."""
|
||||
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
|
||||
|
||||
|
||||
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]:
|
||||
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
|
||||
The file's metadata says which version and build its rows come from; `modelo_sha` is copied when the version has
|
||||
The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows
|
||||
come from; `modelo_sha` is copied when the version has
|
||||
it, and isn't checked."""
|
||||
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
|
||||
output_path = Path(output_path)
|
||||
resolved = registry.resolve(domain, scenario, version)
|
||||
armado_id = read_metadata(cohort_path)["armado_id"]
|
||||
if already_estimated(output_path, resolved.version, armado_id):
|
||||
cohort = cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))
|
||||
if already_estimated(output_path, resolved.version, cohort):
|
||||
return resolved, False
|
||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
|
||||
if tuple(risks.columns) != ESTIMATE_COLUMNS:
|
||||
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
|
||||
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
|
||||
"mlflow_run_id": resolved.run_id, "armado_id": armado_id}
|
||||
"mlflow_run_id": resolved.run_id, **cohort}
|
||||
if resolved.modelo_sha:
|
||||
provenance["modelo_sha"] = resolved.modelo_sha
|
||||
table = pa.Table.from_pandas(risks, preserve_index=False)
|
||||
|
||||
@@ -15,7 +15,7 @@ import pandas as pd
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
|
||||
from models.io.lineage import file_sha256
|
||||
from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256
|
||||
from models.io.registry import registry
|
||||
from models.io.storage import read_cohort, read_metadata
|
||||
from models.io.tracking import TrainingRun
|
||||
@@ -97,9 +97,12 @@ class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
||||
|
||||
def registered_model(fit: LogisticRegression, 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."""
|
||||
"""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=int(lineage["armado_id"]))
|
||||
cohorte_armado_id=armado_id, cohort=cohort)
|
||||
run.log_model(Cin2Logistic(fit))
|
||||
run.finish(metrics=evaluate, hyperparameters={
|
||||
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256})
|
||||
|
||||
@@ -16,6 +16,8 @@ MODEL_SHA_TAG = "modelo_sha"
|
||||
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
|
||||
GIT_DIRTY_TAG = "models.git.dirty"
|
||||
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
|
||||
COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source"
|
||||
COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256"
|
||||
|
||||
|
||||
def registered_name(domain: str, scenario: str) -> str:
|
||||
@@ -44,6 +46,15 @@ def model_sha(model_dir: str | Path) -> str:
|
||||
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
|
||||
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
|
||||
`dbt`), its number in that source and the file's hash. A kit build's number is its `armado_id`."""
|
||||
source = metadata.get("producer", "kit")
|
||||
build = metadata["armado_id"] if source == "kit" else metadata["build"]
|
||||
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
|
||||
COHORT_FILE_TAG: file_sha256}
|
||||
|
||||
|
||||
def file_sha256(*paths: str | Path) -> str:
|
||||
"""The hash of these files' bytes, in this order."""
|
||||
digest = hashlib.sha256()
|
||||
|
||||
@@ -148,7 +148,7 @@ class ModelRegistry:
|
||||
|
||||
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
|
||||
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
|
||||
cohort link, `modelo_sha`, report URIs), and returns the version."""
|
||||
cohort link and cohort file, `modelo_sha`, report URIs), and returns the version."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
@@ -161,6 +161,7 @@ class ModelRegistry:
|
||||
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
|
||||
if run.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
|
||||
version_tags.update(run.cohort)
|
||||
if run.modelo_sha is not None:
|
||||
version_tags[MODEL_SHA_TAG] = run.modelo_sha
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
|
||||
+10
-5
@@ -72,9 +72,10 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str |
|
||||
|
||||
class TrainingRun:
|
||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
||||
runs require `cohorte_armado_id`, the indicator kit cohort build they were
|
||||
trained on, so their metrics trace back to that data (ML-03); dev runs may
|
||||
omit it.
|
||||
runs name the cohort build they were trained on, so their metrics trace
|
||||
back to that data (ML-03): `cohort`, the reference to its file
|
||||
(`models.io.lineage.cohort_reference`), or `cohorte_armado_id`, a kit build
|
||||
by number; dev runs may omit both.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -84,17 +85,19 @@ class TrainingRun:
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
cohort: dict[str, str] | None = None,
|
||||
):
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
environment = Environment(environment)
|
||||
if environment is Environment.PROD and cohorte_armado_id is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
|
||||
if environment is Environment.PROD and cohorte_armado_id is None and cohort is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id o cohort).")
|
||||
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.environment = environment
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.cohort = dict(cohort or {})
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
@@ -105,6 +108,8 @@ class TrainingRun:
|
||||
self.modelo_sha: str | None = None
|
||||
if cohorte_armado_id is not None:
|
||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
||||
for tag, value in self.cohort.items():
|
||||
self.client.set_tag(self.run_id, tag, value)
|
||||
|
||||
def _experiment_id(self) -> str:
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
|
||||
@@ -136,7 +136,7 @@ def test_prod_without_a_build_is_refused(capsys):
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(["train", "cacu", "cin2_logistic", "--environment", "prod"])
|
||||
|
||||
assert stopped.value.code == 2 and "--armado" in capsys.readouterr().err
|
||||
assert stopped.value.code == 2 and "--build" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arguments, message", [
|
||||
@@ -166,7 +166,7 @@ def test_estimate_scores_each_member_with_the_production_version(exported, mlflo
|
||||
assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"]
|
||||
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"modelo_version"] == b"1" and metadata[b"armado_id"] == b"12"
|
||||
assert metadata[b"modelo_version"] == b"1" and metadata[b"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit"
|
||||
|
||||
|
||||
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||
@@ -291,3 +291,51 @@ def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_track
|
||||
|
||||
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
|
||||
assert not _versions()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dbt_exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
|
||||
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
|
||||
path = folder / f"{number}.parquet"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
||||
pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path)
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys):
|
||||
"""Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source,
|
||||
number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is
|
||||
ignored, or the version loses its cohort file."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt"]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert ARMADO_TAG not in tags
|
||||
assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia")
|
||||
assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating
|
||||
it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the
|
||||
dbt file."""
|
||||
output = tmp_path / "output.parquet"
|
||||
|
||||
assert main(["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod",
|
||||
"--train", "--promote", "--estimate", "--output", str(output)]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1"
|
||||
assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"]
|
||||
|
||||
|
||||
def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys):
|
||||
"""Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's
|
||||
command is suggested or another build is used."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt", "--build", "9"]) == 1
|
||||
assert "--source dbt" in capsys.readouterr().err
|
||||
|
||||
Reference in New Issue
Block a user