Skip to content

The platform for continuously improving AI agents.

11.4 KB
Raw Blame
import json
import time
from unittest.mock import patch

import pytest
from factories import make_user

from modal_shared import training_control
from modal_shared.container_meter import STORE as METER_STORE
from overbae.core.errors import InputValidationError
from overbae.models import (
    Dataset,
    FinetuningJob,
    Project,
    TrainingCheckpoint,
    TrainingControl,
    TrainingReview,
)
from overbae.services import container_meter, training_agent, training_monitoring

pytestmark = pytest.mark.covers("training-changes")

RUN = "ft-job-1a2b3c4d"
ENVIRONMENT = "training-test"


@pytest.fixture
def job():
    project = Project.objects.create(name="Agent", slug="agent")
    dataset = Dataset.objects.create(project=project)
    return FinetuningJob.objects.create(
        project=project,
        dataset=dataset,
        base_model="fixture",
        provider=FinetuningJob.Provider.MODAL,
        status=FinetuningJob.Status.RUNNING,
        remote_job_id=f"{RUN}:fc-1",
        requested_configuration={
            "runtime": {"environment": ENVIRONMENT, "controls": training_control.VERSION}
        },
        hyperparameters={
            "monitoring": {"mode": "interval"},
            "learning_rate": 2e-4,
            "execution_limits": training_control.limits({"max_interventions": 2}),
        },
    )


def change(job, operation, arguments=None, *, key="one", author=TrainingControl.Author.PERSON):
    with patch("overbae.tasks.training_agent.send_controls.delay"):
        return training_agent.request(
            job,
            operation=operation,
            arguments=arguments or {},
            reason="Development loss rose",
            request_key=key,
            author=author,
        )


def check(step, loss, state="completed"):
    return {
        "key": f"1:development:{step}",
        "attempt": 1,
        "stream": "development",
        "step": step,
        "state": state,
        "policy_fingerprint": "a" * 64,
        "sample_fingerprint": "b" * 64,
        "started_at": 100,
        "observed_at": 110,
        "metrics": {"eval_loss": loss},
        "coverage": {"expected": 64, "scored": 64},
    }


@pytest.mark.django_db
def test_a_change_stays_inside_the_limits_and_a_retry_returns_it(job):
    with pytest.raises(InputValidationError, match="learning rate"):
        change(job, "set_learning_rate", {"value": 0.5})
    with pytest.raises(InputValidationError, match="No retained checkpoint at step 40"):
        change(job, "restore_checkpoint", {"step": 40})

    first = change(job, "set_learning_rate", {"value": 1e-4})
    assert change(job, "set_learning_rate", {"value": 1e-4}) == first
    with pytest.raises(InputValidationError, match="different change"):
        change(job, "set_learning_rate", {"value": 5e-5})
    assert job.training_controls.count() == 1


@pytest.mark.django_db
def test_the_agent_makes_at_most_its_allowed_changes(job):
    change(job, "set_clip_norm", {"value": 0.5}, key="a", author=TrainingControl.Author.AGENT)
    change(job, "set_clip_norm", {"value": 0.7}, key="b", author=TrainingControl.Author.AGENT)
    with pytest.raises(InputValidationError, match="all 2 allowed changes"):
        change(job, "set_clip_norm", {"value": 0.9}, key="c", author=TrainingControl.Author.AGENT)
    # A person's change is not the agent's allowance.
    change(job, "set_clip_norm", {"value": 0.9}, key="d")


@pytest.mark.django_db
def test_a_run_whose_trainer_takes_no_changes_refuses_them_but_can_stop(
    job, fake_modal, django_capture_on_commit_callbacks
):
    job.requested_configuration = {"runtime": {"environment": ENVIRONMENT}}
    job.save(update_fields=["requested_configuration"])
    assert training_agent.unavailable(job) == "This run's trainer takes no live changes"
    with pytest.raises(InputValidationError, match="takes no live changes"):
        change(job, "finish")

    with django_capture_on_commit_callbacks(execute=True):
        control = change(job, "stop", key="stop")
    control.refresh_from_db()
    job.refresh_from_db()
    assert control.state == TrainingControl.State.APPLIED
    assert job.status == FinetuningJob.Status.CANCELLED


