Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/developing/telemetry-internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ rejects a point that conflicts with an existing series, hence the explicit casts
| Metric class | Measurement | Tags | Fields | Emitted by |
|---|---|---|---|---|
| `ModelLoadTimeMetric` | `model_load_time` | `model_key`, `load_type` (`initial` \| `from_cache`) | `replica_id`, `duration_ms`, `num_gpus` | `BaseModelDeployment.load_from_disk` and `from_cache`; the tensor-parallel actor's load |
| `GPUMemMetric` | `gpu_mem` | `model_key`, `api_key`, `email`, `gpu_index` | `request_id`, `replica_id`, `baseline_bytes`, `peak_bytes`, `extra_bytes` | `BaseModelDeployment.run`, one point per device |
| `GPUMemMetric` | `gpu_mem` | `model_key`, `api_key`, `email`, `gpu_index` | `request_id`, `replica_id`, `baseline_bytes`, `peak_bytes`, `extra_bytes`, `peak_reserved_bytes` | `BaseModelDeployment.run`, one point per device |
| `RequestSizeMetric` | `request_size` | `model_key`, `api_key`, `email` | `request_id`, `session_id`, `ip_address`, `user_agent`, `payload_bytes` | `create_request` in `src/ndif/services/api/app.py`, at ingress |
| `RequestResponseSizeMetric` | `response_size` | `model_key`, `api_key`, `email` | `request_id`, `replica_id`, `response_bytes`, `compressed` | `BaseModelDeployment.prepare_result` |
| `ExecutionTimeMetric` | `execution_time` | `model_key`, `api_key`, `email`, `status` (`completed` \| `error` \| `timeout` \| `cancelled` \| `preempted`) | `request_id`, `replica_id`, `exec_ms`, `deserialize_ms`, `upload_ms` | `BaseModelDeployment.report` |
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ what an unmodified client parses.
| `status` | `Status` | *(required)* | Lifecycle position (above). |
| `description` | `str` | `""` | Human-readable detail — queue position, error message, or one line of `print` output for `LOG`. |
| `data` | `Optional[Any]` | `None` | Only on `COMPLETED`: the result itself (on a response sent as `torch.save` bytes) when it fits under `ObjectStoreProvider.max_socket_result_bytes` and the job is blocking, otherwise a presigned GET URL for `{id}.pt` (`BaseModelDeployment.upload_bytes`). The cap lives in [status-and-results.md](../concepts/status-and-results.md). |
| `meta` | `Optional[dict]` | `None` | What the run cost, on `COMPLETED` **and** on the actor's `ERROR` responses (`src/ndif/services/ray/deployments/modeling/util.py` `request_meta`): `runtime` (wall-clock seconds), `max_mem_by_gpu` / `max_mem_pct_by_gpu` (bytes above the resident weights, and that against the headroom the request had), `max_memory_usage` (the worst device), and, only on an out-of-memory failure, `alloc_shortfall_by_gpu`. GPU keys are strings so the JSON and `torch.save` encodings agree. |
| `meta` | `Optional[dict]` | `None` | What the run cost, on `COMPLETED` **and** on the actor's `ERROR` responses (`src/ndif/services/ray/deployments/modeling/util.py` `request_meta`): `runtime` (wall-clock seconds), `max_mem_by_gpu` / `max_mem_pct_by_gpu` (bytes above the resident weights, and peak reserved bytes above them against the headroom the request had), `max_memory_usage` (the worst device), and, only on an out-of-memory failure, `alloc_shortfall_by_gpu`. GPU keys are strings so the JSON and `torch.save` encodings agree. |

Model config (`arbitrary_types_allowed=True, protected_namespaces=()`) is
inherited. `pickle()` (a `torch.save` of `model_dump(exclude_unset=True)`) is
Expand Down
2 changes: 1 addition & 1 deletion docs/runbooks/model-oom-on-deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Its keys:
| Key | Meaning |
|---|---|
| `max_mem_by_gpu` | bytes the request drove on top of the resident weights, per GPU |
| `max_mem_pct_by_gpu` | that, as a percentage of the headroom the request had (share minus weights); 100 means it filled it |
| `max_mem_pct_by_gpu` | peak reserved bytes above the weights, which is what the cap counts, as a percentage of the headroom the request had (share minus weights); 100 means it filled it |
| `alloc_shortfall_by_gpu` | present only on an OOM: how many bytes the refused allocation lacked, per GPU — the amount of padding missing |
| `runtime` | wall-clock seconds |

