Skip to content

[train][tune] v1 CheckpointManager only stores scoring metric if env var set - #54642

Merged
matthewdeng merged 6 commits into
ray-project:masterfrom
TimothySeah:tseah/tune-cpm-reduce-memory
Jul 17, 2025
Merged

matthewdeng merged 6 commits into
ray-project:masterfrom
TimothySeah:tseah/tune-cpm-reduce-memory

Conversation

@TimothySeah

@TimothySeah TimothySeah commented Jul 16, 2025 •

Copy link
Copy Markdown
Contributor

Summary

When Ray Train v1 or Ray Tune users report metrics, we persist them in memory inside CheckpointManager, which can OOM.

This change adds a new env variable, TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE, which makes it so CheckpointManager only saves the checkpoint_score_attribute metric in memory, reducing the memory footprint from O(checkpoints * metrics) to O(checkpoints).

Note that when TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE is set, we still persist all the metrics to disk, but when we construct the Tune ResultGrid, it only contains the checkpoint_score_attribute. This is just a temporary solution to unblock users; we can implement a more robust solution, such as reading metrics from disk in a streaming fashion, in the future.

Testing

I ran this driver script

import ray
import ray.train
import ray.train.torch
import os

def train_func():
    dir_path = "/tmp/example_checkpoint_dir"
    os.makedirs(dir_path, exist_ok=True)
    ray.train.report(
        {"score": 2.5, "unsaved": 1.0}, 
        checkpoint=ray.train.Checkpoint.from_directory(dir_path))
    dir_path = "/tmp/another_example_checkpoint_dir"
    os.makedirs(dir_path, exist_ok=True)
    ray.train.report(
        {"unsaved": 0.5}, 
        checkpoint=ray.train.Checkpoint.from_directory(dir_path))
   
trainer = ray.train.torch.TorchTrainer(
    train_func,
    scaling_config=ray.train.ScalingConfig(num_workers=1),
    run_config=ray.train.RunConfig(
        checkpoint_config=ray.train.CheckpointConfig(
            num_to_keep=2,
            checkpoint_score_attribute="score",
            checkpoint_score_order="max",
        ),
    )
)
result = trainer.fit()

with this command TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE=1 python ../playground/dummy_train_report.py

I added print statements to CheckpointManager which verified that its internal state only has the score metric:

checkpoint_results: [TrainingResult(checkpoint=Checkpoint(filesystem=local, path=/Users/tseah/ray_results/TorchTrainer_2025-07-16_16-08-39/TorchTrainer_d0b6a_00000_0_2025-07-16_16-08-42/checkpoint_000000), metrics={'score': 2.5}), TrainingResult(checkpoint=Checkpoint(filesystem=local, path=/Users/tseah/ray_results/TorchTrainer_2025-07-16_16-08-39/TorchTrainer_d0b6a_00000_0_2025-07-16_16-08-42/checkpoint_000001), metrics={})]

I also inspected the result.json object to verify that it was still writing all the metrics to disk

(ray4) tseah@tseah-LV3607J62K TorchTrainer_d0b6a_00000_0_2025-07-16_16-08-42 % cat result.json
{"score": 2.5, "unsaved": 1.0, "timestamp": 1752707325, "checkpoint_dir_name": "checkpoint_000000", "should_checkpoint": true, "done": false, "training_iteration": 1, "trial_id": "d0b6a_00000", "date": "2025-07-16_16-08-45", "time_this_iter_s": 1.3460710048675537, "time_total_s": 1.3460710048675537, "pid": 67017, "hostname": "Mac.attlocal.net", "node_ip": "127.0.0.1", "config": {}, "time_since_restore": 1.3460710048675537, "iterations_since_restore": 1}
{"unsaved": 0.5, "timestamp": 1752707325, "checkpoint_dir_name": "checkpoint_000001", "should_checkpoint": true, "done": false, "training_iteration": 2, "trial_id": "d0b6a_00000", "date": "2025-07-16_16-08-45", "time_this_iter_s": 0.0030426979064941406, "time_total_s": 1.3491137027740479, "pid": 67017, "hostname": "Mac.attlocal.net", "node_ip": "127.0.0.1", "config": {}, "time_since_restore": 1.3491137027740479, "iterations_since_restore": 2}

I also tested this with tune/rllib in a workspace:

@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.

Summary of Changes

Hello @TimothySeah, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a critical memory optimization for Ray Tune's CheckpointManager by limiting the in-memory storage of checkpoint metrics to only the essential scoring attribute. As a result, the mechanism for constructing Result objects has been updated to retrieve comprehensive data directly from disk, ensuring continued functionality while mitigating memory consumption issues.

