Skip to content

The platform for continuously improving AI agents.

22.9 KB
Raw Blame
from itertools import islice

from django.conf import settings
from pydantic import ValidationError

from modal_shared.decisions import DECISION_OBJECTIVE
from overbae.core.errors import DatasetError, InputValidationError
from overbae.modal.model_registry import get_model_config_any_backend
from overbae.models import Cell, DataPartitionMember
from overbae.services import (
    benchmark_evaluations,
    decision_serving,
    experiment_assets,
    experiment_execution,
    experiment_interfaces,
    experiment_partitions,
    native_evaluation,
    training_monitoring,
)
from overbae.services.datasets import rows, transform_checks, transform_compiler, use, workbench
from overbae.services.datasets.transform_spec import TransformSpec
from overbae.services.decision_providers import qualify_participants
from overbae.services.experiment_compiler import compile_document, references
from overbae.services.experiment_settings import CONTROL_SETTINGS, benchmark_participants
from overbae.services.research_contract import Benchmark
from overbae.services.training_contract import (
    dataset_objective,
    validate_effective_batch,
    validate_numbers,
)
from sandbox import packages


def validate(project, document):
    problems = issues(project, document)
    if problems:
        raise InputValidationError("Complete the flow configuration:\n" + "\n".join(problems))


def readiness(project, document):
    problems = []
    try:
        document, _ = compile_document(document, {})
    except InputValidationError as exc:
        problems.append(str(exc.detail))
    problems.extend(issues(project, document))
    return {"ready": not problems, "errors": problems}


def issues(project, document):
    nodes = {node["id"]: node for node in document["nodes"]}
    problems = []
    for node in nodes.values():
        if node["kind"] in {"map", "iterate"}:
            child = node.get("config", {}).get("_definition", {})
            if contains_qualification(child) and (
                node["kind"] == "iterate"
                and node["config"].get("max_iterations", 1) > 1
                or node["kind"] == "map"
                and len(node["config"].get("bindings", [])) > node["config"].get("concurrency", 2)
            ):
                problems.append(
                    f"{node['id']}: Place qualification after all adaptive variants or iterations; every final candidate must be materialized before selection"
                )
    for node in nodes.values():
        try:
            validate_node(project, document, nodes, node)
        except InputValidationError as exc:
            problems.append(f"{node['id']}: {exc.detail}")
        except ValidationError as exc:
            details = "; ".join(
                f"{'.'.join(map(str, item['loc']))}: {item['msg']}"
                for item in exc.errors(include_input=False, include_url=False)[:6]
            )
            problems.append(f"{node['id']}: {details}")
        except ValueError as exc:
            problems.append(f"{node['id']}: {exc}")
    return problems


def contains_qualification(value):
    if isinstance(value, dict):
        operation = value.get("operation", {})
        if isinstance(operation, dict):
            arguments = operation.get("arguments", {})
            if (
                operation.get("tool") == "training"
                and arguments.get("operation") == "qualify"
                or operation.get("tool") == "benchmark"
                and arguments.get("phase") == "final"
            ):
                return True
        return any(contains_qualification(child) for child in value.values())
    return isinstance(value, list) and any(contains_qualification(child) for child in value)


def validate_node(project, document, nodes, node):
    operation = node.get("operation") or {}
    if list(references(operation)):
        return
    connected = {}
    for edge in document["edges"]:
        if edge["target"] != node["id"]:
            continue
        source = nodes[edge["source"]]
        reserving = node["kind"] == "train" and edge["input"] == "final"
        if source["kind"] == "split" and (edge["output"] != "final" or reserving):
            # A partition that already exists is checked like the dataset it yields. A train
            # stage's reservation is compared with its training rows, never read.
            cell = Cell.objects.filter(
                pk=experiment_partitions.member_cell(project, document, edge),
                dataset__project=project,
            ).first()
            uncut = cell is None and node["kind"] == "train" and not reserving
            if uncut:
                # A partition cut when the flow runs has the columns of the data it is cut
                # from: a train stage is checked against that until its member exists.
                cell = Cell.objects.filter(
                    pk__in=[
                        nodes[feeding["source"]]["config"].get("cell")
                        for feeding in document["edges"]
                        if feeding["target"] == source["id"]
                        and nodes[feeding["source"]]["kind"] == "data"
                        and not list(references(nodes[feeding["source"]]["config"]))
                    ],
                    dataset__project=project,
                ).first()
            if cell is not None:
                source = {
                    "id": f"{edge['source']}.{edge['output']}",
                    "kind": "data",
                    "uncut": uncut,
                    "config": {
                        "cell": str(cell.pk),
                        "fingerprint": cell.fingerprint,
                        "dataset": str(cell.dataset_id),
                    },
                }
        connected[edge["input"]] = source
    if isinstance(node["config"].get("model"), dict):
        connected["model"] = {"kind": "model", "config": node["config"]["model"]}
    validate_operation(
        project,
        node,
        connected,
        objective=prepared_objective(document, nodes, connected.get("data")),
    )