Expand Down
14 changes: 11 additions & 3 deletions src/ndif/common/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,11 @@ class GPUMemMetric(Metric):
the peak counter and snapshots the baseline before running the request, then
reads the peak afterward. ``extra_bytes = peak - baseline`` is the request's
own activation/allocation footprint on top of the resident weights.
``peak_reserved_bytes`` is the most the allocator held at once, weights
included, which is what the per-process cap counts.

Pass ``per_device`` as ``{gpu_index: (baseline_bytes, peak_bytes)}``; one
Pass ``per_device`` as
``{gpu_index: (baseline_bytes, peak_bytes, peak_reserved_bytes)}``; one
point is emitted per device, tagged with ``gpu_index``.
"""

Expand All @@ -107,12 +110,16 @@ def update(
*,
model_key: str,
request_id: str,
per_device: Dict[int, Tuple[int, int]],
per_device: Dict[int, Tuple[int, int, int]],
api_key: Optional[str] = None,
email: Optional[str] = None,
replica_id: Optional[str] = None,
) -> None:
for gpu_index, (baseline_bytes, peak_bytes) in per_device.items():
for gpu_index, (
baseline_bytes,
peak_bytes,
peak_reserved_bytes,
) in per_device.items():
cls._emit(
tags={
"model_key": model_key,
Expand All @@ -126,6 +133,7 @@ def update(
"baseline_bytes": int(baseline_bytes),
"peak_bytes": int(peak_bytes),
"extra_bytes": int(peak_bytes - baseline_bytes),
"peak_reserved_bytes": int(peak_reserved_bytes),
},
)

Expand Down
2 changes: 2 additions & 0 deletions src/ndif/services/ray/deployments/modeling/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
set_default_gpu,
set_process_limits,
verify_device_placement,
watch_refusals,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -174,6 +175,7 @@ def __init__(
self.runtime_context = ray.get_runtime_context()

self.model = self.load_from_disk()
watch_refusals()
# Move the loaded model's objects (hundreds of thousands) out of the
# collector's reach so the full gc.collect in cleanup() no longer scans
# them on every request. Nothing per-request exists yet, so nothing
Expand Down
136 changes: 53 additions & 83 deletions src/ndif/services/ray/deployments/modeling/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import asyncio
import logging
import os
import re
import threading
from typing import TYPE_CHECKING, Any, Callable, Dict, Tuple

Expand Down Expand Up @@ -285,14 +284,16 @@ def verify_device_placement(model: Any, gpu_ids: Any) -> None:


def gpu_baselines(gpu_mem_bytes_by_id: Dict[int, int]) -> Dict[int, int]:
"""Reset each assigned GPU's peak-allocation counter and snapshot the current
allocation, so a request's own footprint can be read afterward.
"""Reset each assigned GPU's peak-allocation counter, forget earlier refusals
and snapshot the current allocation, so a request's own footprint can be
read afterward.

Called just before a request executes; pair with ``gpu_peaks``. Best-effort —
a device that errors is simply left out of the result.
"""
import torch

_REFUSALS.clear()
baselines: Dict[int, int] = {}
for gpu_id in gpu_mem_bytes_by_id:
try:
Expand All @@ -303,18 +304,24 @@ def gpu_baselines(gpu_mem_bytes_by_id: Dict[int, int]) -> Dict[int, int]:
return baselines


def gpu_peaks(baselines: Dict[int, int]) -> Dict[int, Tuple[int, int]]:
"""Read each device's peak allocation since ``gpu_baselines``.
def gpu_peaks(baselines: Dict[int, int]) -> Dict[int, Tuple[int, int, int]]:
"""Read each device's peak allocation and peak reservation since
``gpu_baselines``.