Highlights

  • Memory Optimization: The CheckpointManager's register_checkpoint method has been updated to store only the checkpoint_score_attribute metric (if configured and present) in memory for each checkpoint. This significantly reduces the memory footprint from O(checkpoints * metrics) to O(checkpoints), addressing potential Out-Of-Memory (OOM) issues.
  • Result Loading Strategy: The _trial_to_result method within ResultGrid has been refactored to load Result objects directly from the trial's path on disk using Result.from_path. This change is a direct consequence of the CheckpointManager no longer holding all reported metrics in memory.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 reduces the memory footprint of the CheckpointManager by only storing the scoring metric and creating the Result from disk. The changes are well-structured and address the OOM issue effectively.

@TimothySeah TimothySeah added the go add ONLY when ready to merge, run all tests label Jul 16, 2025
@TimothySeah
TimothySeah force-pushed the tseah/tune-cpm-reduce-memory branch from 0828a00 to 1f0860f Compare July 16, 2025 20:32
@TimothySeah
TimothySeah requested a review from justinvyu July 16, 2025 20:41
@TimothySeah
TimothySeah marked this pull request as ready for review July 16, 2025 20:41
@TimothySeah
TimothySeah requested a review from a team as a code owner July 16, 2025 20:41
@TimothySeah TimothySeah changed the title [train][tune] v1 CheckpointManager only stores scoring metric [train][tune] v1 CheckpointManager only stores scoring metric if env var set Jul 16, 2025
Signed-off-by: Timothy Seah <[email protected]>
Comment thread python/ray/train/constants.py Resolved
Signed-off-by: Timothy Seah <[email protected]>
@TimothySeah
TimothySeah requested a review from matthewdeng July 16, 2025 23:13
Comment thread python/ray/train/constants.py Outdated
# Defaults to 0.
# TODO: this is a temporary solution to avoid CheckpointManager OOM.
# See https://github.com/ray-project/ray/pull/54642#issue-3234029360 for more details.
RAY_TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE = (

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added - not sure how many internal details to expose so ptal, thanks!

Comment on lines +221 to +226
assert manager.best_checkpoint_results[0].metrics == {"score": 1.0}
assert manager.best_checkpoint_results[0].checkpoint.path == checkpoint_paths[1]
assert manager.best_checkpoint_results[1].metrics == {"score": 3.0}
assert manager.best_checkpoint_results[1].checkpoint.path == checkpoint_paths[0]
assert manager.best_checkpoint_results[2].metrics == {}
assert manager.best_checkpoint_results[2].checkpoint.path == checkpoint_paths[2]

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.

is this order correct? Should score==3 be at the top?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I also thought that would be more intuitive but best_checkpoint_result does return the last element in the list: https://github.com/ray-project/ray/blob/master/python/ray/train/_internal/checkpoint_manager.py#L175.

This means that TrainingResults that lack metrics will automatically be seen as "better." Maybe we should change that in the future but I don't want to introduce too many changes to this PR.

Comment on lines +228 to +233
assert manager.best_checkpoint_results[0].metrics == {}
assert manager.best_checkpoint_results[0].checkpoint.path == checkpoint_paths[0]
assert manager.best_checkpoint_results[1].metrics == {}
assert manager.best_checkpoint_results[1].checkpoint.path == checkpoint_paths[1]
assert manager.best_checkpoint_results[2].metrics == {}
assert manager.best_checkpoint_results[2].checkpoint.path == checkpoint_paths[2]

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.

is this order correct? Should it be insertion order ascending or descending?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Ya sounds good I realized none of that logic was changed in this PR.

@TimothySeah
TimothySeah removed the request for review from justinvyu July 17, 2025 00:08
Signed-off-by: Timothy Seah <[email protected]>
@TimothySeah
TimothySeah requested review from a team as code owners July 17, 2025 00:28
@TimothySeah
TimothySeah requested a review from matthewdeng July 17, 2025 00:30
Comment thread doc/source/tune/api/env.rst Resolved
TimothySeah and others added 2 commits July 16, 2025 19:09
Co-authored-by: matthewdeng <[email protected]>
Signed-off-by: Timothy Seah <[email protected]>
Signed-off-by: Timothy Seah <[email protected]>
@matthewdeng
matthewdeng merged commit a161090 into ray-project:master Jul 17, 2025
jugalshah291 pushed a commit to jugalshah291/ray_fork that referenced this pull request Sep 11, 2025
…var set (ray-project#54642)

When Ray Train v1 or Ray Tune users report metrics, we persist them in
memory inside CheckpointManager, which can OOM.

This change adds a new env variable,
`TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE`, which makes it so
CheckpointManager only saves the `checkpoint_score_attribute` metric in
memory, reducing the memory footprint from O(checkpoints * metrics) to
O(checkpoints).

Note that when `TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE` is set, we
still persist all the metrics to disk, but when we construct the Tune
[ResultGrid](https://github.com/ray-project/ray/blob/master/python/ray/tune/result_grid.py#L269),
it only contains the `checkpoint_score_attribute`. This is just a
temporary solution to unblock users; we can implement a more robust
solution, such as reading metrics from disk in a streaming fashion, in
the future.

---------

Signed-off-by: Timothy Seah <[email protected]>
Signed-off-by: Timothy Seah <[email protected]>
Co-authored-by: Timothy Seah <[email protected]>
Co-authored-by: matthewdeng <[email protected]>
Signed-off-by: jugalshah291 <[email protected]>
dstrodtman pushed a commit to dstrodtman/ray that referenced this pull request Oct 6, 2025
…var set (ray-project#54642)

When Ray Train v1 or Ray Tune users report metrics, we persist them in
memory inside CheckpointManager, which can OOM.

This change adds a new env variable,
`TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE`, which makes it so
CheckpointManager only saves the `checkpoint_score_attribute` metric in
memory, reducing the memory footprint from O(checkpoints * metrics) to
O(checkpoints).

Note that when `TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE` is set, we
still persist all the metrics to disk, but when we construct the Tune
[ResultGrid](https://github.com/ray-project/ray/blob/master/python/ray/tune/result_grid.py#L269),
it only contains the `checkpoint_score_attribute`. This is just a
temporary solution to unblock users; we can implement a more robust
solution, such as reading metrics from disk in a streaming fashion, in
the future.

---------

Signed-off-by: Timothy Seah <[email protected]>
Signed-off-by: Timothy Seah <[email protected]>
Co-authored-by: Timothy Seah <[email protected]>
Co-authored-by: matthewdeng <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
elliot-barn pushed a commit that referenced this pull request Nov 10, 2026
## Description

Fixes two bugs in the v1 `_CheckpointManager` (used by Train v1 and Tune
trials) when `TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE` is set.

1. **Nested score attributes are dropped.** The only-store path looked
up `checkpoint_score_attribute` among the top-level metric keys only. A
nested attribute such as `env_runners/episode_return_mean` was not
found, so the checkpoint was stored with `{}` metrics, ranked worst, and
the best checkpoint could be deleted. The lookup now uses
`flatten_dict`, the same as `_get_checkpoint_score`. The stored metrics
use the flat key (`{"a/b": v}`), which `Result.get_best_checkpoint`
already resolves through `unflattened_lookup`.
2. **The latest checkpoint could be deleted right after it was
registered.** `_latest_checkpoint_result` was recorded before the
only-store path rebuilt the result as a new `_TrainingResult`. Deletion
excludes the latest result by object identity, so the rebuilt object was
not protected. This has affected flat keys as well since #54642.
`_latest_checkpoint_result` is now set after the rewrite.

The original issue in this PR, checkpoints with a nested score attribute
being ordered by registration time instead of by score, was fixed on
master by #67901, which inserts every checkpoint by score whenever
`checkpoint_score_attribute` is set. The earlier flattened-score cache
from this PR is no longer included. It isn't needed for correctness, and
adding state to `_CheckpointManager` would break restoring Tune
experiments pickled by older Ray versions.

## Related issues

Related to #54251.

## Additional information

Tests in `python/ray/train/tests/test_checkpoint_manager.py`:
- `test_keep_latest_checkpoint` is parametrized over only-store mode
on/off and over flat-key (`{"nested/score": v}`) and nested (`{"nested":
{"score": v}}`) metrics.
- `test_only_store_score_attr` is parametrized over a top-level,
flat-key and nested score attribute.

Test run:
- `python -m pytest python/ray/train/tests/test_checkpoint_manager.py`:
22 passed.
- With only the `checkpoint_manager.py` change reverted, 3 fail:
`test_keep_latest_checkpoint[...-True]` for both metric shapes (latest
checkpoint deleted) and
`test_only_store_score_attr[nested/score-<nested>-True]` (nested
lookup). The nested cases with only-store off pass on master, confirming
#67901 covers the original sorting bug.
- `pre-commit run` on both files passes.

Not a duplicate: this is the existing community PR, narrowed to what
#67901 did not already fix. AI assistance (Claude Code) was used to
review and narrow the change; the maintainer pushing it reviewed every
line and ran the tests above.

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

---------

Signed-off-by: CesarRodrigu <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Timothy Seah <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants