Skip to content

The platform for continuously improving AI agents.

10.5 KB
Raw Blame
import json
import math
from datetime import datetime, timedelta
from uuid import UUID

import modal
from asgiref.sync import async_to_sync
from django.utils import timezone

from modal_shared.modelfam import serve_image_key
from modal_shared.serving.artifacts import digest_json
from modal_shared.shared import base_pool_name, rel_weights_path, worker_cls_name
from modal_shared.stacks import WORKER_MEMORY_MIB
from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import get_hf_base
from overbae.models import DeployedModel, ResearchAction
from overbae.services import execution_mandates


def staged_base(job, environment):
    base = get_hf_base(job.base_model)
    path = ".base_models/" + base.replace("/", "--")

    async def read():
        volume = modal.Volume.from_name("overmind-weights", environment_name=environment)
        parts = [chunk async for chunk in volume.read_file.aio(f"{path}/.base-manifest.json")]
        return json.loads(b"".join(parts))

    manifest = async_to_sync(read)()
    if manifest.get("repo") != base or manifest.get("identity") != digest_json(
        {key: value for key, value in manifest.items() if key != "identity"}
    ):
        raise InputValidationError("The retained base snapshot has no valid immutable manifest")
    return {"path": path, "identity": manifest["identity"]}


def policy(deployed):
    return (deployed.serving_runtime or {}).get("lease")


def closed(deployed):
    lease = policy(deployed)
    return bool(
        lease
        and (lease.get("closed_at") or datetime.fromisoformat(lease["deadline"]) <= timezone.now())
    )


# The longest a deployment may take to start. A lease allows it and its quote reserves it.
STARTUP_SECONDS = 2400


def admitted(ttl_seconds, now, limit):
    """A new lease's time. Serving counts from ready, so until then its deadline allows the
    startup as well."""
    return {
        "ttl_seconds": ttl_seconds,
        "deadline": min(limit, now + timedelta(seconds=STARTUP_SECONDS + ttl_seconds)).isoformat(),
    }


def started(lease, now):
    """The lease of a deployment that has just become ready: its serving time starts now."""
    # A lease admitted before its duration was recorded keeps the deadline it was given.
    if "ttl_seconds" not in lease:
        return lease
    until = now + timedelta(seconds=lease["ttl_seconds"])
    return {**lease, "deadline": min(datetime.fromisoformat(lease["deadline"]), until).isoformat()}


def require_open(deployed):
    expected = policy(deployed)
    if expected is None:
        return None
    current = DeployedModel.objects.filter(pk=deployed.pk).first()
    lease = policy(current) if current else None
    if (
        not lease
        or current.deployment_generation != deployed.deployment_generation
        or any(lease.get(key) != expected.get(key) for key in ("allocation", "assignment"))
    ):
        raise InputValidationError("This serving allocation has been superseded")
    if closed(current):
        raise InputValidationError("This serving allocation has expired")
    execution_mandates.require_serving_lease(current)
    return lease


def require_inference(request, *, deployed=None):
    if request.payload.get("source") != "research" and not request.payload.get(
        "serving_allocation"
    ):
        return
    deployed = deployed or request.deployment
    lease = require_open(deployed)
    # Research inference on a checkpoint's standard deployment carries no allocation.
    standard = policy(deployed) is None and not request.payload.get("serving_allocation")
    if not standard and (
        not lease
        or deployed.status != "ready"
        or request.project_id != deployed.project_id
        or request.payload.get("deployment") != str(deployed.pk)
        or request.payload.get("deployment_generation") != str(deployed.deployment_generation)
        or request.payload.get("serving_allocation") != lease["allocation"]
    ):
        raise InputValidationError("The inference allocation has been superseded")
    prefix, _, identifier = request.request_key.partition(":")
    try:
        action_id = UUID(identifier)
    except (ValueError, AttributeError) as exc:
        raise InputValidationError("Research inference has no retained request owner") from exc
    action = (
        ResearchAction.objects.select_related("agent__assignment")
        .filter(
            pk=action_id,
            agent__assignment__project_id=request.project_id,
            agent__assignment__created_by_id=request.user_id,
            agent__parent__isnull=True,
            tool="serving",
            arguments__operation="infer",
            arguments__deployment=str(deployed.pk),
            state__in=["pending", "running", "unknown", "completed"],
        )
        .first()
    )
    if prefix != "research" or action is None:
        raise InputValidationError("Research inference has no retained request owner")
    execution_mandates.require_action_continuation(action, "serve")


def options(lease, *, gpu=False):
    remaining = int((datetime.fromisoformat(lease["deadline"]) - timezone.now()).total_seconds())
    if remaining <= 0:
        raise InputValidationError("This serving allocation has expired")
    return {
        "timeout": min(lease["execution_seconds"], remaining),
        "retries": 0,
        "max_containers": 1,
        "buffer_containers": 0,
        "scaledown_window": 30,
        **({} if gpu else {"cpu": (2, 2), "memory": (8192, 8192)}),
    }


