128 lines
6.3 KiB
Python
128 lines
6.3 KiB
Python
"""Training any scenario: one driver built from the modules its `model.toml` lists, its config, a cohort source and
|
|
the adapters.
|
|
|
|
A scenario is a folder with `model.toml` and its dataflow. `model.toml` names it (`domain`, `scenario`, `cohort`,
|
|
`outcome`, `description`), lists the `modules` whose functions are the graph's nodes, and holds `[config]`, the values
|
|
the dataflow receives through `with_config`. The dataflow goes from `cohort` and `cohort_lineage` to `fitted_model` (a
|
|
scikit-learn estimator that takes the long frame) and `metrics`, with no I/O.
|
|
|
|
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
|
|
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
|
|
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed
|
|
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold
|
|
members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import tomllib
|
|
from dataclasses import dataclass
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
from types import ModuleType
|
|
|
|
from hamilton import base, driver
|
|
from hamilton.io.materialization import from_, to
|
|
|
|
from models.io import adapters # noqa: F401 (registers the loaders and the saver)
|
|
from models.io.lineage import code_version, matches
|
|
from models.io.registry import registered_name, registry
|
|
from models.io.storage import CohortSource
|
|
from models.io.tracking import TrainingRun
|
|
|
|
REGISTERED_MODEL = "registered_model"
|
|
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
|
|
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Scenario:
|
|
domain: str
|
|
scenario: str
|
|
cohort: str
|
|
outcome: str
|
|
description: str
|
|
modules: tuple[ModuleType, ...]
|
|
config: dict
|
|
folder: Path
|
|
requirements: tuple[str, ...] = ()
|
|
|
|
@classmethod
|
|
def from_toml(cls, path: str | Path) -> "Scenario":
|
|
path = Path(path)
|
|
found = tomllib.loads(path.read_text())
|
|
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
|
|
outcome=found["outcome"], description=found.get("description", ""),
|
|
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
|
|
folder=path.parent, requirements=tuple(found.get("requirements", ())))
|
|
|
|
@classmethod
|
|
def load(cls, domain: str, scenario: str) -> "Scenario":
|
|
"""`models/<domain>/<scenario>/model.toml`; `LookupError` if there's no such scenario."""
|
|
try:
|
|
package = import_module(f"models.{domain}.{scenario}")
|
|
except ModuleNotFoundError as error:
|
|
raise LookupError(f"no such model: {domain}/{scenario}") from error
|
|
return cls.from_toml(Path(package.__file__).parent / "model.toml")
|
|
|
|
def config_sha256(self) -> str:
|
|
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
|
|
|
|
|
|
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
|
|
"""The graph of these modules. Without materializers it takes `cohort` and `cohort_lineage` as inputs."""
|
|
builder = driver.Builder().with_modules(*modules).with_config(config)
|
|
if materializers:
|
|
builder = builder.with_materializers(*materializers)
|
|
return builder.build()
|
|
|
|
|
|
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
|
|
"""The graph's inputs that some node requires, and those every node taking them has a default for."""
|
|
variables = dr.list_available_variables()
|
|
inputs = {v.name for v in variables if v.is_external_input}
|
|
required = set().union(*(v.required_dependencies for v in variables)) & inputs
|
|
return required, inputs - required
|
|
|
|
|
|
def expected_params(scenario: Scenario, source: CohortSource) -> dict[str, str]:
|
|
return {**source.reference(), **code_version(), "config_sha256": scenario.config_sha256()}
|
|
|
|
|
|
def find_trained(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str | None:
|
|
"""The newest version not retired from the same source reference, `models` version, config and environment."""
|
|
name = registered_name(scenario.domain, scenario.scenario)
|
|
expected = expected_params(scenario, source)
|
|
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
|
|
for mv in versions:
|
|
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
|
|
continue
|
|
if matches(registry.client.get_run(mv.run_id).data.params, expected):
|
|
return str(mv.version)
|
|
return None
|
|
|
|
|
|
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
|
|
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
|
|
rows."""
|
|
logging.getLogger(HAMILTON_NODE_ERRORS).setLevel(logging.CRITICAL)
|
|
run = TrainingRun(domain=scenario.domain, scenario=scenario.scenario, environment=environment,
|
|
cohorte_armado_id=source.armado_id, cohort=source.reference())
|
|
try:
|
|
plain = dataflow(*scenario.modules, config=scenario.config)
|
|
required, _ = external_inputs(plain)
|
|
loaders = [loader(target=target, source=source) for target, loader in
|
|
(("cohort", from_.cohort_source), ("cohort_lineage", from_.cohort_source_lineage))
|
|
if target in required]
|
|
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=["fitted_model", "metrics"],
|
|
combine=base.DictResult(), run=run, description=scenario.description,
|
|
hyperparameters={**expected_params(scenario, source), **scenario.config},
|
|
requirements=list(scenario.requirements))
|
|
dr = dataflow(*scenario.modules, config=scenario.config, materializers=(*loaders, saver))
|
|
result = dr.execute([REGISTERED_MODEL])
|
|
except BaseException:
|
|
run.client.set_terminated(run.run_id, status="FAILED")
|
|
raise
|
|
return result[REGISTERED_MODEL]["version"]
|