@pytest.mark.django_db
def test_changes_reach_the_trainer_and_come_back_with_their_step(job, fake_modal):
    TrainingCheckpoint.objects.create(
        job=job, key="1:20", attempt=1, step=20, state="available", identity="c" * 64
    )
    lower = change(job, "set_learning_rate", {"value": 1e-4}, key="lr")
    back = change(job, "restore_checkpoint", {"step": 20}, key="back")

    training_agent.send(job.pk)
    sent = fake_modal.dictionaries[(ENVIRONMENT, training_control.STORE)][RUN]
    assert [item["id"] for item in sent] == [str(lower.pk), str(back.pk)]
    assert {item.state for item in job.training_controls.all()} == {"sent"}

    with patch("overbae.tasks.training_agent.review_check.delay"):
        training_monitoring.ingest(
            job,
            {
                "controls": [
                    {"id": str(lower.pk), "state": "applied", "step": 31, "previous": 2e-4},
                    {"id": str(back.pk), "state": "rejected", "step": 31, "error": "Corrupt"},
                ]
            },
        )
    lower.refresh_from_db()
    back.refresh_from_db()
    assert (lower.state, lower.step, lower.result) == ("applied", 31, {"previous": 2e-4})
    assert (back.state, back.result) == ("rejected", {"error": "Corrupt"})
    assert training_agent.detail(job)["learning_rate"] == 1e-4


@pytest.mark.django_db
def test_a_change_the_trainer_never_took_is_not_applied_once_the_run_ends(job, fake_modal):
    pending = change(job, "checkpoint")
    training_agent.send(job.pk)
    training_agent.expire(job)
    pending.refresh_from_db()
    assert (pending.state, pending.result) == (
        "rejected",
        {"error": "The run ended before the trainer applied it"},
    )


@pytest.mark.django_db
def test_a_completed_development_check_is_reviewed_once(job, django_capture_on_commit_callbacks):
    with (
        patch("overbae.tasks.training_agent.review_check.delay") as review,
        django_capture_on_commit_callbacks(execute=True),
    ):
        training_monitoring.ingest(job, {"checks": [check(10, 1.2, "running")]})
        training_monitoring.ingest(job, {"checks": [check(10, 1.2)]})
        training_monitoring.ingest(job, {"checks": [check(10, 1.2)]})
    assert review.call_count == 1


def review_reply(**answer):
    return json.dumps(
        {
            "action": "continue",
            "value": None,
            "step": None,
            "reason": "Development loss fell from 1.40 to 1.20.",
            "expected_effect": "Loss keeps falling.",
            "falsified_by": "Loss rises at the next check.",
            **answer,
        }
    )


@pytest.mark.django_db
def test_the_agent_changes_the_run_through_the_same_controls(job, fake_llm):
    with patch("overbae.tasks.training_agent.review_check.delay"):
        training_monitoring.ingest(job, {"checks": [check(10, 1.4), check(20, 1.6)]})
    fake_llm.on(
        "training agent",
        review_reply(
            action="set_learning_rate",
            value=1e-4,
            reason="Development loss rose from 1.40 to 1.60 while training continued.",
        ),
    )
    with patch("overbae.tasks.training_agent.send_controls.delay"):
        review = training_agent.review_check(job.validation_runs.get(step=20).pk)

    review.refresh_from_db()
    assert review.decision == "set_learning_rate"
    assert review.state == "completed"
    assert "1.40 to 1.60" in review.summary
    control = review.control
    assert (control.author, control.operation, control.arguments) == (
        "agent",
        "set_learning_rate",
        {"value": 1e-4},
    )
    sent = json.loads(fake_llm.requests[-1].body["messages"][-1]["content"])
    assert [item["metrics"]["eval_loss"] for item in sent["development_checks"]] == [1.4, 1.6]


