Skip to content

The platform for continuously improving AI agents.

28.0 KB
Raw Blame
import math
from datetime import datetime, timedelta

from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.core.model_registry import openrouter_configured
from overbae.models import (
    Cell,
    EvalRun,
    FinetuningJob,
    NativeEvaluationPlan,
    TrainingCampaign,
    TrainingTrial,
)
from overbae.services import (
    benchmark_evaluations,
    context_graph,
    experiment_training,
    model_catalog,
    native_evaluation,
    provider_pricing,
    research,
    research_evidence,
    research_science,
    research_team,
)
from overbae.services.decision_providers import (
    catalog,
    openrouter_models,
    qualify_participants,
)


def candidate_identity(participant):
    return context_graph.fingerprint(
        {k: v for k, v in participant.items() if k not in {"key", "name"}}
    )


def qualification_descriptor(assignment, request, *, retained=None):
    if request.eval_set or request.suite:
        return benchmark_evaluations.qualification_descriptor(assignment, request)
    qualified = qualify_participants(
        assignment.project,
        [p.model_dump(mode="json", exclude_none=True) for p in request.participants],
    )
    cell = Cell.objects.filter(pk=request.cell, dataset__project=assignment.project).first()
    if cell is None:
        raise InputValidationError("The pinned final input is unavailable")
    developed = {}
    for previous in NativeEvaluationPlan.objects.filter(
        project=assignment.project,
        state="completed",
        config__purpose="development",
        config__research__assignment__in=[
            str(key) for key in research_evidence.investigation(assignment)
        ],
    ).order_by("created_at", "pk"):
        if previous.results.get("completion", {}).get("status") != "complete":
            continue
        configured = {candidate_identity(p) for p in previous.config.get("participants", [])}
        for participant in previous.results.get("participants", []):
            identity = candidate_identity(participant)
            candidate = (
                previous.results.get("comparisons", {})
                .get(participant["key"], {})
                .get("raw", {})
                .get("candidate", {})
            )
            cards = candidate.get("benchmarks", {})

            def finite_metric(value):
                if isinstance(value, dict):
                    return any(finite_metric(child) for child in value.values())
                return type(value) in {int, float} and math.isfinite(value)

            if (
                identity in configured
                and cards
                and candidate.get("suite_manifest_sha256")
                and candidate.get("predictions_sha256")
                and all(
                    card.get("expected", 0) > 0
                    and card.get("scored") == card["expected"]
                    and finite_metric(card.get("metrics", {}))
                    for card in cards.values()
                )
            ):
                developed[identity] = {
                    "evaluation": str(previous.pk),
                    "candidate": identity,
                    "sample_manifest": candidate["suite_manifest_sha256"],
                    "predictions": candidate["predictions_sha256"],
                    "fingerprint": context_graph.fingerprint([previous.config, previous.results]),
                }
                prediction = previous.calls.get(f"final_{participant['key']}", {})
                if prediction.get("state") == "completed":
                    developed[identity]["artifact_identity"] = prediction.get("receipt", {}).get(
                        "artifact_identity"
                    )
    candidates, evidence = [], []
    for participant in sorted(qualified, key=lambda item: item["kind"] != "trained"):
        identity = candidate_identity(participant)
        proof, checkpoint = developed.get(identity), None
        baseline_identity = None
        if participant["kind"] == "trained":
            trial = (
                TrainingTrial.objects.select_related("job", "campaign")
                .filter(job_id=participant["job"], campaign__project=assignment.project)
                .first()
            )
            selected = (
                experiment_training.selection(trial.campaign)
                if trial and trial.campaign.selected_id == trial.job_id
                else None
            )
            job = FinetuningJob.objects.filter(
                project=assignment.project, pk=participant["job"]
            ).first()
            published = experiment_training.handoff(job) if job else None
            if published and published["state"] == "ready":
                checkpoint = published["checkpoint"]["identity"]
                artifact = job.result.get("artifact_identity")
                if proof is not None and (
                    not artifact or proof.get("artifact_identity") != artifact
                ):
                    proof = None
                if (
                    selected
                    and selected["eligible"]
                    and selected["best_development_loss"] is not None
                    and not participant.get("instructions")
                    and proof is None
                ):
                    proof = {
                        "trial": str(trial.pk),
                        "checkpoint": checkpoint,
                        "fingerprint": context_graph.fingerprint(selected),
                    }
            if checkpoint is None:
                raise InputValidationError(
                    "Final trained candidates require exact eligible checkpoint evidence"
                )
        if (
            proof is None
            and participant["kind"] == "foundation"
            and participant["key"] == request.baseline
            and participant.get("job")
            and not participant.get("instructions")
        ):
            companion = next(
                (
                    candidate
                    for candidate in candidates
                    if candidate["participant"]["kind"] == "trained"
                    and candidate["participant"].get("job") == participant["job"]
                ),
                None,
            )
            if companion:
                baseline_identity = {
                    "kind": "unchanged_job_base",
                    "job": participant["job"],
                    "model": participant["model"],
                    "companion_checkpoint": companion["checkpoint"],
                    "companion_identity": companion["identity"],
                }
        if proof is None and baseline_identity is None:
            raise InputValidationError(
                "Every final candidate must have complete retained development measurements before selection"
            )
        candidate = {"participant": participant, "identity": identity, "checkpoint": checkpoint}
        if baseline_identity:
            candidate["baseline_identity"] = baseline_identity
        candidates.append(candidate)
        if proof is not None:
            evidence.append(proof)
    return {
        "candidates": candidates,
        "sealed": [{"cell": str(cell.pk), "fingerprint": cell.fingerprint}],
        "protocol": {
            "baseline": request.baseline,
            "inference": request.inference.model_dump(mode="json"),
            "bootstrap_samples": 1000,
            "seed": 73491,
            "runtime": retained["protocol"]["runtime"] if retained else native_evaluation.runtime(),
        },
        "development": evidence,
    }


def plans(assignment, *, observe=False):
    owners = [str(assignment.pk)]
    if observe:
        owners.extend(
            str(key) for key in research_evidence.flows(assignment).values_list("pk", flat=True)
        )
    return NativeEvaluationPlan.objects.filter(
        project=assignment.project, config__research__assignment__in=owners
    )


def observations(assignment, *, detail=False):
    return [
        *(describe(plan, detail=detail) for plan in plans(assignment, observe=True)),
        *benchmark_evaluations.observations(assignment),
    ]


def report_summary(results):
    return {
        "participants": [
            {
                **participant,
                "benchmarks": results.get("comparisons", {})
                .get(participant["key"], {})
                .get("raw", {})
                .get("candidate", {})
                .get("benchmarks", {}),
                "paired": results.get("comparisons", {})
                .get(participant["key"], {})
                .get("raw", {})
                .get("paired"),
                "predictions_sha256": results.get("comparisons", {})
                .get(participant["key"], {})
                .get("raw", {})
                .get("candidate", {})
                .get("predictions_sha256"),
            }
            for participant in results.get("participants", [])
        ],
        **{key: results.get(key) for key in ("completion", "limitations", "report")},
    }


CATALOG_PAGE = 40


def score_reports(plan, binding):
    reports = []
    participants = plan.results.get("participants", [])
    baseline = next(
        (item for item in participants if item["key"] == plan.config.get("baseline")), None
    )
    for participant in participants:
        modes = plan.results.get("comparisons", {}).get(participant["key"], {})
        for mode, comparison in modes.items():
            candidate = comparison.get("candidate", {})
            cards = candidate.get("benchmarks", {})
            if not cards:
                continue
            single = len(cards) == 1
            name = next(iter(cards)) if single else None
            card = (
                cards[name]
                if single
                else {
                    "benchmarks": cards,
                    "macro_across_benchmarks": candidate.get("macro_across_benchmarks", {}),
                }
            )
            paired = comparison.get("benchmarks", {}).get(name, {}) if single else {}
            paired_metrics = {}
            for benchmark, measurements in comparison.get("benchmarks", {}).items():
                for metric, values in measurements.get("metrics", {}).items():
                    path = (
                        f"/report/metrics/{metric}/mean"
                        if single
                        else f"/report/benchmarks/{benchmark}/metrics/{metric}/mean"
                    )
                    paired_metrics[path] = {
                        "difference": values.get("candidate_minus_baseline"),
                        "interval_95": values.get("interval_95"),
                        "paired_decisions": measurements.get("paired_decisions"),
                        "expected": measurements.get("expected"),
                    }
            report = {
                **binding,
                "candidate_identity": candidate_identity(participant),
                "participant": participant,
                "benchmark": name,
                "calibration": mode,
                "protocol": context_graph.fingerprint(
                    {
                        "protocol": binding["protocol"],
                        "benchmark": name,
                        "calibration": mode,
                        "scorer": comparison.get("scorer"),
                        **({"benchmarks": sorted(cards)} if not single else {}),
                    }
                ),
                "sample_manifest": candidate.get("suite_manifest_sha256"),
                "evidence": {
                    "evaluation": str(plan.pk),
                    "predictions": candidate.get("predictions_sha256"),
                    "sample_manifest": candidate.get("suite_manifest_sha256"),
                    "benchmarks": {
                        benchmark: {
                            key: value.get(key)
                            for key in (
                                "scored",
                                "expected",
                                "missing_predictions",
                                "invalid_predictions",
                            )
                        }
                        for benchmark, value in cards.items()
                    },
                },
                "paired_comparison": {
                    "baseline": candidate_identity(baseline) if baseline else None,
                    "baseline_predictions": comparison.get("baseline", {}).get(
                        "predictions_sha256"
                    ),
                    "candidate_predictions": candidate.get("predictions_sha256"),
                    "sample_manifest": candidate.get("suite_manifest_sha256"),
                    "paired_sha256": comparison.get("paired_sha256"),
                    "paired_decisions": paired.get("paired_decisions"),
                    "expected": paired.get("expected"),
                    "metrics": paired_metrics,
                },
                "report": {
                    **card,
                    "completion": plan.results.get("completion", {}),
                    "predictions_sha256": candidate.get("predictions_sha256"),
                },
            }
            reports.append({**report, "fingerprint": context_graph.fingerprint(report)})
    return reports


def compact_costs(costs):
    if isinstance(costs, dict):
        return {key: compact_costs(value) for key, value in costs.items() if key != "rate_card"}
    if isinstance(costs, list):
        return [compact_costs(value) for value in costs]
    return costs


def describe(plan, *, detail=True):
    return {
        "id": str(plan.pk),
        "state": plan.state,
        "phase": plan.config.get("purpose", "final"),
        "cell": str(plan.final_cell_id),
        "participants": plan.config["participants"],
        "baseline": plan.config["baseline"],
        "protocol": plan.config.get("protocol"),
        "generation": plan.config.get("generation"),
        "inference": plan.config.get("inference"),
        "suites": plan.config.get("suites"),
        "results": plan.results if detail else report_summary(plan.results),
        "costs": native_evaluation.cost_record(plan)
        if detail
        else compact_costs(native_evaluation.cost_record(plan)),
        "error": plan.error,
        "stages": {
            key: {k: value.get(k) for k in ("state", "error", "id")}
            for key, value in plan.calls.items()
        },
    }


def active(plan):
    return (
        plan.state not in {"completed", "failed", "paused", "cancelled"}
        or any(
            call.get("lease")
            or call.get("state") in {"submitting", "running", "submission_unknown"}
            for call in plan.calls.values()
        )
        or plan.requests.filter(state__in=["submitting", "running", "submission_unknown"]).exists()
    )


