Skip to content

The platform for continuously improving AI agents.

25.9 KB
Raw Blame
import json
import math
from concurrent.futures import ThreadPoolExecutor, as_completed

from django.db import transaction
from django.db.models import Count
from django.utils import timezone
from pydantic import ValidationError

from modal_shared.decision_inference import input_digest
from modal_shared.decisions import DECISION_OBJECTIVES, decision_request
from modal_shared.serving.artifacts import atomic_json
from modal_shared.stacks import NATIVE_FOUNDATION_STACKS
from overbae.core import decisions
from overbae.core.errors import InputValidationError
from overbae.core.model_registry import decision_models
from overbae.modal.model_registry import (
    get_hf_base,
    get_model_config_any_backend,
    get_unsloth_image,
)
from overbae.models import BillingService, DecisionProviderRequest, FinetuningJob
from overbae.services import billing_ledger, evaluation_inputs, model_catalog, model_meter
from overbae.services.evaluation_contract import MAX_EVALUATION_PARTICIPANTS, PromptParticipant


class SubmissionUnknownError(RuntimeError):
    pass


class RetryableEvaluationError(RuntimeError):
    pass


def recover_request(record):
    if record.state in {"submitting", "submission_unknown"} and record.response is not None:
        record.state, record.error = "received", ""
        record.save()
    elif (
        record.state == "submission_unknown"
        and record.attempts
        and record.attempts[-1].get("error") in {"capacity_timeout", "capacity_unavailable"}
    ):
        # Only a completed transport attempt can be repeated. A bare submission
        # intent may still have a live owner and is not evidence of a timeout.
        record.state = "retryable" if len(record.attempts) < 3 else "failed"
        record.save()


# Option labels must each be one token, and a provider returns at most 20 alternatives.
OPTION_LABELS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
TOP_LOGPROBS = 20


def openrouter_models():
    """OpenRouter chat models that report per-token probabilities, which decision scoring needs."""
    models, _ = model_catalog.fetch_model_catalog()
    return [
        model
        for model in models
        if {"logprobs", "top_logprobs"} <= set(model["supported_parameters"])
    ]


def catalog(project):
    options = [
        {
            "id": model["id"],
            "name": model["name"],
            "kind": "external",
            "qualification": "catalog_eligible",
        }
        for model in openrouter_models()
    ]
    for job in FinetuningJob.objects.filter(project=project, status="succeeded").order_by(
        "-created_at", "-pk"
    ):
        if (job.hyperparameters or {}).get("objective") in DECISION_OBJECTIVES:
            options.append(
                {
                    "id": str(job.pk),
                    "name": job.name,
                    "kind": "trained",
                    "model": job.base_model,
                    "qualification": "checkpoint_available",
                }
            )
    return options


def qualify_participants(project, selected):
    if not isinstance(selected, list) or not 1 <= len(selected) <= MAX_EVALUATION_PARTICIPANTS:
        raise InputValidationError(f"Choose 1 to {MAX_EVALUATION_PARTICIPANTS} model participants")
    result = []
    seen = set()
    for participant in selected:
        try:
            participant = PromptParticipant.model_validate(participant).model_dump(
                mode="json", exclude_none=True
            )
        except ValidationError as exc:
            raise InputValidationError(str(exc)) from None
        key = participant["key"]
        if key in seen:
            raise InputValidationError("Participant keys must be distinct")
        seen.add(key)
        name = participant.get("name")
        kind = participant.get("kind")
        reference = {"key": key, "name": name, "kind": kind}
        instructions = participant.get("instructions", "")
        if instructions:
            if kind == "external":
                raise InputValidationError("Prompt variants require native decision participants")
            reference["instructions"] = instructions
        if kind == "external":
            model = participant.get("model")
            served = participant.get("served_model", "")
            chat = model not in {item.slug for item in decision_models()}
            if (
                participant.get("job")
                or (chat and model not in {item["id"] for item in openrouter_models()})
                or not isinstance(served, str)
                or (served and served != model and not served.startswith(model + "-"))
            ):
                raise InputValidationError(
                    "An external participant requires an OpenRouter model from the benchmark "
                    "catalogue and a compatible served version"
                )
            reference.update(model=model, served_model=served)
            if chat:
                reference["adapter"] = "chat"
        elif participant.get("job"):
            job = FinetuningJob.objects.filter(pk=participant["job"], project=project).first()
            if (
                job is None
                or (job.hyperparameters or {}).get("objective") not in DECISION_OBJECTIVES
            ):
                raise InputValidationError("Select a native decision training job in this project")
            if participant.get("model") not in {None, job.base_model} or participant.get(
                "served_model"
            ):
                raise InputValidationError(
                    "A trained reference gets its model identity from the saved job"
                )
            reference.update(job=str(job.pk), model=job.base_model)
        elif kind == "foundation":
            model = participant.get("model")
            if (
                not model
                or get_model_config_any_backend(model) is None
                or get_unsloth_image(model) not in NATIVE_FOUNDATION_STACKS
            ):
                raise InputValidationError(
                    "This foundation has no supported native evaluation runtime"
                )
            reference.update(model=model, hf_model=get_hf_base(model, backend="modal"))
        else:
            raise InputValidationError("A trained participant requires a job")
        result.append(reference)
    return result