Returns ``{gpu_id: (baseline_bytes, peak_bytes)}`` — the difference is the
extra memory the just-finished request drove on top of the resident weights.
Returns ``{gpu_id: (baseline_bytes, peak_bytes, peak_reserved_bytes)}`` —
peak minus baseline is the extra memory the just-finished request drove on
top of the resident weights; reserved is what the per-process cap counts.
"""
import torch

per_device: Dict[int, Tuple[int, int]] = {}
per_device: Dict[int, Tuple[int, int, int]] = {}
for gpu_id, baseline in baselines.items():
try:
per_device[gpu_id] = (baseline, torch.cuda.max_memory_allocated(gpu_id))
per_device[gpu_id] = (
baseline,
torch.cuda.max_memory_allocated(gpu_id),
torch.cuda.max_memory_reserved(gpu_id),
)
except Exception:
continue
return per_device
Expand All @@ -340,93 +347,56 @@ def is_oom(exception: BaseException) -> bool:
return "CUDA out of memory" in str(exception)


# The allocator says how much it could not give you, and on which card. Both are
# rounded to two decimals in whatever unit reads best, which costs a few KB of
# precision on a multi-GB figure and nothing that matters.
_REFUSED = re.compile(r"Tried to allocate ([\d.]+)\s*([KMGT]?i?B)", re.IGNORECASE)
_ON_DEVICE = re.compile(r"GPU (\d+)")
_UNITS = {"B": 1, "KIB": 1024, "MIB": 1024**2, "GIB": 1024**3, "TIB": 1024**4}
# What the CUDA allocator refused in this process since `gpu_baselines`:
# {gpu_id: (requested, allowed, reserved)}.
_REFUSALS: Dict[int, Tuple[int, int, int]] = {}


def _refused_allocation(message: str) -> "Tuple[int | None, int] | None":
"""``(device, bytes)`` of the allocation the allocator turned down.
def watch_refusals() -> None:
"""Record every allocation the CUDA allocator refuses in this process.

``device`` is ``None`` when the message names no GPU. ``None`` overall when
the message isn't one of torch's refusals at all.
torch calls the observer once per out-of-memory error it raises, after it
has released its cache and retried, so the reserved bytes read here are the
ones the refusal was measured against. Attaching starts CUDA, so call it
after ``set_default_gpu``.
"""
refused = _REFUSED.search(message)
if refused is None:
return None

scale = _UNITS.get(refused.group(2).upper())
if scale is None:
return None

on_device = _ON_DEVICE.search(message)
return (
int(on_device.group(1)) if on_device else None,
int(float(refused.group(1)) * scale),
)
import torch

def observe(device: int, requested: int, allowed: int, free: int) -> None:
_REFUSALS[device] = (requested, allowed, torch.cuda.memory_reserved(device))

torch._C._cuda_attach_out_of_memory_observer(observe)

def alloc_shortfall(
exception: BaseException, gpu_mem_bytes_by_id: Dict[int, int]
) -> "Dict[str, int] | None":

def alloc_shortfall() -> "Dict[str, int] | None":
"""Of the allocation the allocator refused, the part that would not fit.

``{gpu_id: bytes}``, keyed like ``max_mem_by_gpu`` and with string keys for
the same reason -- a response crosses the wire as JSON or as ``torch.save``
bytes, and only JSON stringifies dict keys.

``requested - (budget - reserved)``: the part of the refused allocation that
``requested - (allowed - reserved)``: the part of the refused allocation that
would not fit in what was left of this actor's assignment. It answers "how
much do I have to free", which the refused allocation's own size does not --
asking for 2 GB with 1.9 GB free and asking for it with nothing free are the
same number and completely different problems.

Only the requested size is read from the exception; the budget is this
actor's own and the reserved figure comes from torch. Reserved rather than
allocated, because the cap is enforced against what the allocator has
*reserved* from the driver, not against what tensors hold.

Taken from the message rather than from torch's OOM observer deliberately.
The observer reports exact integers, but it is out-of-band state that fires
on refusals torch then recovers from, so it has to be cleared per request and
can still hand a later failure someone else's number. The message cannot
desynchronize: it belongs to the exception being reported.

Approximate by nature -- the allocator frees cached blocks and retries before
finally failing, so the reserved figure is a moving snapshot, and the message
rounds. ``None`` when this wasn't a refusal, when the card can't be
identified, or when there is nothing to compare against.
"""
import torch