def prepared_objective(document, nodes, source):
    visited = set()
    while source and source["id"] not in visited:
        visited.add(source["id"])
        operation = source.get("operation") or {}
        if list(references(operation)):
            return None
        if experiment_interfaces.operation_key(source) == ("platform", "prepare_dataset"):
            TransformSpec.model_validate(operation["arguments"].get("arguments", {}).get("spec"))
            return DECISION_OBJECTIVE
        if source["kind"] != "split":
            return None
        upstream = [
            nodes[edge["source"]]
            for edge in document["edges"]
            if edge["target"] == source["id"] and edge["input"] == "data"
        ]
        source = upstream[0] if len(upstream) == 1 else None
    return None


def validate_resolved(project, node, inputs):
    experiment_interfaces.validate_inputs(node, inputs)
    connected = {}
    for port, value in inputs.items():
        bindings = value if isinstance(value, list) else [value]
        for binding in bindings:
            if binding.get("cell") and binding.get("kind") == "data":
                cell = (
                    Cell.objects.select_related("dataset")
                    .filter(pk=binding["cell"], dataset__project=project)
                    .first()
                )
                if cell is None or not cell.ran:
                    raise InputValidationError(f"{port}: the connected dataset cell is unavailable")
                if binding.get("fingerprint") != cell.fingerprint:
                    raise InputValidationError(f"{port}: the connected dataset fingerprint changed")
                if binding.get("dataset") != str(cell.dataset_id):
                    raise InputValidationError(f"{port}: the connected dataset identity changed")
        if isinstance(value, dict):
            config = {"_checkpoint": value} if value.get("job") else value
            connected[port] = {"id": port, "kind": value.get("kind"), "config": config}
    try:
        validate_operation(project, node, connected)
    except ValueError as exc:
        raise InputValidationError(f"{node['id']}: {exc}") from exc


def trainable(project, training, selecting):
    """Campaign admission's checks of its data, made when the train stage is written."""

    def bound(source):
        if not source or source["kind"] != "data" or list(references(source["config"])):
            return None
        return (
            Cell.objects.select_related("dataset")
            .filter(pk=source["config"].get("cell"), dataset__project=project)
            .first()
        )

    def admitted(source, role):
        cell = bound(source)
        if cell is None:
            return None
        if source.get("uncut"):
            # Only the rows carry over into a partition that is not cut yet; its members get
            # datasets of their own.
            fits, reason = cell.fits("train")
            if not fits:
                raise DatasetError(f"{cell.dataset.name}: {reason}.")
        else:
            use.check(cell.dataset, role, cell=cell, verify=False)
        return cell

    def held_out(cell):
        # The partition a model is trained or selected on holds its final data back.
        member = (
            DataPartitionMember.objects.filter(
                plan__members__cell=cell, plan__project=project, role="final"
            )
            .select_related("cell__dataset")
            .first()
        )
        return member.cell if member else None

    try:
        cell = admitted(training, "train")
        selected = admitted(selecting, "development")
        held = (selected and held_out(selected)) or (cell and held_out(cell))
        if cell and held and not training.get("uncut"):
            use.check_held_out(cell, held)
    except DatasetError as exc:
        raise InputValidationError(
            f"{exc.detail} Training reads a version in a training dataset whose rows a trainer "
            "can read: a partition's train output, or what the Workshop publishes when it "
            "prepares data from that output."
        ) from exc
    if cell and selected and dataset_objective(cell) != dataset_objective(selected):
        raise InputValidationError(
            f"{cell.dataset.name} and {selected.dataset.name} are in different training "
            "formats. Training and development data come from one preparation."
        )


