Training config: reference name and mains frequency: GET /models/{domain}/{name}/training-config; POST train accepts reference
This commit is contained in:
@@ -0,0 +1,65 @@
|
|||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def empty_reference_root(platform, tmp_path):
|
||||||
|
root = tmp_path / "reference"
|
||||||
|
root.mkdir()
|
||||||
|
platform.env["TEA_REFERENCE_ROOT"] = str(root)
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(response):
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tea_training_config_schema(api):
|
||||||
|
config = _ok(api.get("/models/tea/example/training-config"))
|
||||||
|
assert (config["domain"], config["name"]) == ("tea", "example")
|
||||||
|
schema = config["json_schema"]
|
||||||
|
assert schema["title"] == "TrainingForm"
|
||||||
|
assert set(schema["properties"]) == {"as_of", "execution", "reference"}
|
||||||
|
assert schema["properties"]["as_of"]["title"] == "Datos hasta"
|
||||||
|
assert set(schema["$defs"]) == {"Execution", "Reference"}
|
||||||
|
execution = schema["$defs"]["Execution"]
|
||||||
|
assert execution["title"] == "Ejecución"
|
||||||
|
assert execution["properties"]["mode"]["title"] == "Modo"
|
||||||
|
assert execution["properties"]["scheduler"]["title"] == "Planificador Dask"
|
||||||
|
reference = schema["$defs"]["Reference"]["properties"]
|
||||||
|
assert reference["name"]["title"] == "Cohorte de referencia"
|
||||||
|
assert reference["line_hz"]["title"] == "Frecuencia de la red eléctrica (Hz)"
|
||||||
|
assert reference["line_hz"]["enum"] == [50, 60]
|
||||||
|
assert config["defaults"] == {
|
||||||
|
"execution": {"mode": "sync", "scheduler": None},
|
||||||
|
"reference": {"line_hz": 50},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_domains_have_no_reference(api):
|
||||||
|
for domain in ("cacu", "cama"):
|
||||||
|
config = _ok(api.get(f"/models/{domain}/example/training-config"))
|
||||||
|
assert (config["domain"], config["name"]) == (domain, "example")
|
||||||
|
schema = config["json_schema"]
|
||||||
|
assert set(schema["properties"]) == {"as_of", "execution"}
|
||||||
|
assert set(schema["$defs"]) == {"Execution"}
|
||||||
|
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_train_validates_the_reference(api):
|
||||||
|
response = api.post("/models/cacu/train", json={"reference": {"name": "nope"}})
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"] == "cacu models take no reference cohort"
|
||||||
|
|
||||||
|
for reference in ({"name": "../x"}, {"name": "nope", "line_hz": 55}):
|
||||||
|
response = api.post("/models/tea/train", json={"reference": reference})
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
run_id = _ok(api.post("/models/tea/train", json={"reference": {"name": "nope"}}))["run_id"]
|
||||||
|
deadline = time.monotonic() + 120
|
||||||
|
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] in ("queued", "running"):
|
||||||
|
assert time.monotonic() < deadline, run
|
||||||
|
time.sleep(1)
|
||||||
|
assert run["state"] == "failed"
|
||||||
|
assert "no reference cohort 'nope'" in run["error"]
|
||||||
+41
-7
@@ -4,16 +4,17 @@ scoring runs (Dagster). The API starts runs and reads the registry; it never tra
|
|||||||
import mimetypes
|
import mimetypes
|
||||||
import zipfile
|
import zipfile
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Annotated
|
from typing import Annotated, Any
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from core import domains
|
||||||
from core.domains import Domain
|
from core.domains import Domain
|
||||||
from persistance import bundle, registry
|
from persistance import bundle, cluster, registry
|
||||||
from persistance.cluster import Execution
|
from persistance.cluster import Execution, Reference
|
||||||
from webapi.runs import dagster, execution_config, submit
|
from webapi.runs import dagster, execution_config, submit
|
||||||
|
|
||||||
router = APIRouter(prefix="/models", tags=["models"])
|
router = APIRouter(prefix="/models", tags=["models"])
|
||||||
@@ -135,10 +136,37 @@ def promote(domain: Domain, name: str, version: int) -> dict:
|
|||||||
return {"champion": version}
|
return {"champion": version}
|
||||||
|
|
||||||
|
|
||||||
class Training(BaseModel):
|
class TrainingForm(BaseModel):
|
||||||
as_of: date | None = None # the date the data are taken up to (default: today)
|
as_of: date | None = Field(
|
||||||
models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence)
|
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
||||||
|
)
|
||||||
execution: Execution | None = None
|
execution: Execution | None = None
|
||||||
|
reference: Reference | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Training(TrainingForm):
|
||||||
|
models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence)
|
||||||
|
|
||||||
|
|
||||||
|
class TrainingConfig(BaseModel):
|
||||||
|
domain: str
|
||||||
|
name: str
|
||||||
|
json_schema: dict[str, Any]
|
||||||
|
defaults: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/training-config")
|
||||||
|
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
||||||
|
json_schema = TrainingForm.model_json_schema()
|
||||||
|
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
||||||
|
if "reference" in getattr(domains.part(domain), "TRAINING_OPTIONS", ()):
|
||||||
|
defaults["reference"] = {"line_hz": 50}
|
||||||
|
else:
|
||||||
|
del json_schema["properties"]["reference"]
|
||||||
|
del json_schema["$defs"]["Reference"]
|
||||||
|
return TrainingConfig(
|
||||||
|
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class Analyze(BaseModel):
|
class Analyze(BaseModel):
|
||||||
@@ -149,11 +177,17 @@ class Analyze(BaseModel):
|
|||||||
def train(domain: Domain, request: Training,
|
def train(domain: Domain, request: Training,
|
||||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||||
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
||||||
|
if request.reference is not None and "reference" not in getattr(
|
||||||
|
domains.part(domain), "TRAINING_OPTIONS", ()
|
||||||
|
):
|
||||||
|
raise HTTPException(422, f"{domain.value} models take no reference cohort")
|
||||||
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||||
if request.as_of:
|
if request.as_of:
|
||||||
config["as_of"] = request.as_of.isoformat()
|
config["as_of"] = request.as_of.isoformat()
|
||||||
if request.models:
|
if request.models:
|
||||||
config["models"] = request.models
|
config["models"] = request.models
|
||||||
|
if request.reference is not None:
|
||||||
|
config["reference"] = request.reference.model_dump()
|
||||||
return submit(client, "train", "train_models", config, domain=domain.value)
|
return submit(client, "train", "train_models", config, domain=domain.value)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user