refusal = _refused_allocation(str(exception))
if refusal is None:
return None
All three figures are torch's, recorded by ``watch_refusals``. Reserved
rather than allocated, because the cap is enforced against what the
allocator has *reserved* from the driver, not against what tensors hold.

device, requested = refusal
if device is None:
# No GPU named. Unambiguous only when this actor holds exactly one.
if len(gpu_mem_bytes_by_id) != 1:
return None
device = next(iter(gpu_mem_bytes_by_id))

budget = gpu_mem_bytes_by_id.get(device)
if budget is None:
return None

try:
reserved = torch.cuda.max_memory_reserved(device)
except Exception:
return None

return {str(device): max(requested - (budget - reserved), 0)}
``None`` when this process refused nothing since ``gpu_baselines``: an
out-of-memory error raised in another process, such as the sandbox runner,
has no figures here.
"""
return {
str(device): max(requested - (allowed - reserved), 0)
for device, (requested, allowed, reserved) in _REFUSALS.items()
} or None


def request_meta(
per_device: Dict[int, Tuple[int, int]],
per_device: Dict[int, Tuple[int, int, int]],
gpu_mem_bytes_by_id: Dict[int, int],
exec_ms: "float | None",
exception: "BaseException | None" = None,
Expand All @@ -450,9 +420,11 @@ def request_meta(
- ``max_mem_by_gpu`` — bytes this request drove *on top of the resident
weights* (peak minus baseline), per device. Not the device's total usage:
the weights are the actor's, not the request's.
- ``max_mem_pct_by_gpu`` — that figure against the headroom the request
actually had (this actor's assigned bytes on the card, less the weights
already sitting in them), so 100% means it filled what was left for it.
- ``max_mem_pct_by_gpu`` — the peak *reserved* bytes above the same
baseline, against the headroom the request actually had (this actor's
assigned bytes on the card, less the weights already sitting in them), so
100% means it filled what was left for it. Reserved, because that is what
the per-process cap counts.
- ``max_memory_usage`` — the worst-pressured single device's bytes, for a
caller that just wants one number.

Expand All @@ -467,7 +439,7 @@ def request_meta(
"""
by_gpu: Dict[str, int] = {}
pct_by_gpu: Dict[str, float] = {}
for gpu_id, (baseline, peak) in per_device.items():
for gpu_id, (baseline, peak, reserved) in per_device.items():
used = max(peak - baseline, 0)
by_gpu[str(gpu_id)] = used
# Headroom is what this actor was assigned on the card minus what its
Expand All @@ -476,7 +448,7 @@ def request_meta(
# dividing by it.
headroom = gpu_mem_bytes_by_id.get(gpu_id, 0) - baseline
pct_by_gpu[str(gpu_id)] = (
round(used / headroom * 100, 2) if headroom > 0 else 0.0
round((reserved - baseline) / headroom * 100, 2) if headroom > 0 else 0.0
)

meta: Dict[str, Any] = {
Expand All @@ -489,9 +461,7 @@ def request_meta(
# Only on an out-of-memory failure: the key is absent on every other
# outcome, so its presence is itself the signal.
if exception is not None and is_oom(exception):
meta["alloc_shortfall_by_gpu"] = alloc_shortfall(
exception, gpu_mem_bytes_by_id
)
meta["alloc_shortfall_by_gpu"] = alloc_shortfall()

return meta

Expand Down
2 changes: 1 addition & 1 deletion tests/test_nnsight_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,7 @@ def test_it_says_how_much_more_was_needed(self, model):
assert all(0 < value <= self.HOG_BYTES for value in short.values())

def test_an_ordinary_failure_carries_no_memory_shortfall(self, model):
# The observer fires on OOM events torch recovers from too, so a failure
# The tests above leave a refusal on the server, so a failure
# that isn't an OOM must not inherit a stale one.
from nnsight.intervention.backends.remote import RemoteError

Expand Down
Loading