Skip to content

The platform for continuously improving AI agents.

8.6 KB
Raw Blame
"""What a Modal container that does a customer's work holds and whom it served.

Every container reports to one Dict, about once a minute: its GPU type and count, the CPU
cores and memory Modal bills it for (the greater of the request and the use, sampled every
few seconds) and the seconds it spent on each billing ref, such as ``finetune_job:<id>``.
The API reads the Dict and charges container seconds at Modal's rates
(overbae/services/container_meter.py). Nothing here prices anything.
"""

import asyncio
import atexit
import contextlib
import functools
import inspect
import logging
import os
import subprocess
import threading
import time

import modal

STORE = "overmind-container-meter"
# Overrides the container's own ref for one request, as for an evaluation that calls a
# fine-tuned model. The API checks that the ref is of the same project.
REF_HEADER = "x-overmind-billing-ref"
REF_ENV = "OVERMIND_BILLING_REF"
PUBLISH_SECONDS = 60
SAMPLE_SECONDS = 5
# Modal's request for a function that names no CPU or memory.
DEFAULT_CPU = 0.125
DEFAULT_MEMORY_GIB = 0.125

logger = logging.getLogger(__name__)

_GPU_NAMES = (
    ("H200", "H200"),
    ("H100", "H100"),
    ("B200", "B200"),
    ("A100-SXM4-80GB", "A100-80GB"),
    ("A100 80GB", "A100-80GB"),
    ("A100", "A100-40GB"),
    ("L40S", "L40S"),
    ("A10", "A10"),
    ("L4", "L4"),
    ("T4", "T4"),
    ("RTX PRO 6000", "RTX-PRO-6000"),
)


def gpus():
    """The container's GPU type, in Modal's names, and count; none without a GPU."""
    try:
        names = subprocess.run(  # noqa: S603
            ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],  # noqa: S607
            capture_output=True,
            text=True,
            timeout=10,
            check=True,
        ).stdout.split("\n")
    except (OSError, subprocess.SubprocessError):
        return None, 0
    names = [name.strip() for name in names if name.strip()]
    if not names:
        return None, 0
    for marker, modal_name in _GPU_NAMES:
        if marker in names[0]:
            return modal_name, len(names)
    return names[0], len(names)


def _cpu_seconds():
    """CPU seconds the container's processes used, from the sandbox's /proc/stat."""
    try:
        with open("/proc/stat") as stat:
            fields = stat.readline().split()[1:]
        ticks = os.sysconf("SC_CLK_TCK")
        user, nice, system = (int(value) for value in fields[:3])
        return (user + nice + system) / ticks
    except (OSError, ValueError, IndexError):
        return None


def _memory_gib():
    try:
        with open("/proc/meminfo") as meminfo:
            values = {line.split(":")[0]: int(line.split()[1]) for line in meminfo if ":" in line}
        return (values["MemTotal"] - values["MemAvailable"]) / 1024**2
    except (OSError, ValueError, KeyError, IndexError):
        return None


