Model governance and CaCu measures as FHIR MeasureReports; Phase 2 gate
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
"""Model governance: versions and their reports (MLflow), promotion, and the training and
|
||||
scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import registry
|
||||
from webapi.runs import dagster
|
||||
|
||||
router = APIRouter(prefix="/models", tags=["models"])
|
||||
JOBS = {Domain.CACU: ("train_cacu", "score_cacu")}
|
||||
|
||||
|
||||
class Version(BaseModel):
|
||||
version: int
|
||||
created: int # ms since the epoch
|
||||
aliases: list[str]
|
||||
metrics: dict[str, float]
|
||||
params: dict[str, str]
|
||||
reports: list[str]
|
||||
|
||||
|
||||
@router.get("/{domain}")
|
||||
def models(domain: Domain) -> list[str]:
|
||||
prefix = f"{domain.value}."
|
||||
return [n.removeprefix(prefix) for n in registry.names(prefix)]
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions")
|
||||
def versions(domain: Domain, name: str) -> list[Version]:
|
||||
if not (found := registry.versions(f"{domain.value}.{name}")):
|
||||
raise HTTPException(404, detail=f"no {domain.value} model {name}")
|
||||
return [Version(**v) for v in found]
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
|
||||
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
|
||||
"""The clinical team's validation of a version: the third report promotion needs."""
|
||||
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
|
||||
file.filename or "report", file.file.read()) # fmt: skip
|
||||
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/promote")
|
||||
def promote(domain: Domain, name: str, version: int) -> dict:
|
||||
"""The version risk batches come from from now on; refused (409) without its three
|
||||
reports: technical validation, interpretability and clinical validation."""
|
||||
try:
|
||||
registry.promote(f"{domain.value}.{name}", version)
|
||||
except registry.MissingReports as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
return {"champion": version}
|
||||
|
||||
|
||||
class Training(BaseModel):
|
||||
as_of: date | None = None # the date the data are taken up to (default: today)
|
||||
|
||||
|
||||
def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
|
||||
try:
|
||||
run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}})
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.post("/{domain}/train")
|
||||
def train(domain: Domain, request: Training,
|
||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
||||
if domain not in JOBS:
|
||||
raise HTTPException(404, detail=f"{domain.value} has no models yet")
|
||||
config = {"as_of": request.as_of.isoformat()} if request.as_of else {}
|
||||
return _submit(client, JOBS[domain][0], "train_models", config)
|
||||
|
||||
|
||||
@router.post("/{domain}/score")
|
||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
"""Starts a risk batch from each model's champion; follow it at /runs."""
|
||||
if domain not in JOBS:
|
||||
raise HTTPException(404, detail=f"{domain.value} has no models yet")
|
||||
return _submit(client, JOBS[domain][1], "score_models", {})
|
||||
Reference in New Issue
Block a user