Repository navigation
fix(tune): release per-trial logger state on trial end to bound driver memory - #66699
SIDDARTHAREDDY8 wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Code Review
This pull request addresses a memory leak issue where finished trials are retained in memory by the default loggers and progress callbacks, leading to linear RSS growth. It ensures that trial states, config snapshots, and continue flags are properly discarded upon trial completion or error. Additionally, regression tests are introduced to verify proper cleanup. The reviewer suggests improving the test assertions by checking against an empty list of alive references instead of using assertTrue(all(...)), which will provide much more descriptive error messages on failure by identifying the leaked Trial objects.
| # cleanup the trials must be collectable. | ||
| del trial | ||
| gc.collect() | ||
| self.assertTrue(all(ref() is None for ref in refs)) |
There was a problem hiding this comment.
Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.
self.assertEqual([ref() for ref in refs if ref() is not None], [])| self.assertEqual(len(logger._trial_csv), 0) | ||
| del trial | ||
| gc.collect() | ||
| self.assertTrue(all(ref() is None for ref in refs)) |
There was a problem hiding this comment.
Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.
self.assertEqual([ref() for ref in refs if ref() is not None], [])| self.assertEqual(len(bookkeeping), 0) | ||
| del trial | ||
| gc.collect() | ||
| self.assertTrue(all(ref() is None for ref in refs)) |
There was a problem hiding this comment.
Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.
self.assertEqual([ref() for ref in refs if ref() is not None], [])There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 8d33c0f. Configure here.
c3f39e6 to
30819c1
Compare
…ni-code-assist review) Signed-off-by: SIDDARTHA REDDY <[email protected]>
30819c1 to
a9aa7f8
Compare
|
Addressed the gemini-code-assist review nit: the three regression tests now assert |
|
This pull request has been automatically marked as stale because it has not had 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. |
|
Still active on this one, the stale flag is just inactivity on my side. The cursor[bot] feedback above is addressed in the current head: |
|
Just checking whether there is anything you would like adjusted here — happy to revise. |
…67610) ## Summary Adds the missing docstrings, `Args:` entries, and `Returns:` sections on public Ray Tune symbols in `search`, `stopper`, `trainable`, `context`, `utils`, `execution`, and `logger`. Each describes existing behavior, written from the code. It follows #67608, which covers `ray.tune.schedulers`. Stacked on #67608: this PR targets that branch so the correctness PR above it can build on both, and retargets to `master` once #67608 merges. The two PRs share no files. ## Before Across these subpackages, 23 public symbols had no docstring, 43 parameters had no `Args:` entry, and 14 callables that annotate a return type had no `Returns:` section. The sampling functions such as `tune.uniform`, `tune.quniform`, and `tune.randint` described their bounds in prose but had no `Args:` block. ## After 19 of the 23 docstrings, 35 of the 43 parameters, and 10 of the 14 `Returns:` sections are documented. Where a base class lacked the docstring its overrides inherit, this PR documents the base instead of each override: `Searcher.get_state`, `Searcher.set_state`, `Stopper.__call__`, and `Stopper.stop_all`. That covers both `ConcurrencyLimiter` classes and `Repeater`, and `CombinedStopper`. Behavior is unchanged. The diff touches only docstrings, which the guard below confirms. ## Not in this PR - **Four methods with untyped signatures:** `BasicVariantGenerator.set_state` and `save_to_dir`, `FunctionStopper.is_valid_function`, and `Trainable.reset`. pydoclint, run with `--arg-type-hints-in-signature`, rejects an `Args:` section on a signature without type hints, so documenting these 6 parameters needs a signature change. That signature change is in #67612, since this PR is docstring-only. `BasicVariantGenerator.set_state` and `FunctionStopper.is_valid_function` get a docstring here, without sections. - **`TuneContext.get_trial_name`, `get_trial_id`, `get_trial_resources`, and `get_trial_dir`:** these take their docstrings at runtime from `ray.train._internal.session` through `@_copy_doc`, so they render documented already. A docstring written on the method would be overwritten. Their `Returns:` sections belong on the `session` functions, which Ray Train owns. - **`Repeater.on_trial_complete`:** #67013 changes this method and edits the same docstring, so its `Args:` entries are left to land after that PR. ## For reviewers These docstrings are worth a close read: - `Verbosity` documents the four levels as the `verbose` argument of `tune.run` describes the legacy output, and notes that the default output treats levels 2 and 3 the same (`get_air_verbosity` in `tune/experimental/output.py`). - `PlacementGroupFactory.__call__` is deprecated. Its new docstring says so and points to `to_placement_group()`. - `BasicVariantGenerator.get_state` documents that it returns `False` instead of a state when any variants are generated lazily. ## Duplicate check No open PR documents these symbols. Open PRs #66923 (`stopper.py`), #66699 (`logger/json.py`), and #58359 (`utils/util.py`) change code in files this PR touches, and all three apply cleanly on top of this branch. #67013 (`repeater.py`) also applies cleanly, because this PR leaves the method it changes alone. ## Testing - `python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base upstream/master HEAD)"`: `docstring-only guard: 15 file(s), docstrings only.` - The full pre-commit suite on the changed files, including ruff, black, pydoclint, and the docstyle hook: passed. - `ci/ray_ci/doc/api_param_coverage.py`, run over `python/ray/tune/` outside `schedulers/`: 43 undocumented parameters on `master`, 8 on this branch: 6 on the four untyped signatures and 2 on `Repeater.on_trial_complete`, all listed above. - The commit carries an `@rtd-build` line, so the Read the Docs preview renders the changed docstrings. AI assistance (Claude Code) was used to prepare 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]>

Fixes #64231
Problem: The default Tune auto loggers pin every finished trial:
JsonLoggerCallback._trial_configsandCSVLoggerCallback._trial_continueare dicts keyed byTrialobjects that are never released, so driver RSS grows linearly with completed trials (confirmed via tracemalloc + gc profiling).Fix: Release per-trial state on trial end — both dicts are popped in
log_trial_end(including the early-return path where no result file was opened).TrialProgressCallbackgains_discard_trial_state(), called fromon_trial_errorandon_trial_complete, clearing_completed_trials,_last_print,_last_print_iteration,_last_result_str, and_last_result. TBX/Aim loggers already cleaned up;TuneController's retained finished trials are by design (ResultGrid/ExperimentAnalysis) and out of scope.Tests: new unit tests with weakref pinning checks proving trial objects are collectable after
log_trial_end, plus a mechanism-level repro driving the real default callback stack through 3000 trial lifecycles showing flat memory.