def validate_operation(project, node, connected, *, objective=None):
    operation = node.get("operation") or {}
    if operation.get("tool") == "platform":
        name = operation["arguments"].get("name")
        arguments = operation["arguments"].get("arguments", {})
        if name == "import_traces":
            from overbae.services.connectors.imports import connector

            connector(project, arguments.get("connector"))
        if name == "create_data_partition":
            upstream = ((connected.get("data") or {}).get("operation") or {}).get("arguments", {})
            spec = (
                upstream.get("arguments", {}).get("spec")
                if upstream.get("name") == "prepare_dataset"
                else None
            )
            if isinstance(spec, dict):
                # The rows a transform spec writes hold the decision and its group keys only.
                keys = {key["name"] for key in spec.get("group_keys", [])}
                recipe = arguments.get("recipe") or {}
                unknown = sorted(set(recipe.get("group_by") or []) - keys)
                if unknown:
                    raise InputValidationError(
                        f"group_by names {', '.join(unknown)}, which the prepared rows do not "
                        f"have. Their group keys: {', '.join(sorted(keys)) or 'none'}. Leave "
                        "group_by out to use them."
                    )
                if recipe.get("stratify_by") not in {None, "decision.target_probabilities", *keys}:
                    raise InputValidationError(
                        "stratify_by names no column of the prepared rows. Leave it out: the "
                        "partition is stratified by label."
                    )
        if name == "measure_serving" and connected.get("scores", {}).get("operation"):
            source_operation = connected["scores"]["operation"]
            if source_operation["tool"] not in {"benchmark", "training"}:
                raise InputValidationError(
                    "Serving performance requires a native decision evaluation"
                )
    if (
        operation.get("tool") == "platform"
        and operation["arguments"].get("name") == "prepare_dataset"
    ):
        arguments = operation["arguments"].get("arguments", {})
        spec = TransformSpec.model_validate(arguments.get("spec"))
        source = connected.get("data") or {}
        cell = (
            Cell.objects.filter(pk=source.get("config", {}).get("cell"), dataset__project=project)
            .select_related("dataset")
            .first()
            if source.get("kind") == "data" and not list(references(source.get("config", {})))
            else None
        )
        if cell is not None:
            try:
                transform_compiler.build(spec, cell)
            except DatasetError as exc:
                raise InputValidationError(exc.detail) from exc
            sample = (row.extra for row in islice(rows.iter_rows(cell), 300))
            for found in transform_checks.label_named(spec, sample):
                # Said before anything runs: the training-data review would refuse the same
                # rows after the preparation had been published.
                raise InputValidationError(
                    f"{node['id']}: input {found['input']} names the row's own "
                    f"{spec.target.column} value in {found['share']:.0%} of {found['rows']} "
                    "sampled rows, so it gives the answer away. Exclude its column as an "
                    "outcome, or derive an input that does not name it."
                )
    if (
        operation.get("tool") == "platform"
        and operation["arguments"].get("name") == "run_dataset_pipeline"
    ):
        arguments = operation["arguments"].get("arguments", {})
        if arguments.get("pipeline"):
            try:
                workbench.resolve_pipeline(
                    project, arguments["pipeline"], parameters=arguments.get("parameters", {})
                )
            except (DatasetError, OSError) as exc:
                raise InputValidationError(f"{node['id']}: {exc}") from exc
    requests = (
        [operation["arguments"]]
        if operation.get("tool") == "serving" and operation["arguments"].get("operation") == "infer"
        else node["config"].get("checks", [])
        if node["kind"] == "publish"
        else []
    )
    for request in requests:
        if request.get("decisions") and (request.get("messages") or request.get("example")):
            raise InputValidationError(
                "Give decisions to a decision model, or messages or a frozen example to a chat "
                "model, not both."
            )
        if request.get("decisions") and not list(references(request["decisions"])):
            decision_serving.validate_requests(request["decisions"])
    source = connected.get("data")
    source_known = source and not list(references(source["config"]))
    selection = node["config"].get("model")
    if (
        operation.get("tool") == "training"
        and operation["arguments"].get("operation") == "create"
        and isinstance(selection, dict)
        and isinstance(selection.get("model"), str)
        and get_model_config_any_backend(selection["model"]) is None
    ):
        raise InputValidationError(
            f"{node['id']}: {selection['model']} is not a training model. Select an exact "
            "model ID from get_model_catalog."
        )
    if operation.get("tool") == "training" and operation["arguments"].get("operation") == "create":
        # start_finetune's own checks, said when the stage is written.
        recipe = operation["arguments"].get("arguments", {}).get("run", {}).get("hyperparameters")
        if isinstance(recipe, dict) and not list(references(recipe)):
            validate_numbers(recipe)
            if settings.FINETUNING_BACKEND == "modal":
                validate_effective_batch(recipe)
    if (
        operation.get("tool") == "training"
        and operation["arguments"].get("operation") == "create"
        and source_known
        and source["kind"] == "data"
    ):
        cell = Cell.objects.select_related("dataset").get(
            pk=source["config"]["cell"], dataset__project=project
        )
        objective = dataset_objective(cell)
        trainable(project, source, connected.get("development"))
    if (
        operation.get("tool") == "training"
        and operation["arguments"].get("operation") == "create"
        and objective is not None
    ):
        run = operation["arguments"].get("arguments", {}).get("run", {})
        training_monitoring.resolve(
            {**run.get("hyperparameters", {}), "objective": objective},
            has_development="development" in connected,
            provider=settings.FINETUNING_BACKEND,
            monitoring=run.get("monitoring"),
        )
    if operation.get("tool") == "platform" and source_known and source["kind"] == "data":
        experiment_execution.arguments(node, {"data": source["config"]})
    if node["kind"] == "component":
        asset = experiment_assets.get(project, node["config"].get("asset"), "component")
        if asset.definition["runtime"] != packages.runtime_id():
            raise InputValidationError(f"{node['id']}: The pinned component runtime is unavailable")
        experiment_assets.check_schema(
            asset.definition["parameters"],
            operation.get("arguments", {}).get("parameters", {}),
            validate=True,
        )
    if operation.get("tool") == "prediction":
        candidate_node = connected.get("model")
        if (
            candidate_node
            and candidate_node["kind"] == "model"
            and candidate_node["config"].get("asset")
        ):
            candidate = experiment_assets.get(
                project, candidate_node["config"]["asset"], "candidate"
            )
            if candidate.definition["kind"] == "checkpoint":
                raise InputValidationError(
                    f"{node['id']}: Checkpoint candidates require the native benchmark adapter; they do not support catalogue Predict"
                )
            expected_runtime = (
                packages.runtime_id()
                if candidate.definition["kind"] == "component"
                else experiment_assets.runtime_identity()
            )
            if candidate.definition["runtime"] != expected_runtime:
                raise InputValidationError(
                    f"{node['id']}: The pinned candidate runtime is unavailable"
                )
    if operation.get("tool") == "score":
        suite_node = connected.get("suite")
        if suite_node and suite_node["kind"] == "suite":
            suite = experiment_assets.get(project, suite_node["config"].get("asset"), "suite")
            if suite.definition["runtime"] != experiment_assets.scoring_identity():
                raise InputValidationError(
                    f"{node['id']}: The pinned scoring runtime is unavailable"
                )
    if operation.get("tool") != "benchmark":
        return
    arguments = dict(operation["arguments"])
    suite_node = connected.get("suite")
    suite = (suite_node or {}).get("config", {}).get("asset")
    if suite and not list(references(suite)):
        arguments["suite"] = suite
    use_eval_set = arguments.get("eval_set") or arguments.get("suite") or suite_node
    if source is None:
        raise InputValidationError(f"Connect evaluation data to {node['title']}")
    if source_known and source["kind"] == "data":
        cell = Cell.objects.select_related("dataset").get(
            pk=source["config"]["cell"], dataset__project=project
        )
        try:
            if use_eval_set:
                benchmark_evaluations.check_data(cell)
            else:
                native_evaluation.validate_suite(
                    project, cell, purpose=arguments.get("phase", "development")
                )
        except (InputValidationError, DatasetError) as exc:
            raise InputValidationError(
                f"Data input {source['id']} (cell {cell.pk}): {exc.detail}. "
                "Connect a compatible evaluation cell or transform its rows before this benchmark."
            ) from exc
    participants = arguments.get("participants", [])
    model = connected.get("model")
    model_known = model and not list(references(model["config"]))
    bound = (
        (model["config"].get("_checkpoint") or model["config"])
        if model_known and model["kind"] == "model"
        else None
    )
    participants = benchmark_participants(participants, bound, connected=model is not None)
    pending = [p for p in participants if p.get("kind") == "trained" and not p.get("job")]
    if participants:
        request = Benchmark.model_validate(
            {
                **arguments,
                "participants": participants,
                "baseline": arguments.get("baseline", "")
                if arguments.get("participants")
                else "candidate",
            }
        )
        known = [p for p in participants if p not in pending]
        if request.eval_set or request.suite:
            benchmark_evaluations.prepare(project, request)
        elif known and not use_eval_set:
            qualify_participants(project, known)
        if model_known and model["kind"] == "model":
            experiment_execution.validate_native_bindings(
                None,
                "benchmark",
                {**arguments, "participants": participants},
                {"model": model["config"].get("_checkpoint") or model["config"]},
                project=project,
            )
    elif model is None:
        raise InputValidationError(f"Select a model for {node['title']}")


def expansion(document):
    count = len(document["nodes"])
    for node in document["nodes"]:
        if node["kind"] in CONTROL_SETTINGS:
            config = node["config"]
            if contains_qualification(config["_definition"]) and (
                node["kind"] == "iterate"
                and config.get("max_iterations", 1) > 1
                or node["kind"] == "map"
                and len(config["bindings"]) > config.get("concurrency", 2)
            ):
                raise InputValidationError(
                    "Place qualification after all adaptive variants or iterations; every final candidate must be materialized before selection"
                )
            repeats = (
                len(config["bindings"])
                if node["kind"] == "map"
                else config.get("max_iterations", 1)
            )
            count += repeats * expansion(config["_definition"])
    if count > 1000:
        raise InputValidationError("A run may expand to at most 1,000 node attempts")
    return count