Skip to content

The platform for continuously improving AI agents.

4.4 KB
Raw Blame
"""The one bridge from research and flow code to training. A research agent or a train node
trains through a training campaign (services/training_campaigns): it starts under the request
key ``research:{assignment}:{action}``, so an assignment's campaigns are found by that prefix,
and this module turns the campaign's records into the evidence experiments read."""

from django.db.models import Q

from overbae.models import FinetuningJob, TrainingCampaign
from overbae.services import training_campaigns

PREFIX = "research:"
# A model is ready to hand on once its run succeeded.
TRAINED = (FinetuningJob.Status.SUCCEEDED, FinetuningJob.Status.DEPLOYING)


def request_key(assignment, action):
    return f"{PREFIX}{assignment.pk}:{action.pk}"


def campaigns(assignments):
    """The campaigns these research assignments started."""
    owners = [str(getattr(item, "pk", item)) for item in assignments]
    if not owners:
        return TrainingCampaign.objects.none()
    query = Q()
    for owner in owners:
        query |= Q(request_key__startswith=f"{PREFIX}{owner}:")
    return TrainingCampaign.objects.filter(query)


def start(action, arguments, *, max_trials):
    """Start the action's campaign; a retry of the same action returns the same campaign."""
    assignment = action.agent.assignment
    return training_campaigns.start(
        assignment.project,
        assignment.created_by,
        arguments=arguments,
        max_trials=max_trials,
        request_key=request_key(assignment, action),
    )


def describe(campaign):
    return training_campaigns.describe(campaign)


def stop(campaign):
    return training_campaigns.cancel(campaign)


def pending(assignments):
    return campaigns(assignments).filter(state=TrainingCampaign.State.RUNNING).exists()


def checkpoint(job):
    """The checkpoint a run hands on: the one its monitoring selected, else its newest."""
    available = job.retained_checkpoints.filter(state="available")
    found = available.filter(selected=True).first() or (
        available.order_by("-attempt", "-step", "-created_at").first()
    )
    if found is None:
        return None
    return {
        "identity": found.identity,
        "step": found.step,
        "attempt": found.attempt,
        "selected": found.selected,
        "metrics": found.metrics,
    }


def development(job):
    """The run's completed development checks, oldest first."""
    return list(
        job.validation_runs.filter(state="completed", stream="development")
        .order_by("attempt", "step")
        .values("id", "attempt", "step", "metrics", "observed_at")
    )


def handoff(job):
    """Whether a run's model is ready for prediction, evaluation or serving, and why not."""
    if job.status in {FinetuningJob.Status.FAILED, FinetuningJob.Status.CANCELLED}:
        return {"state": job.status, "reason": job.error_message or f"The run {job.status}"}
    if job.status not in TRAINED:
        return {"state": "waiting", "reason": f"The run is {job.status}"}
    found = checkpoint(job)
    if found is None:
        return {"state": "unavailable", "reason": "The run retained no checkpoint"}
    return {"state": "ready", "checkpoint": found}


def selection(campaign):
    """The campaign's kept run, with its measured development loss and checkpoint. Missing
    measurements stay missing."""
    campaign.refresh_from_db()
    if campaign.selected_id is None:
        return {
            "state": campaign.state,
            "eligible": False,
            "reason": campaign.summary or "No run has been kept yet",
        }
    job = campaign.selected
    ready = handoff(job)
    return {
        "state": campaign.state,
        "eligible": ready["state"] == "ready",
        "job": str(job.pk),
        "model": job.base_model,
        "best_development_loss": training_campaigns.outcome(job),
        **({"checkpoint": ready["checkpoint"]} if ready["state"] == "ready" else {}),
        **({"reason": ready["reason"]} if ready["state"] != "ready" else {}),
    }


def model_output(campaign):
    """The model a completed campaign hands to the next node, or None until it has one."""
    chosen = selection(campaign)
    if not chosen["eligible"]:
        return None
    return {
        "kind": "model",
        "model": chosen["model"],
        "job": chosen["job"],
        "campaign": str(campaign.pk),
        "fingerprint": chosen["checkpoint"]["identity"],
        "checkpoint": chosen["checkpoint"],
    }