ray icon indicating copy to clipboard operation
ray copied to clipboard

[Data] Support task memory metrics on macOS

Open Jo-Leo-35 opened this issue 2 months ago • 1 comments

Description

Ray Data currently completes CPU-only map_batches tasks on macOS without recording task USS samples. The current MemoryProfiler implementation enables its RSS-minus-shared estimator only on Linux.

I would like to request macOS-compatible task memory sampling for Ray Data CPU workloads, so users can inspect task memory usage and benefit from the high-memory issue detector when valid measurements are available.

The reproduction below demonstrates the current limitation. The separate MPS experiment provides additional context about memory accounting and is not evidence of Ray MPS support.

Observed behavior

Local tests on an Apple M5 with Ray 2.59.0 produced:

CPU allocation per map task Completed map tasks max_uss_bytes.num_samples Task peak USS
64 MiB 2 0 Unavailable
1 GiB 2 0 Unavailable

Both runs exited successfully and returned both input rows. Each task filled a NumPy array with random data and kept it alive for two seconds. MemoryProfiler._can_estimate_uss() returned False in both runs.

The empty internal aggregate contains mean=0.0, min=None, and max=None. These values represent unavailable samples, not measured zero memory usage.

The captured public Dataset.stats() output contains no heap-memory line. This report uses the internal sample count to establish availability; public formatting was not compared across platforms, and Dashboard/Prometheus output was not tested.

Implementation and documentation

MemoryProfiler only enables its RSS-minus-shared estimator on Linux. Its internal docstring describes the restriction, but the monitoring guide's average_max_uss_per_task description does not mention it.

Data's high-memory issue detector also skips operators with zero memory samples.

The short reproduction below checks sample availability. It does not use the absence of a warning as evidence: periodic warning detection also depends on its interval and a safe-default threshold beyond the requested memory value.

Requested enhancement

Please consider:

  • Adding macOS-compatible task memory sampling for Ray Data CPU workloads.
  • Exposing the measurements through task memory statistics, with clearly defined semantics and acceptable sampling overhead.
  • Allowing Data's high-memory issue detector to use these measurements when available.
  • Clearly distinguishing unsupported or unavailable measurements from measured zero memory usage.
  • Documenting the supported platforms and the types of allocations covered.

USS, phys_footprint, and MPS allocation counters have different meanings. Any implementation should preserve those distinctions rather than combine them or expose a different measurement under the USS name.

MPS accounting could be considered separately. The primary request here is task memory visibility for CPU workloads on macOS.

Environment

  • Hardware: Apple M5 (Mac17,3), 32 GiB RAM.
  • OS: macOS 26.6, build 25G72, arm64.
  • Python: 3.12.14.
  • Ray: 2.59.0, commit dd83c3a703a5422d0b47f142cb380c6330817608.
  • NumPy: 2.5.3; PyArrow: 25.0.1; pandas: 3.0.6; psutil: 7.2.2.
  • Local single-node cluster: 2 logical CPUs, 256 MiB object store, one map task at a time.
  • Runs captured on 2026-10-05.

Linux and a master/nightly build were not executed in this validation.

Minimal reproduction

Save as repro_ray_data_observed.py. This uses synthetic data and Ray Data's dependencies; PyTorch is not required.

"""Compare Ray Data task USS samples on macOS and Linux (Ray 2.59.0)."""
import os
import platform
import sys
import time

import numpy as np
import ray
from ray.data._internal.util import MemoryProfiler

MiB = 1024**2
PAYLOAD = int(os.environ.get("PAYLOAD_MIB", "1024")) * MiB
HOLD = float(os.environ.get("HOLD_SECONDS", "2"))
assert PAYLOAD > 0 and HOLD >= 2