@pytest.mark.django_db
def test_only_the_newest_of_checks_that_arrive_together_is_reviewed(job, fake_llm):
    with patch("overbae.tasks.training_agent.review_check.delay"):
        training_monitoring.ingest(job, {"checks": [check(10, 1.4), check(20, 1.2)]})
    fake_llm.on("training agent", review_reply())
    assert training_agent.review_check(job.validation_runs.get(step=10).pk) is None
    assert training_agent.review_check(job.validation_runs.get(step=20).pk) is not None
    assert len(fake_llm.requests) == 1


@pytest.mark.django_db
def test_a_proposal_outside_the_limits_is_recorded_and_not_applied(job, fake_llm):
    with patch("overbae.tasks.training_agent.review_check.delay"):
        training_monitoring.ingest(job, {"checks": [check(10, 1.4)]})
    fake_llm.on("training agent", review_reply(action="set_learning_rate", value=0.5))
    review = training_agent.review_check(job.validation_runs.get().pk)
    review.refresh_from_db()
    assert review.decision == "refused"
    assert "Not applied" in review.summary
    assert not job.training_controls.exists()


@pytest.mark.django_db
def test_recorded_spend_at_the_allowance_stops_the_run(
    job, fake_modal, django_capture_on_commit_callbacks
):
    job.project.owner = make_user()
    job.project.save(update_fields=["owner"])
    job.hyperparameters = {
        **job.hyperparameters,
        "execution_limits": training_control.limits({"max_cost_usd": 1}),
    }
    job.save(update_fields=["hyperparameters"])
    # An hour of an H100 at FakeModal's rate: past the $1 allowance.
    fake_modal.dictionaries.setdefault(("", METER_STORE), {})["tr-1"] = {
        "container": "tr-1",
        "function": "sft_unsloth",
        "gpu": "H100",
        "gpu_count": 1,
        "cpu": 8,
        "memory_gib": 64,
        "started_at": time.time() - 3600,
        "seen_at": time.time(),
        "wall_seconds": 3600,
        "cpu_core_seconds": 8 * 3600,
        "memory_gib_seconds": 64 * 3600,
        "usage_measured": True,
        "refs": {f"finetune_job:{job.pk}": 3600},
        "stopped": False,
    }
    with django_capture_on_commit_callbacks(execute=True):
        container_meter.collect()
    job.refresh_from_db()
    stop = job.training_controls.get()
    assert job.status == FinetuningJob.Status.CANCELLED
    assert (stop.operation, stop.author) == ("stop", "agent")
    assert stop.reason.startswith("Spent $") and stop.reason.endswith("of the $1 allowance.")


@pytest.mark.django_db
def test_setup_fills_only_what_the_person_left_to_the_agent(job, fake_llm):
    fake_llm.on(
        "starting recipe",
        json.dumps({"learning_rate": 1e-4, "clip_norm": 0.5, "reason": "Small dataset."}),
    )
    plan = type(
        "Plan",
        (),
        {
            "training_type": "Lora",
            "n_epochs": 2,
            "batch_size": 8,
            "context_length": 2048,
            "learning_rate": 2e-4,
        },
    )()
    # The person set the learning rate; only the clip norm is the agent's.
    assert training_agent.setup(job, plan) == {"clip_norm": 0.5}
    assert training_agent.setup(job, plan) == {"clip_norm": 0.5}
    assert TrainingReview.objects.filter(job=job, reason="setup").count() == 1
    assert len(fake_llm.requests) == 1


def test_the_trainer_takes_each_change_once(tmp_path):
    inbox = tmp_path / "controls.json"
    reader = training_control.Inbox(inbox)
    assert reader.take() == []
    first = {"id": "1", "operation": "checkpoint", "arguments": {}}
    training_control.write_inbox(inbox, [first])
    assert reader.take() == [first]
    second = {"id": "2", "operation": "finish", "arguments": {}}
    training_control.write_inbox(inbox, [first, second])
    assert reader.take() == [second]
    assert reader.take() == []