def pending(assignment):
    return benchmark_evaluations.active(assignment).exists() or any(
        active(plan) for plan in plans(assignment)
    )


def reconcile(assignment, *, cancelling=False):
    if cancelling or assignment.deadline <= timezone.now():
        benchmark_evaluations.cancel(assignment)
    for plan in plans(assignment):
        expired = datetime.fromisoformat(plan.config["research"]["deadline"]) <= timezone.now()
        if active(plan) and (cancelling or expired):
            native_evaluation.request_cancel(plan, user=assignment.created_by)


def compute_allowance(limits, *, gpu_type, gpu_count, cpu_count=8, memory_gib=32):
    card = provider_pricing.current_rates()
    gpu = provider_pricing.gpu_rate(card, gpu_type)
    cpu, memory = (
        card["rates"].get(key) for key in ("cpu_hour_cost_sandbox", "mem_gib_hour_cost_sandbox")
    )
    if any(
        type(rate) not in {float, int} or not math.isfinite(rate) or rate <= 0
        for rate in (gpu, cpu, memory)
    ):
        raise InputValidationError(
            "Current GPU, CPU and memory rates are required before benchmark admission"
        )
    # Reserve 20% for unmetered provider overhead; this is not an actual bill.
    per_second = gpu * gpu_count + (cpu_count * cpu + memory_gib * memory) / 3600
    duration = limits["max_seconds"]
    if limits.get("max_cost_usd") is not None:
        duration = min(duration, int(limits["max_cost_usd"] * 0.8 / per_second))
    if duration < 60:
        raise InputValidationError("The execution budget does not cover a one-minute compute lease")
    return {
        "seconds": duration,
        "rate_card": card,
        "compute_usd_per_second": per_second,
        "basis": "reserved GPU/CPU/memory estimate; excludes storage and provider adjustments",
    }


def owned_campaigns(assignment):
    return TrainingCampaign.objects.filter(project=assignment.project).filter(
        Q(pk__in=experiment_training.campaigns(research_evidence.owners(assignment)).values("pk"))
        | Q(pk__in=research_evidence.campaigns(assignment).values("pk"))
    )


def admitted_jobs(assignment):
    return {
        str(job.pk)
        for job in FinetuningJob.objects.filter(project=assignment.project).prefetch_related(
            "retained_checkpoints"
        )
        if experiment_training.handoff(job)["state"] == "ready"
    }