def allocate(batch):
    x = np.random.default_rng(42).random(PAYLOAD // 4, dtype=np.float32)
    assert x.nbytes == PAYLOAD
    time.sleep(HOLD)  # Keep pages live across the default 1-second sampling interval.
    del x
    return batch


print(f"{platform.system()} {platform.machine()} | Python {sys.version.split()[0]}"
      f" | Ray {ray.__version__} ({ray.__commit__})", flush=True)
print("MemoryProfiler._can_estimate_uss():", MemoryProfiler._can_estimate_uss())
print(f"payload_mib={PAYLOAD // MiB}, hold_seconds={HOLD}, memory_request_mib=512")
ray.init(address="local", num_cpus=2, object_store_memory=256 * MiB,
         include_dashboard=False)
try:
    ds = ray.data.range(2, override_num_blocks=2).map_batches(
        allocate, batch_size=1, num_cpus=1, memory=512 * MiB,
        compute=ray.data.TaskPoolStrategy(size=1),
    ).materialize()
    # Internal API: this may change between Ray releases.
    print("max_uss_bytes:", ds._raw_stats().extra_metrics["max_uss_bytes"])
    print("completed_rows:", ds.count())
    print("public_stats:\n" + ds.stats())
finally:
    ray.shutdown()

Install from official PyPI in a Python 3.12 virtual environment:

python3.12 -m venv .venv
.venv/bin/python -m pip install --index-url https://pypi.org/simple \
  'ray[data]==2.59.0' numpy==2.5.3 pyarrow==25.0.1 pandas==3.0.6 psutil==7.2.2

PAYLOAD_MIB=64 .venv/bin/python -u repro_ray_data_observed.py
PAYLOAD_MIB=1024 .venv/bin/python -u repro_ray_data_observed.py

Allow several GiB of available memory. The 64 MiB run is sufficient to check sample availability.

Selected output from the 1 GiB run:

Darwin arm64 | Python 3.12.14 | Ray 2.59.0 (dd83c3a703a5422d0b47f142cb380c6330817608)
MemoryProfiler._can_estimate_uss(): False
payload_mib=1024, hold_seconds=2.0, memory_request_mib=512
max_uss_bytes: {'num_samples': 0, 'mean': 0.0, 'variance': 0.0, 'min': None, 'max': None, 'p25': None, 'p50': None, 'p75': None, 'p90': None, 'p95': None, 'p99': None}
completed_rows: 2

The public statistics also report MapBatches(allocate): 2 tasks executed. The 64 MiB run has the same sample-availability result.

memory=512 MiB is a scheduling reservation, not a hard allocation limit. _raw_stats() and MemoryProfiler are internal APIs and may change between releases.

Related work

#66335 concerns CUDA allocations missing from existing Linux measurements on DGX Spark. #66340 proposes NVIDIA CUDA/NVML accounting.

This report concerns the macOS platform gate, which disables CPU task samples as well.

Supplementary experiment: CPU and Apple MPS memory accounting

This experiment ran outside Ray on the same Apple M5 / macOS 26.6 machine. It used Python 3.12.14, PyTorch 2.14.0, NumPy 2.5.3, and psutil 7.2.2.

A fresh process allocated a 2 GiB random float32 tensor on each device. Each process warmed up its selected device first. The MPS process cleared the warm-up cache and synchronized device operations before sampling. The tensor remained live for the after-allocation snapshot.

Both processes exited with status 0 and empty stderr.

Allocation RSS delta USS delta phys_footprint delta MPS active delta MPS driver delta
CPU, 2 GiB +2.000076 GiB +2.000015 GiB +2.000993 GiB N/A N/A
Apple MPS, 2 GiB +80 KiB +16 KiB +2.000015 GiB +2.000000 GiB +2.000000 GiB

For this MPS allocation, RSS and USS changed very little while phys_footprint and PyTorch's MPS counters increased by approximately the allocation size. This suggests that enabling CPU USS measurement alone would not capture this MPS case.

phys_footprint is read via proc_pid_rusage(RUSAGE_INFO_V2) and has different semantics from USS. It should not be added to USS or silently exposed as USS.

This table represents one run per device in the specified environment, not a comprehensive benchmark of MPS allocations. System-wide memory deltas include other processes and are not attributed solely to the tensor. These results do not resolve NVIDIA USS/NVML overlap questions in #66340.

Extract mps_memory_accounting.py from the attached evidence archive, then run it in a separate environment:

python3.12 -m venv .venv-mps
.venv-mps/bin/python -m pip install --index-url https://pypi.org/simple \
  torch==2.14.0 numpy==2.5.3 psutil==7.2.2

.venv-mps/bin/python mps_memory_accounting.py --device cpu --mib 2048
.venv-mps/bin/python mps_memory_accounting.py --device mps --mib 2048

The script outputs versions, before/after counters, and deltas as JSON. It requires the payload plus 2 GiB of available memory.

This supplementary experiment is independent of the minimal CPU-only Ray reproduction.

The attached evidence archive contains the scripts, environment details, and raw execution logs.

This report and its scripts were prepared and executed with AI assistance.

Use case

Users developing Ray Data pipelines on macOS need task memory visibility to identify memory-heavy transformations and choose appropriate concurrency and memory requests.

In the attached reproduction, both CPU workloads complete successfully, but neither produces task USS samples. As a result, the task memory statistics cannot help users assess these allocations, and Data's high-memory issue detector skips operators without samples.

macOS-compatible sampling would make these diagnostics available during local development.

ray-macos-evidence-redacted.zip

Implementation plan:

  • [ ] Benchmark macOS USS sampling accuracy and overhead.
  • [ ] Support CPU task USS sampling on macOS.
  • [ ] Add unit and macOS allocation tests.
  • [ ] Document supported platforms and allocation types.
  • [ ] Consider clearer unavailable-vs-zero presentation separately.

Out of scope:

  • Apple MPS memory accounting
  • CUDA/NVML memory accounting

Jo-Leo-35 avatar Oct 05 '26 14:10 Jo-Leo-35

Hi @goutamvenkat-anyscale, I'd like to pick this up. Plan: extend MemoryProfiler._can_estimate_uss in python/ray/data/_internal/util.py to support Darwin using psutil.Process().memory_full_info().uss, keep reporting no samples (rather than zero) when it isn't available, and update the platform note for average_max_uss_per_task in doc/source/data/monitoring-your-workload.rst. I'll add a test that runs a CPU map_batches allocating a known array and asserts that max_uss_bytes has samples and a plausible peak on macOS, while the Linux path stays unchanged. psutil's macOS USS walks memory regions and can be slow, so is that acceptable at the current poll interval, or would you prefer a cheaper macOS metric under a different name? Could you assign it to me?

rahulsjha avatar Nov 17 '26 17:11 rahulsjha