Skip to content

[Data] Include GPU memory in average_max_uss_per_task on UMA systems - #66340

Closed
xuwenyihust wants to merge 2 commits into
ray-project:masterfrom
xuwenyihust:wenyixu/uma-memory-accounting
Closed

xuwenyihust wants to merge 2 commits into
ray-project:masterfrom
xuwenyihust:wenyixu/uma-memory-accounting

Conversation

@xuwenyihust

@xuwenyihust xuwenyihust commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On DGX Spark, CPU and GPU allocations share the same physical memory, but CUDA allocations are not reflected in the worker's RSS. Ray Data's RSS - shared estimate therefore misses this memory usage.

Solution

This PR detects a single visible integrated NVIDIA GPU using CU_DEVICE_ATTRIBUTE_INTEGRATED and estimates task memory as actual USS plus the GPU memory attributed to the worker by NVML.

Validation

Tested on DGX Spark with the patched Ray master wheel.

Both pipelines used one actor with num_cpus=1, num_gpus=1,
and memory=512 * 1024**2 (512 MiB).

Allocation Mean task peak memory High-memory warning
CPU 3.38 GiB Emitted
CUDA 3.71 GiB Emitted

Before the change, the CUDA case reported about 401 MiB and did not emit the warning

Related issues

Related to #66335.

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@xuwenyihust xuwenyihust changed the title Account for GPU memory on unified memory architectures [Data] Account for GPU memory on unified memory architectures Sep 21, 2026
@xuwenyihust xuwenyihust changed the title [Data] Account for GPU memory on unified memory architectures [Data] Include GPU memory in average_max_uss_per_task on UMA systems Sep 21, 2026
@xuwenyihust
xuwenyihust marked this pull request as ready for review September 21, 2026 03:19
@xuwenyihust
xuwenyihust requested a review from a team as a code owner September 21, 2026 03:19

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces process memory accounting for unified memory architectures (UMA) by detecting integrated GPUs and incorporating their memory usage into the MemoryProfiler's USS estimates. It also adds a comprehensive suite of unit tests. The review feedback suggests three key improvements: using a cheaper USS approximation instead of memory_full_info().uss to avoid high CPU overhead from parsing /proc/<pid>/smaps, wrapping the pynvml import in a try-except block to handle potential ImportErrors, and ensuring nvml.nvmlShutdown is registered with atexit only once to prevent duplicate shutdown errors at process exit.

Comment on lines +1941 to +1945
try:
return self._process.memory_full_info().uss + gpu_memory
except psutil.Error:
logger.warning("Process USS measurement unavailable", exc_info=True)
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using self._process.memory_full_info().uss can be extremely slow because it parses /proc/<pid>/smaps on Linux, which can take tens of milliseconds and introduce significant CPU overhead in the background polling thread. Since MemoryProfiler is designed to be a cheap approximation, consider using the estimated USS (self._process.memory_info().rss - memory_info.shared) instead, even when GPU memory is present, to keep the profiling overhead minimal.

Suggested change
try:
return self._process.memory_full_info().uss + gpu_memory
except psutil.Error:
logger.warning("Process USS measurement unavailable", exc_info=True)
return None
try:
memory_info = self._process.memory_info()
return memory_info.rss - memory_info.shared + gpu_memory
except psutil.Error:
logger.warning("Process USS measurement unavailable", exc_info=True)
return None

Comment thread python/ray/data/_internal/uma_memory.py Resolved
Comment thread python/ray/data/_internal/uma_memory.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit af8e5bc. Configure here.

Comment thread python/ray/data/_internal/util.py Resolved
@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Sep 21, 2026
raise ValueError("NVML process memory is unavailable")
return value
# No CUDA context (including after cudaDeviceReset).
return 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing NVML entry is treated as a certain zero, not as unknown.

Inside a container NVML reports host PIDs, so process.pid == pid never matches.

Under MPS the memory is attributed to the MPS server PID. In both cases the reader confidently returns 0 and the task reports plain USS, which is the very under-reporting the issue complains about, now hidden behind a "supported" code path.

The N/A case a few lines up is correctly treated as unavailable, so the handling is asymmetric.

if gpu_memory is None:
return None
try:
return self._process.memory_full_info().uss + gpu_memory

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible double counting on UMA.

On an integrated GPU the CUDA allocation is carved from system RAM. If those pages are mapped into the process (managed memory, pinned host memory, or driver mappings), they already appear in USS and are counted again via NVML.