def cpu(function, deployed):
    lease = require_open(deployed)
    return function.with_options(**options(lease)) if lease else function


async def worker(deployed):
    lease = policy(deployed)
    if lease and deployed.inference_contract == "decision":
        return modal.Cls.from_name(
            deployed.serving_runtime["app"],
            "DecisionEndpoint",
            environment_name=lease["environment"],
        ).with_options(
            **options(lease, gpu=True),
            gpu=deployed.gpu_type,
            cpu=(8, 8),
            memory=(WORKER_MEMORY_MIB[deployed.gpu_type], WORKER_MEMORY_MIB[deployed.gpu_type]),
        )(
            weights_path=deployed.weights_path,
            artifact_identity=deployed.checkpoint_hash,
            max_model_len=deployed.max_model_len,
        )
    if not lease or not deployed.adapter_path:
        raise InputValidationError("A bounded LoRA serving allocation is required")
    path = rel_weights_path(deployed.weights_path)
    volume = modal.Volume.from_name("overmind-weights", environment_name=lease["environment"])
    chunks = [chunk async for chunk in volume.read_file.aio(f"{path}/.base-manifest.json")]
    identity = json.loads(b"".join(chunks))["identity"]
    if lease["staged_base"] != {"path": path, "identity": identity}:
        raise InputValidationError("The serving base differs from the admitted immutable snapshot")
    gpu_options = {
        **options(lease, gpu=True),
        "cpu": (8, 8),
        "memory": (WORKER_MEMORY_MIB[deployed.gpu_type], WORKER_MEMORY_MIB[deployed.gpu_type]),
    }
    cls = modal.Cls.from_name(
        "overmind-inference",
        worker_cls_name(
            deployed.gpu_type, serve_image_key(deployed.base_model_id), enable_lora=True
        ),
        environment_name=lease["environment"],
    ).with_options(**gpu_options)
    return cls(
        model_path=path,
        model_name=base_pool_name(path) + "-research-" + lease["allocation"],
        max_model_len=deployed.max_model_len,
        enable_lora=True,
        max_lora_rank=deployed.lora_rank or 16,
        base_identity=identity,
    )


def operation(deployed, inputs):
    require_open(deployed)
    instance = async_to_sync(worker)(deployed)
    if deployed.inference_contract == "decision":
        return instance.predict, {"requests": inputs["decisions"]}
    return instance.infer, {
        "method": "POST",
        "path": "/v1/chat/completions",
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"model": deployed.model_id, "stream": False, **inputs}).encode(),
        "adapter": (deployed.model_id, rel_weights_path(deployed.adapter_path)),
    }


def completion(result, deployed=None, decisions=None):
    if deployed is not None and deployed.inference_contract == "decision":
        if not isinstance(result, dict) or result.get("model_identity") != deployed.checkpoint_hash:
            raise ValueError("Decision serving returned a different checkpoint")
        predictions = result.get("predictions")
        if not isinstance(predictions, list) or not predictions or result.get("error_code"):
            raise ValueError("Decision serving returned no predictions")
        for prediction in predictions:
            probabilities = prediction.get("probabilities", [])
            if (
                prediction.get("model_identity") != deployed.checkpoint_hash
                or len(probabilities) != len(prediction.get("options", []))
                or not probabilities
                or any(not math.isfinite(p) or p < 0 or p > 1 for p in probabilities)
                or not math.isclose(sum(probabilities), 1, abs_tol=1e-5)
            ):
                raise ValueError("Decision serving returned invalid probabilities")
        if decisions is not None and (
            len(predictions) != len(decisions)
            or any(
                prediction.get("options") != request["options"]
                or prediction.get("kind") != request["kind"]
                for prediction, request in zip(predictions, decisions, strict=True)
            )
        ):
            raise ValueError("Decision serving returned different request bindings")
        return result
    if not isinstance(result, dict) or result.get("status") != 200:
        raise ValueError("The serving worker did not return a successful response")
    body = json.loads(result["body"])
    choices = body.get("choices") if isinstance(body, dict) else None
    if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
        raise ValueError("The serving response has no completion choice")
    choice = choices[0]
    message = choice.get("message")
    if not isinstance(message, dict):
        raise ValueError("The serving response has no completion message")
    content = message.get("content")
    if not isinstance(content, str) or not content.strip() or not choice.get("finish_reason"):
        raise ValueError("The serving worker returned no usable completion")
    return {
        "content": content,
        "usage": body.get("usage"),
        "finish_reason": choice["finish_reason"],
        "latency_ms": None,
        "model_identity": body.get("model"),
    }