def question(request, instructions=""):
    decision_request(request)
    kind, options = request["kind"], request["options"]
    text = f"{instructions}\n\n{request['question']}" if instructions else request["question"]
    result = {"type": kind, "instructions": text}
    if kind == "score":
        if len(options) > 10:
            raise InputValidationError(
                "This provider supports score decisions with at most ten options"
            )
        result["criteria"] = options
    elif kind == "noul":
        result["criteria"] = {"false": options[0], "true": options[1]}
    else:
        result["criteria"] = {str(i): value for i, value in enumerate(options)}
    return result


def chat_request(model, request):
    decision_request(request)
    options = request["options"]
    if len(options) > len(OPTION_LABELS):
        raise ValueError(
            f"An OpenRouter chat model answers decisions with at most {len(OPTION_LABELS)} options"
        )
    listing = "\n".join(f"{OPTION_LABELS[i]}. {option}" for i, option in enumerate(options))
    return {
        "model": model,
        "messages": [
            {
                "role": "system",
                "content": "Answer the question about the supplied state. Reply with the "
                "letter of exactly one option and nothing else.",
            },
            {
                "role": "user",
                "content": f"State:\n{request['state']}\n\nQuestion:\n{request['question']}"
                f"\n\nOptions:\n{listing}",
            },
        ],
        "max_tokens": 1,
        "temperature": 0,
        "logprobs": True,
        "top_logprobs": TOP_LOGPROBS,
        "usage": {"include": True},
    }


def interpret_chat(request, payload, participant):
    expected = participant.get("served_model")
    served = payload.get("model")
    if (
        not isinstance(served, str)
        or (expected and served != expected)
        or (
            not expected
            and served != participant["model"]
            and not served.startswith(participant["model"] + "-")
        )
    ):
        raise InputValidationError("The provider served a different model identity")
    try:
        alternatives = payload["choices"][0]["logprobs"]["content"][0]["top_logprobs"]
        tokens = [(item["token"], float(item["logprob"])) for item in alternatives]
    except (KeyError, IndexError, TypeError, ValueError):
        raise InputValidationError("The provider returned no token probabilities") from None
    n = len(request["options"])
    observed, listed = {}, 0.0
    for token, logprob in tokens:
        if not math.isfinite(logprob) or logprob > 1e-6:
            raise InputValidationError("Provider token probabilities are invalid")
        mass = math.exp(min(logprob, 0.0))
        listed += mass
        label = token.strip()
        index = OPTION_LABELS.find(label) if len(label) == 1 else -1
        if 0 <= index < n:
            observed[index] = observed.get(index, 0.0) + mass
    if not observed:
        raise InputValidationError("No option label is among the returned tokens")
    # An option absent from the listed alternatives holds at most the unlisted mass.
    unobserved = n - len(observed)
    share = max(0.0, 1 - listed) / unobserved if unobserved else 0.0
    raw = [observed.get(i, share) for i in range(n)]
    total = math.fsum(raw)
    p = [v / total for v in raw]
    return {
        "input_sha256": input_digest(request),
        "kind": request["kind"],
        "model_identity": served,
        "probabilities": p,
        "log_probabilities": [math.log(max(v, 1e-12)) for v in p],
        "provider_response_id": payload.get("id"),
    }, {
        "served_identity": served,
        "identity_evidence": "provider_reported_alias"
        if served == participant["model"]
        else "provider_reported_version",
        "identity_limit": "Provider identity is recorded, not independently verified against weights",
        "probability_basis": "first answer token log-probabilities over option letters",
        "option_token_mass": math.fsum(observed.values()),
        "listed_token_mass": listed,
        "unobserved_options": unobserved,
        "logarithm_floor": 1e-12,
    }