The PR's own numbers (3.71 GiB CUDA-side vs 3.38 GiB CPU-side for a 3 GiB allocation) do not rule this out.

Nothing in the PR measures the overlap.

if self._gpu_memory_reader is not None:
gpu_memory = self._gpu_memory_reader()
if gpu_memory is None:
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One transient failure erases the whole task's metric.

_sample_memory latches _measurement_failed (util.py:1905–1907) and there is no fallback to the legacy estimate.

Before this PR a UMA task always produced a number. After it, a single NVML hiccup produces None.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 14, 2026
dstrodtman added a commit that referenced this pull request Oct 21, 2026
…examples to stock doctests (#67207)

## Description

Converts the remaining runnable `.. testcode::` examples in nine
`Dataset` methods to stock `>>>` doctests: `streaming_split`, `split`,
`iter_batches`, `iter_jax_batches`, `iter_tf_batches`, `stats`,
`explain`, `serialize_lineage`, and `deserialize_lineage`. It also
converts the one example each in
`SerializablePreprocessorBase._set_serializable_fields`
(`preprocessor.py`) and `MemoryProfiler` (`_internal/util.py`). Stock
doctests render without Sphinx-only directives, and the `docstring-only`
label's examples step runs them. The change touches only docstrings.

Three examples used `:options: +MOCK`, which hid their output from
comparison. Comparing it surfaced the following fixes:

- **`iter_batches`** read `example://image-datasets/simple`, which
resolves inside the installed package, and wheels don't ship
`ray/data/examples/data/`. It now reads the same images from
`s3://anonymous@ray-example-data/image-datasets/simple`, as
`Dataset.map` does. The three images make exactly two batches, so the
expected output drops the `...` line between them, which wouldn't have
matched.
- **`stats`** shows the current output format, with ellipses for counts,
timings, and the read operator's name, which becomes
`ReadRange->SplitBlocks(N)` depending on the CPU count. The `assert
ds.stats() == ""` is now `>>> ds.stats()` with `''` as the output.
- **`MemoryProfiler`** replaces the `...` placeholder statement with
`pass`. In a doctest, a bare `...` expression echoes `Ellipsis` on every
loop iteration. The USS values use an ellipsis.

**`iter_tf_batches`** called `Dataset.to_tf`, which has its own
examples. It now calls `iter_tf_batches` and prints the first batch,
matching the `iter_jax_batches` example.

The fourth `streaming_split` example deliberately blocks, so it stays
render-only, now with `# doctest: +SKIP` on that one line in place of
`:skipif: True`. The rest of the docstring runs. `explain`, `split`, and
the lineage examples matched as written.

**`iter_jax_batches` and `iter_tf_batches` run only in postmerge under
the label.** The docstring examples image omits JAX and TensorFlow, so
the step skips both docstrings by name. They still run in
`//python/ray/data:doctest`.

## Related issues

Related to #66814, #67083, and #67202.

## Additional information

**Not a duplicate.** I searched open PRs that touch
`python/ray/data/dataset.py`, `streaming_split`, `serialize_lineage`, or
`MemoryProfiler`. #67202 converts the `Dataset` transform methods
(`map`, `map_batches`, `flat_map`, `groupby`, `aggregate`, `join`) in
the same file, and the two PRs edit different methods. #64869 and #66340
don't touch these examples. #66746, #66812, #67070, and #67080 converted
other Data modules and have merged.

**Tests run**

- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3
file(s), docstrings only."
- `ci/ray_ci/doc/run_docstring_examples.py` on the three files in an
aarch64 image built from
`python/deplocks/docs/docstring_examples_depset_py3.10.lock`, with the
Ray nightly at `093faf5583e` and the changed files mounted over the
installed ones. The three files are unchanged between that commit and
this PR's base. Result: 61 docstrings run and 0 failed.
`iter_jax_batches`, `iter_tf_batches`, `to_tf`, `write_tfrecords`, and
`iter_torch_batches` are skipped for libraries the image omits.
- The two JAX and TensorFlow docstrings, run with `doctest` in the same
image after installing `jax` 0.6.2 and `tensorflow` 2.21.0: 0 failures
each. Those aren't CI's pinned versions, so I'll check the postmerge
`data: docs example tests` result after merge.
- `pre-commit run --files` on the three files: all hooks pass, including
ruff, black, pydoclint, and the Ray docstyle check.

The PR carries the `docstring-only` label, and its commit carries an
`@rtd-build` line for the Read the Docs preview.

AI assistance (Claude Code) was used for this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants