The platform for continuously improving AI agents.
"""Charges Modal containers from their reports (modal_shared/container_meter.py).
Each report's new GPU, CPU and memory seconds are priced at Modal's live rates and split
across the refs the container served by their request seconds. Time with no request goes to
the ref the container served last, or was started for. One ledger row per container and ref
grows while the container runs. A report that names no ref, or a ref no record matches, is
our cost: it is logged, never charged to anyone.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from decimal import Decimal
import modal
from django.core.cache import cache
from django.db import transaction
from django.utils import timezone
from modal_shared import container_meter
from overbae.models import (
BillingService,
DecisionPerformanceRun,
DedicatedDeployment,
DeployedModel,
EvalRun,
FinetuningJob,
MeteredContainer,
NativeEvaluationPlan,
TrainingPreparation,
)
from overbae.services import billing_ledger, provider_pricing
logger = logging.getLogger(__name__)
# A container that reported nothing for this long has stopped; its last report is final.
STALE = timedelta(minutes=5)
BASE_FETCH_KEY = "container-meter:base-fetch:{}"
def note_base_fetch(base_model: str, ref: str) -> None:
"""A base download is shared; the work that asked for it first pays for it."""
cache.add(BASE_FETCH_KEY.format(base_model), ref, timeout=6 * 3600)
def _when(seconds: float) -> datetime:
return datetime.fromtimestamp(seconds, UTC)
def resolve(ref: str, function: str = "") -> billing_ledger.Cause | None:
"""The cause a billing ref names: the project and work a container served."""
kind, _, ident = ref.partition(":")
service = BillingService
try:
if kind == "finetune_job":
job = FinetuningJob.objects.filter(pk=ident).first()
return job and billing_ledger.cause(
job.project_id, service.FINETUNING_JOB, kind, job.pk, actor=job.triggered_by_id
)
if kind == "training_run":
job = FinetuningJob.objects.filter(remote_job_id__startswith=f"{ident}:").first()
return job and resolve(f"finetune_job:{job.pk}")
if kind == "training_preparation":
job = FinetuningJob.objects.filter(preparation_id=ident).order_by("created_at").first()
if job is not None:
return resolve(f"finetune_job:{job.pk}")
preparation = (
TrainingPreparation.objects.filter(pk=ident).select_related("cell__dataset").first()
)
return preparation and billing_ledger.cause(
preparation.cell.dataset.project_id, service.FINETUNING_JOB, kind, preparation.pk
)
if kind == "base_model":
asked = cache.get(BASE_FETCH_KEY.format(ident))
return asked and resolve(asked)
if kind in ("served_model", "decision_weights"):
if ident.startswith("dedicated/"):
dedicated = DedicatedDeployment.objects.filter(pk=ident.split("/", 1)[1]).first()
return dedicated and billing_ledger.cause(
dedicated.project_id,
service.DEDICATED_INFERENCE,
"dedicated_deployment",
dedicated.pk,
actor=dedicated.started_by_id,
)
field = "model_id" if kind == "served_model" else "weights_path"
deployed = (
DeployedModel.objects.filter(**{field: ident}).order_by("-created_at").first()
)
if deployed is None:
return None
if function.startswith("decision_dedicated"):
dedicated = deployed.dedicated_deployments.order_by("-created_at").first()
if dedicated is not None:
return resolve(f"served_model:{dedicated.served_model_id}")
return billing_ledger.cause(
deployed.project_id, service.INFERENCE_FT_MODEL, "deployed_model", deployed.pk
)
if kind == "native_evaluation":
plan = NativeEvaluationPlan.objects.filter(pk=ident).first()
return plan and billing_ledger.cause(
plan.project_id, service.EVALUATION, kind, plan.pk, actor=plan.triggered_by_id
)
if kind == "decision_performance":
run = (
DecisionPerformanceRun.objects.filter(pk=ident).select_related("evaluation").first()
)
return run and billing_ledger.cause(
run.project_id,
service.EVALUATION,
kind,
run.pk,
actor=run.evaluation.triggered_by_id,
)
if kind == "eval_run":
run = EvalRun.objects.filter(pk=ident).first()
return run and billing_ledger.cause(run.project_id, service.EVALUATION, kind, run.pk)
except (ValueError, TypeError):
# A malformed id names nothing.
return None
return None
def _rates(card, report):
"""USD per second of each resource; None while Modal's rates are not known."""
rates = card["rates"]
cpu, memory = rates.get("cpu_hour_cost"), rates.get("mem_gib_hour_cost")
gpu = 0.0
if report.get("gpu_count"):
gpu = provider_pricing.gpu_rate(card, report.get("gpu"))
if cpu is None or memory is None or gpu is None:
return None
return {
"gpu": Decimal(str(gpu)),
"cpu": Decimal(str(cpu / 3600)),
"memory": Decimal(str(memory / 3600)),
}
def _resource(report) -> str:
gpu = f"{report['gpu']} x{report['gpu_count']}, " if report.get("gpu_count") else ""
return f"modal {gpu}{report.get('cpu')} CPU, {report.get('memory_gib')} GiB"
def charge_report(report: dict, card: dict) -> bool:
"""Charge what a container reported since its last charge. False when it waits: for
Modal's rates, or for the first ref of a container that is still starting."""
rates = _rates(card, report)
if rates is None:
return False
seen = _when(report["seen_at"])
with transaction.atomic():
state, _ = MeteredContainer.objects.select_for_update().get_or_create(
container_id=report["container"],
defaults={
"function": report.get("function", "")[:128],
"started_at": _when(report["started_at"]),
"charged_until": _when(report["started_at"]),
},
)
done = state.charged
wall = Decimal(str(report["wall_seconds"])) - Decimal(str(done.get("wall", 0)))
if wall <= 0:
return True
cpu = Decimal(str(report["cpu_core_seconds"])) - Decimal(str(done.get("cpu", 0)))
memory = Decimal(str(report["memory_gib_seconds"])) - Decimal(str(done.get("memory", 0)))
gpu = wall * int(report.get("gpu_count") or 0)
usd = gpu * rates["gpu"] + cpu * rates["cpu"] + memory * rates["memory"]
served = {
ref: Decimal(str(seconds)) - Decimal(str(done.get("refs", {}).get(ref, 0)))
for ref, seconds in (report.get("refs") or {}).items()
}
served = {ref: seconds for ref, seconds in served.items() if seconds > 0}
idle = report.get("last_ref") or state.last_ref or report.get("default_ref")
if not served and not idle and not report.get("stopped"):
return False
total = sum(served.values())
shares = (
{ref: seconds / total for ref, seconds in served.items()}
if total
else ({idle: Decimal(1)} if idle else {})
)
if not shares:
logger.error("Container time with no billing ref is absorbed: %s", report["container"])
charged_jobs = set()
for ref, share in shares.items():
found = resolve(ref, report.get("function", ""))
if found is None:
logger.error("Container time for an unknown billing ref is absorbed: %s", ref)
continue
if found.kind == "finetune_job":
charged_jobs.add(found.id)
billing_ledger.accrue(
found,
usd * share,
key=f"modal:{report['container']}:{found.ref}"[:255],
resource=_resource(report),
seconds=wall * share,
provider_ref=report["container"],
started_at=state.charged_until,
ended_at=seen,
components={
"gpu_seconds": float(gpu * share),
"cpu_core_seconds": float(cpu * share),
"memory_gib_seconds": float(memory * share),
},
)
for job in charged_jobs:
billing_ledger.mirror_job_spend(job)
# Cyclic: the agent stops runs through the Modal runner, which imports this module.
from overbae.services import training_agent # noqa: PLC0415
training_agent.enforce_allowance(job)
state.charged = {
"wall": report["wall_seconds"],
"cpu": report["cpu_core_seconds"],
"memory": report["memory_gib_seconds"],
"refs": report.get("refs") or {},
}
state.last_ref = (report.get("last_ref") or idle or "")[:255]
state.charged_until = seen
state.finished = bool(report.get("stopped"))
state.save()
return True
def collect() -> int:
"""Charge every container's latest report; forget a container once it has stopped."""
card = provider_pricing.current_rates()
store = modal.Dict.from_name(container_meter.STORE, create_if_missing=True)
now = timezone.now()
charged = 0
for key, report in list(store.items()):
if now - _when(report["seen_at"]) > STALE:
# It stopped without a last report: up to its last report is all that is known.
report = {**report, "stopped": True}
try:
done = charge_report(report, card)
except Exception:
logger.exception("Container report was not charged: %s", key)
continue
charged += done
if done and report.get("stopped"):
MeteredContainer.objects.filter(pk=report["container"]).update(finished=True)
store.pop(key)
return charged