def interpret_response(request, payload, participant):
    expected = participant.get("served_model")
    served = payload.get("model")
    if (
        not isinstance(served, str)
        or (expected and served != expected)
        or (
            not expected
            and served != participant["model"]
            and not served.startswith(participant["model"] + "-")
        )
    ):
        raise InputValidationError("The provider served a different model identity")
    if payload.get("provider") != "TypeSafe" or set(payload.get("answers", {})) != {"decision"}:
        raise InputValidationError("Provider or answer coverage differs from the request")
    answer = payload["answers"]["decision"]
    kind, options = request["kind"], request["options"]
    n = len(options)
    if answer.get("type") != kind:
        raise InputValidationError("Provider changed the decision kind")
    if kind == "noul":
        value = answer.get("noul")
        if type(value) not in {int, float}:
            raise InputValidationError("Invalid binary probability")
        probabilities = [1 - value, value]
    else:
        raw = answer.get("probabilities")
        if not isinstance(raw, dict) or set(raw) != {str(i) for i in range(n)}:
            raise InputValidationError("Provider probability vector is incomplete")
        probabilities = [raw[str(i)] for i in range(n)]
        if kind == "score" and answer.get("legend") != {
            str(i): option for i, option in enumerate(options)
        }:
            raise InputValidationError("Provider score option order changed")
    if any(
        type(v) not in {int, float} or not math.isfinite(v) or not 0 <= v <= 1
        for v in probabilities
    ):
        raise InputValidationError("Provider probability values are invalid")
    total = math.fsum(probabilities)
    digits = next(
        (d for d in range(2, 13) if all(abs(v - round(v, d)) <= 1e-12 for v in probabilities)), 15
    )
    radius = 0.5 * 10**-digits
    lower = math.fsum(max(0, v - radius) for v in probabilities)
    upper = math.fsum(min(1, v + radius) for v in probabilities)
    if total <= 0 or not (abs(total - 1) <= 1e-6 or lower - 1e-8 <= 1 <= upper + 1e-8):
        raise InputValidationError("Probability mass cannot be explained by output rounding")
    p = [v / total for v in probabilities]
    diagnostic = {
        "served_identity": served,
        "identity_evidence": "provider_reported_alias"
        if served == participant["model"]
        else "provider_reported_version",
        "identity_limit": "Provider identity is recorded, not independently verified against weights",
        "original_probabilities": probabilities,
        "original_probability_sum": total,
        "response_decimal_precision": digits,
        "logarithm_floor": 1e-12,
    }
    if kind == "choice":
        selected = str(answer.get("choice"))
        maximum = max(range(n), key=p.__getitem__)
        diagnostic.update(
            provider_reported_choice=selected,
            probability_argmax_index=maximum,
            provider_choice_matches_common_tie_break=selected == str(maximum),
        )
    if kind == "score":
        point = answer.get("score")
        estimate = math.fsum(i * v for i, v in enumerate(p))
        diagnostic.update(
            provider_reported_score=point,
            probability_derived_score=estimate,
            provider_score_difference=point - estimate
            if type(point) in {float, int} and math.isfinite(point)
            else None,
        )
    return {
        "input_sha256": input_digest(request),
        "kind": kind,
        "model_identity": served,
        "probabilities": p,
        "log_probabilities": [math.log(max(v, 1e-12)) for v in p],
        "provider_response_id": payload.get("id"),
    }, diagnostic


def complete_response(record, request, participant):
    interpret = interpret_chat if participant.get("adapter") == "chat" else interpret_response
    vector, diagnostics = interpret(request, record.response, participant)
    record.prediction, record.diagnostics, record.state, record.error = (
        vector,
        diagnostics,
        "completed",
        "",
    )
    record.save()