class ContainerMeter:
    def __init__(self):
        self.lock = threading.Lock()
        self.function = ""
        self.gpu, self.gpu_count = None, 0
        self.cpu, self.memory_gib = DEFAULT_CPU, DEFAULT_MEMORY_GIB
        self.default_ref = None
        self.active = {}
        self.thread = None
        self._start()

    def _start(self):
        """This container's identity and zero counters. A container restored from a memory
        snapshot runs this again: the snapshot holds another container's identity and time."""
        self.container = os.environ.get("MODAL_TASK_ID", "")
        self.started_at = time.time()
        self.refs = {}
        self.last_ref = None
        self.cpu_core_seconds = 0.0
        self.memory_gib_seconds = 0.0
        self.measured = True
        self.sampled_at = time.monotonic()
        self.cpu_seen = _cpu_seconds()

    def configure(self, function, *, cpu=None, memory_gib=None, ref=None):
        """Name the container's function, its CPU and memory request, and the ref its idle
        and unattributed time goes to."""
        with self.lock:
            self.function = function or self.function
            self.cpu = cpu if cpu is not None else self.cpu
            self.memory_gib = memory_gib if memory_gib is not None else self.memory_gib
            self.default_ref = ref or self.default_ref
            if self.container != os.environ.get("MODAL_TASK_ID", ""):
                self._start()
            if self.thread is None and self.container:
                self.gpu, self.gpu_count = gpus()
                self.thread = threading.Thread(target=self._run, daemon=True)
                self.thread.start()
                atexit.register(self.publish, stopped=True)

    @contextlib.contextmanager
    def serving(self, ref):
        """Count the seconds inside the block toward ``ref``."""
        ref = ref or self.default_ref
        token = object()
        with self.lock:
            if ref:
                self.active[token] = (ref, time.monotonic())
        try:
            yield
        finally:
            with self.lock:
                started = self.active.pop(token, None)
                if started:
                    self.refs[ref] = self.refs.get(ref, 0.0) + time.monotonic() - started[1]
                    self.last_ref = ref

    def _sample(self):
        if self.container != os.environ.get("MODAL_TASK_ID", ""):
            self._start()
            return
        now = time.monotonic()
        elapsed, self.sampled_at = now - self.sampled_at, now
        cpu, memory = _cpu_seconds(), _memory_gib()
        if cpu is None or memory is None or self.cpu_seen is None:
            # Billed at the request alone, which is below what Modal bills for heavier use.
            self.measured = False
        used = cpu - self.cpu_seen if cpu is not None and self.cpu_seen is not None else 0.0
        # A failed read restarts the baseline: the request already covered that interval.
        self.cpu_seen = cpu
        self.cpu_core_seconds += max(self.cpu * elapsed, used)
        self.memory_gib_seconds += max(self.memory_gib, memory or 0.0) * elapsed

    def beat(self, *, stopped=False):
        with self.lock:
            self._sample()
            now = time.monotonic()
            refs = dict(self.refs)
            for ref, started in self.active.values():
                refs[ref] = refs.get(ref, 0.0) + now - started
            return {
                "container": self.container,
                "function": self.function,
                "environment": os.environ.get("MODAL_ENVIRONMENT", ""),
                "gpu": self.gpu,
                "gpu_count": self.gpu_count,
                "cpu": self.cpu,
                "memory_gib": self.memory_gib,
                "started_at": self.started_at,
                "seen_at": time.time(),
                "wall_seconds": time.time() - self.started_at,
                "cpu_core_seconds": self.cpu_core_seconds,
                "memory_gib_seconds": self.memory_gib_seconds,
                "usage_measured": self.measured,
                "refs": refs,
                "last_ref": self.last_ref or self.default_ref,
                "default_ref": self.default_ref,
                "stopped": stopped,
            }

    def publish(self, *, stopped=False):
        # Losing a report must never fail the customer's work; the next one carries totals.
        try:
            value = self.beat(stopped=stopped)
            store = modal.Dict.from_name(STORE, create_if_missing=True)

            async def put():
                await asyncio.wait_for(store.put.aio(self.container, value), timeout=10)

            asyncio.run(put())
        except Exception:
            logger.warning("Container meter report unavailable", exc_info=False)

    def _run(self):
        published = time.monotonic()
        self.publish()
        while True:
            time.sleep(SAMPLE_SECONDS)
            if time.monotonic() - published >= PUBLISH_SECONDS:
                self.publish()
                published = time.monotonic()
            else:
                with self.lock:
                    self._sample()


METER = ContainerMeter()


def serving(ref, *, function, cpu=None, memory_gib=None):
    """Meter this container from now on and count the block toward ``ref``."""
    METER.configure(function, cpu=cpu, memory_gib=memory_gib, ref=ref)
    return METER.serving(ref)


def metered(ref_of, *, cpu=None, memory_gib=None):
    """Meter a Modal function: ``ref_of`` maps its keyword arguments to the billing ref."""

    def wrap(fn):
        signature = inspect.signature(fn)

        @functools.wraps(fn)
        def run(*args, **kwargs):
            arguments = signature.bind(*args, **kwargs).arguments
            with serving(ref_of(**arguments), function=fn.__name__, cpu=cpu, memory_gib=memory_gib):
                return fn(*args, **kwargs)

        return run

    return wrap