def invoke(action, request):
    agent, assignment = action.agent, action.agent.assignment
    if request.operation == "catalog":
        jobs = admitted_jobs(assignment)
        checkpoints = [
            {
                "job": option["id"],
                "name": option["name"],
                "model": option["model"],
                "admission": "eligible"
                if option["id"] in jobs
                else "requires_verified_published_checkpoint",
                "qualification": option["qualification"],
                "participant": {
                    "key": "candidate",
                    "name": option["name"] or option["model"],
                    "kind": "trained",
                    "job": option["id"],
                },
            }
            for option in catalog(assignment.project)
            if option["kind"] == "trained"
        ]
        wanted = request.search.strip().lower()
        eval_set_comparison = bool(request.eval_set or request.suite)
        catalogue = (
            model_catalog.fetch_model_catalog()[0] if eval_set_comparison else openrouter_models()
        )
        models = [
            {
                "model": model["id"],
                "name": model["name"],
                "kind": "external",
                "probabilities": "answer_token"
                if not eval_set_comparison or "logprobs" in model["supported_parameters"]
                else None,
                "context_length": model["context_length"],
                "usd_per_million_tokens": {
                    "prompt": model["prompt_price"],
                    "completion": model["completion_price"],
                },
            }
            for model in catalogue
        ]
        models = [
            model
            for model in models
            if wanted in model["model"].lower() or wanted in model["name"].lower()
        ]
        page = slice(request.offset, request.offset + CATALOG_PAGE)
        return {
            "provider": "OpenRouter",
            "provider_configured": openrouter_configured(),
            "models": models[page],
            "models_total": len(models),
            "checkpoints": checkpoints[page],
            "checkpoints_total": len(checkpoints),
            "next_offset": request.offset + CATALOG_PAGE
            if max(len(models), len(checkpoints)) > request.offset + CATALOG_PAGE
            else None,
            "participant_contract": (
                "Participants are OpenRouter models (kind=external, model=<id>) and this "
                "project's trained checkpoints (kind=trained, job=<id>). Eval-set comparisons "
                "use chat models and the selected set's scoring criteria."
                if eval_set_comparison
                else "Participants are OpenRouter models (kind=external, model=<id>) and this "
                "project's trained checkpoints (kind=trained, job=<id>). Only OpenRouter models "
                "that report token probabilities are listed, because decisions are scored by "
                "accuracy and cross-entropy. Training catalogue models are not participants."
            ),
        }
    participants = [p.model_dump(mode="json", exclude_none=True) for p in request.participants]
    owned = plans(assignment)
    if request.operation == "inspect":
        if not request.evaluation:
            return research_evidence.visible(
                assignment, observations(assignment, detail=request.detail)
            )
        cohort = list(
            benchmark_evaluations.records(assignment, observe=True).filter(group=request.evaluation)
        )
        if cohort:
            return benchmark_evaluations.describe(cohort)
        plan = NativeEvaluationPlan.objects.filter(
            pk=request.evaluation,
            project=assignment.project,
        ).first()
        if plan is None:
            raise InputValidationError("The requested benchmark is unavailable in this project")
        return research_evidence.visible(assignment, [describe(plan, detail=request.detail)])
    if agent.parent_id:
        raise InputValidationError("Only the research owner may launch or stop benchmarks")
    if request.operation == "stop":
        cohort = list(benchmark_evaluations.records(assignment).filter(group=request.evaluation))
        if cohort:
            benchmark_evaluations.cancel(assignment, group=request.evaluation)
            return benchmark_evaluations.describe(
                list(benchmark_evaluations.records(assignment).filter(group=request.evaluation))
            )
        plan = owned.filter(pk=request.evaluation).first()
        if plan is None:
            raise InputValidationError("Select an evaluation owned by this assignment")
        research_team.current_turn(agent)
        native_evaluation.request_cancel(plan, user=assignment.created_by)
        return describe(plan)
    return create(action, request, participants)