def usage(plan, participant, role):
    entries = DecisionProviderRequest.objects.filter(plan=plan, participant=participant, role=role)
    counts = dict(entries.values("state").annotate(count=Count("id")).values_list("state", "count"))
    measured = 0.0
    unknown = 0
    tokens = 0
    for entry in entries.only("usage", "attempts").iterator():
        attempts = entry.attempts or [{"usage": entry.usage}]
        for attempt in attempts:
            stats = attempt.get("usage") or {}
            cost = stats.get("response_cost")
            measured += cost or 0
            unknown += cost is None
            pair = (stats.get("prompt_tokens"), stats.get("completion_tokens"))
            # One attempt without a reported count makes the total unknown, not smaller.
            tokens = None if tokens is None or None in pair else tokens + sum(pair)
    return {
        "requests": counts,
        "recorded_cost_usd": measured,
        "unknown_cost_attempts": unknown,
        "tokens": tokens,
        "cost_basis": "provider_reported_api_usage",
    }


def external_step(plan, role, participant):
    # Suite sealing shares the evaluator's local reference store; requests never receive it.
    # Evaluation imports this adapter; load its suite writer after module initialization.
    from overbae.services.native_evaluation import (
        NativeSubmissionRejectedError,
        directory,
        request_cancel,
        require_execution_authority,
        seal_suite,
    )

    participant = dict(participant)
    chat = participant.get("adapter") == "chat"
    previous = (
        DecisionProviderRequest.objects.filter(
            plan=plan, participant=participant["key"], state="completed", response__isnull=False
        )
        .order_by("created_at")
        .first()
    )
    if previous is not None:
        served = previous.response["model"]
        if participant.get("served_model") and participant["served_model"] != served:
            raise InputValidationError(
                "Saved provider identity differs from the requested snapshot"
            )
        participant["served_model"] = served
    source = directory(plan, role) / "inputs.jsonl"
    if not (source.parent / "chunks" / "index.json").exists():
        source = seal_suite(plan, role)
    progress = source.parent / f"{participant['key']}-progress.json"
    offset = json.loads(progress.read_text())["rows"] if progress.exists() else 0
    # Qualify one response before sending concurrent requests to a resolved snapshot.
    limit = 128 if participant.get("served_model") else 1
    chunk, total_rows = evaluation_inputs.read_from(source, offset, limit)
    pending = {}
    for row in chunk:
        record, _ = DecisionProviderRequest.objects.get_or_create(
            plan=plan, participant=participant["key"], role=role, input_sha256=row["input_sha256"]
        )
        recover_request(record)
        if record.state == "submitting" or record.state == "submission_unknown":
            record.state = "submission_unknown"
            record.error = "Provider acknowledgement is unresolved; request was not replayed."
            record.save()
            continue
        if record.state == "received":
            complete_response(record, row["decision"], participant)
        elif record.state not in {"completed", "failed", "incompatible"}:
            try:
                if chat:
                    chat_request(participant["model"], row["decision"])
                else:
                    question(row["decision"])
            except ValueError as exc:
                record.state, record.error = "incompatible", str(exc)
                record.save()
                continue
            pending[record.pk] = (record, row["decision"])
    found = billing_ledger.cause(
        plan.project_id,
        BillingService.EVALUATION,
        "native_evaluation",
        plan.pk,
        actor=plan.triggered_by_id,
    )
    with ThreadPoolExecutor(max_workers=plan.config["inference"]["concurrency"]) as executor:
        futures, errors = {}, []
        queue = iter(pending.values())
        admission_ended = False

        def dispatch_next():
            nonlocal admission_ended
            if admission_ended:
                return False
            try:
                record, request = next(queue)
            except StopIteration:
                return False
            try:
                require_execution_authority(plan)
            except NativeSubmissionRejectedError as exc:
                admission_ended = True
                errors.append(exc)
                request_cancel(plan)
                return False
            with transaction.atomic():
                locked = DecisionProviderRequest.objects.select_for_update().get(pk=record.pk)
                if locked.state not in {"pending", "retryable"}:
                    raise SubmissionUnknownError("External request was claimed by another observer")
                locked.state = "submitting"
                locked.attempts = [
                    *locked.attempts,
                    {"intent_at": timezone.now().isoformat(), "usage": {"response_cost": None}},
                ]
                locked.save()
            record.refresh_from_db()
            model = participant.get("served_model") or participant["model"]
            if chat:
                # OpenRouter routes by catalogue id; the dated identity is what it reports back.
                submission = executor.submit(
                    model_meter.carried(decisions.request_once, found),
                    chat_request(participant["model"], request),
                    endpoint="chat/completions",
                )
            else:
                submission = executor.submit(
                    model_meter.carried(decisions.request_once, found),
                    {
                        "model": model,
                        "state": request["state"],
                        "questions": {
                            "decision": question(request, participant.get("instructions", ""))
                        },
                    },
                )
            futures[submission] = (record, request)
            return True

        for _ in range(plan.config["inference"]["concurrency"]):
            if not dispatch_next():
                break
        while futures:
            future = next(as_completed(futures))
            record, request = futures.pop(future)
            try:
                payload, stats = future.result()
                record.response, record.usage, record.state = payload, stats, "received"
                record.attempts[-1].update(
                    response_id=payload.get("id"),
                    usage=stats,
                    received_at=timezone.now().isoformat(),
                    outcome="received",
                )
                record.save()
                complete_response(record, request, participant)
            except decisions.DecisionError as exc:
                code = exc.stats.get("status_code")
                retryable = exc.reason != "submission_unknown" and (
                    code == 429
                    or (isinstance(code, int) and 500 <= code < 600)
                    or exc.reason in {"capacity_timeout", "capacity_unavailable"}
                )
                record.attempts[-1].update(
                    error=exc.reason,
                    usage=exc.stats,
                    outcome="submission_unknown"
                    if exc.reason == "submission_unknown"
                    else "failed",
                    finished_at=timezone.now().isoformat(),
                )
                record.state = (
                    "submission_unknown"
                    if exc.reason == "submission_unknown"
                    else "retryable"
                    if retryable and len(record.attempts) < 3
                    else "failed"
                    if retryable
                    or code
                    or exc.reason
                    in {
                        "not_configured",
                        "capacity_configuration",
                        "invalid_state",
                        "invalid_response",
                    }
                    else "submission_unknown"
                )
                record.error = exc.reason
                record.save()
                if record.state == "retryable":
                    errors.append(RetryableEvaluationError(exc.reason))
            except Exception as exc:
                record.state = "failed" if record.response is not None else "submission_unknown"
                record.error = str(exc)[:1000]
                record.save()
            dispatch_next()
        if errors:
            raise errors[0]
    unresolved = (
        DecisionProviderRequest.objects.filter(pk__in=pending)
        .exclude(state__in=["completed", "incompatible", "failed", "submission_unknown"])
        .exists()
    )
    if not unresolved:
        atomic_json(progress, {"rows": offset + len(chunk)})
    completed = offset + len(chunk) == total_rows and not unresolved
    if completed:
        output_path = source.parent / f"{participant['key']}.jsonl"
        failures_path = output_path.with_suffix(".failures.jsonl")
        with (
            evaluation_inputs.replacing(output_path) as written,
            evaluation_inputs.replacing(failures_path) as failed,
            written.open("w") as output,
            failed.open("w") as failures,
        ):
            for batch in evaluation_inputs.batches(source):
                saved = {
                    record.input_sha256: record
                    for record in DecisionProviderRequest.objects.filter(
                        plan=plan,
                        participant=participant["key"],
                        role=role,
                        input_sha256__in=[r["input_sha256"] for r in batch],
                    )
                }
                for row in batch:
                    record = saved.get(row["input_sha256"])
                    if record and record.state == "completed":
                        output.write(json.dumps({**record.prediction, "key": row["key"]}) + "\n")
                    elif record and record.state == "incompatible":
                        failures.write(
                            json.dumps(
                                {
                                    "key": row["key"],
                                    "input_sha256": row["input_sha256"],
                                    "reason": record.error,
                                }
                            )
                            + "\n"
                        )
                    elif not record or record.state not in {"failed", "submission_unknown"}:
                        raise InputValidationError("Provider collection is incomplete")
    return {
        "completed": completed,
        "decisions": offset + len(chunk),
        "served_model": participant.get("served_model"),
        "identity_basis": "provider_reported",
        "issues": list(
            DecisionProviderRequest.objects.filter(
                plan=plan,
                participant=participant["key"],
                role=role,
                state__in=["failed", "submission_unknown"],
            )
            .values("error")
            .annotate(requests=Count("id"))
        )
        if completed
        else [],
        **(
            usage(plan, participant["key"], role)
            if completed
            else {"cost_basis": "request_ledger_pending_final_aggregation"}
        ),
    }