@transaction.atomic
def create(action, request, participants):
    # Research tools own source admission and import this native service for dispatch.
    from overbae.services.research_tools import experiment_partitions, source_cell

    agent, assignment = action.agent, action.agent.assignment
    research_science.experiment_for(assignment, lock=True)
    assignment = research_team.current_turn(agent).assignment
    owned = plans(assignment)
    prior = owned.filter(request_key=f"research:{action.pk}").first()
    if prior:
        return describe(prior)
    cohort = list(benchmark_evaluations.records(assignment).filter(group=action.pk))
    if cohort:
        return benchmark_evaluations.describe(cohort)
    research_team.admit_mutation(agent)
    if assignment.result.get("selection_locked") and request.phase == "development":
        raise InputValidationError("Development is closed after final selection")
    if not participants:
        raise InputValidationError("Choose OpenRouter models or verified trained checkpoints")
    using_eval_set = bool(request.eval_set or request.suite)
    if (
        not using_eval_set
        and any(p.get("kind") == "external" for p in participants)
        and not openrouter_configured()
    ):
        raise InputValidationError(
            "OpenRouter is not configured on this deployment, so its models cannot run. "
            "Tell the user; do not substitute another model."
        )
    jobs = {p["job"] for p in participants if p.get("job")}
    if not using_eval_set and jobs and not jobs <= admitted_jobs(assignment):
        raise InputValidationError(
            "Job participants require a succeeded, reload-verified published checkpoint in this project"
        )
    if request.phase == "development":
        cell = source_cell(assignment, request.cell)
    else:
        # A later run of the experiment compares the models an earlier run trained, on the
        # final split an earlier run made.
        partitions = experiment_partitions(assignment)
        finals = {
            str(c)
            for c in partitions.filter(members__role="final").values_list(
                "members__cell_id", flat=True
            )
        } | set(assignment.specification.get("sealed_cells", []))
        if str(request.cell) not in finals or request.cell is None:
            raise InputValidationError(
                "Final comparison requires a sealed final cell from this experiment: a "
                "partition's final member or an admitted sealed cell"
            )
        owners = [str(key) for key in research_evidence.investigation(assignment)]
        if (
            NativeEvaluationPlan.objects.filter(
                project=assignment.project,
                config__research__assignment__in=owners,
                final_cell_id=request.cell,
            )
            .exclude(config__purpose="development", config__purpose__isnull=False)
            .exists()
            or EvalRun.objects.filter(
                project=assignment.project,
                params__benchmark_assignment__in=owners,
                params__benchmark_phase="final",
                cell_id=request.cell,
            ).exists()
        ):
            raise InputValidationError("This sealed comparison has already been admitted")
        cell = source_cell(assignment, request.cell, platform_reads=True)
        descriptor = qualification_descriptor(
            assignment,
            request,
            retained=research_science.retained_qualification(assignment, action),
        )
        research_science.freeze(assignment, action=action, **descriptor)
    if using_eval_set:
        return benchmark_evaluations.start(action, request, cell)
    remaining = int((assignment.deadline - timezone.now()).total_seconds())
    if remaining < 180:
        raise InputValidationError("The assignment has insufficient time for a native benchmark")
    requested_seconds = request.max_seconds
    request = request.model_copy(update={"max_seconds": min(request.max_seconds, remaining)})
    allocation = research.claim(
        agent,
        f"benchmark:{action.pk}",
        "benchmark_allocation",
        request.model_dump(mode="json"),
    )
    if allocation.state == "denied":
        raise InputValidationError(allocation.result["error"])
    plan = native_evaluation.create_plan(
        assignment.project,
        name=request.name,
        request_key=f"research:{action.pk}",
        final_cell=cell,
        participants=participants,
        baseline=request.baseline,
        inference=request.inference.model_dump(),
        purpose=request.phase,
        pinned_runtime=descriptor["protocol"]["runtime"] if request.phase == "final" else None,
        triggered_by=assignment.created_by,
    )
    leases = {
        stage: compute_allowance(
            {"max_seconds": seconds, "max_cost_usd": None},
            gpu_type="H100",
            gpu_count=gpus,
        )
        for stage, seconds, gpus in (
            ("prepare", min(300, request.max_seconds // 3), 0),
            ("predict", request.max_seconds * 2 // 3, 1),
        )
    }
    stages = {
        "prepare": len(native_evaluation.preparation_groups(plan)),
        "predict": sum(p["kind"] != "external" for p in plan.config["participants"]),
    }
    allocation.reservation_usd = research.number(
        sum(
            lease["seconds"] * lease["compute_usd_per_second"] * stages[stage]
            for stage, lease in leases.items()
        )
    )
    allocation.save(update_fields=["reservation_usd"])
    plan.config = {
        **plan.config,
        "resource_leases": leases,
        "research": {
            "assignment": str(assignment.pk),
            "allocation": str(allocation.pk),
            "deadline": min(
                assignment.deadline, timezone.now() + timedelta(seconds=request.max_seconds)
            ).isoformat(),
            "requested_seconds": requested_seconds,
            "admitted_seconds": request.max_seconds,
        },
    }
    plan.save(update_fields=["config"])
    native_evaluation.launch(plan, user=assignment.created_by)
    research.complete(allocation, {"evaluation": str(plan.pk)})
    return describe(plan)