Repository navigation
[BugFix] Fix CEMPlanner NaN actions with top_k=1 - #4734
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4734
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New FailureAs of commit 14b3431 with merge base fdf01c1 ( NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
| Prefix | Label Applied | Example |
|---|---|---|
[Algorithm] |
new algo | [Algorithm] Add new RL objective |
[BE] |
BE | [BE] Improve error messages |
[Benchmark] or [Benchmarks] |
Benchmarks | [Benchmark] Add collector benchmark |
[BugFix] |
BugFix | [BugFix] Fix memory leak in collector |
[Example] or [Examples] |
Examples | [Example] Add training script |
[Feature] |
Feature | [Feature] Add new optimizer |
[Doc] or [Docs] |
Documentation | [Doc] Update installation guide |
[Refactor] |
Refactoring | [Refactor] Clean up module imports |
[CI] |
CI | [CI] Fix workflow permissions |
[Test] or [Tests] |
Tests | [Tests] Add unit tests for buffer |
[Trainer] or [Trainers] |
Trainers | [Trainer] Add trainer config |
[Environment] or [Environments] |
Environments | [Environments] Add Gymnasium support |
[Data] |
Data | [Data] Fix replay buffer sampling |
[LLM] |
llm/ | [LLM] Add reward model integration |
[Minor] |
small change | [Minor] Fix typo in error message |
[Performance] or [Perf] |
Performance | [Performance] Optimize tensor ops |
[BC-Breaking] |
bc breaking | [BC-Breaking] Remove deprecated API |
[Deprecation] |
Deprecation | [Deprecation] Mark old function |
[Algorithm] or [Algorithms] |
new algo | [Algorithm] Add new objective |
[Quality] |
Quality | [Quality] Fix typos and add codespell |
[Versioning] |
versioning | [Versioning] Bump release version |
[WIP] |
WIP | [WIP] Draft implementation |
Note: Common variations like singular/plural are supported (e.g., [Doc] or [Docs]).
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
Additional numerical regression for 14b3431 below: it checks the selected action, not only finiteness, and protects the unchanged multi-elite correction. It reuses With one elite the expected first action is 6 and stays 6 on later iterations. With two elites the expected recurrence is
Both source controls were restored. Ruff lint/format and diff checks pass. Windows/Python 3.12.14, torch 2.11 CPU, TensorDict nightly; existing missing C++ extension and torch-version deprecation warnings remain. No GPU, trained world model, or full-repository claim. Codex assisted with this independent test and report. Test-only patchdiff --git a/test/modules/test_planners.py b/test/modules/test_planners.py
index d4782bf9..966867ac 100644
--- a/test/modules/test_planners.py
+++ b/test/modules/test_planners.py
@@ -523,3 +523,26 @@ class TestTdMpc2Planner:
if __name__ == "__main__":
args, unknown = argparse.ArgumentParser().parse_known_args()
pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)
+
+
+@pytest.mark.parametrize("batch_size", [[], [2], [2, 3]])
+@pytest.mark.parametrize("top_k", [1, 2])
+@pytest.mark.parametrize("optim_steps", [1, 3])
+def test_cem_elite_statistics_oracle(batch_size, top_k, optim_steps):
+ env = _TwoSequenceEnv()
+ planner = CEMPlanner(
+ env, planning_horizon=3, optim_steps=optim_steps, num_candidates=2, top_k=top_k
+ )
+ initial = env.reset(TensorDict({}, batch_size=batch_size, device="cpu"))
+ low = torch.full((3, 1), 2.0)
+ high = torch.full((3, 1), 6.0)
+ with _fixed_planner_candidates("cem", low, high):
+ result = planner(initial.clone()).get("action")
+ mean, std = 0.0, 1.0
+ for _ in range(optim_steps):
+ if top_k == 1:
+ mean, std = mean + 6.0 * std, 0.0
+ else:
+ mean, std = mean + 4.0 * std, std * (8.0**0.5)
+ torch.testing.assert_close(result, torch.full((*batch_size, 1), mean))
+ assert torch.isfinite(result).all()
|
|
Thanks for the additional testing and for the detailed validation. The numerical regression test looks valuable, especially the check that the multi-elite correction remains unchanged. I'd be happy to incorporate it into this PR and credit you as a co-author of the test commit, if you're interested. Would that work for you? |
|
Yes, that works for me—thank you for offering to incorporate it and credit the contribution. Please credit Jonathan D Faeth (@JonnyFaeth). Feel free to adapt the test to the module’s conventions; preserving the analytical singleton and multi-elite assertions is the important part. The patch in my previous comment is against |
|
Thank you for incorporating the test and recording the coauthor credit in |
|
Thank you for your independent verification and confirming the results. I really appreciate your contribution and collaboration! |
bsprenger
left a comment
There was a problem hiding this comment.
The fix LGTM @ricardo55ribeiro , thanks for spotting that. The first test change also looks good to me!
I do not see any value in the 2nd test commit. The fix is already tested as part of the first one. The 2nd commit adds very little value beyond it, I do not think it is worth 12 additional test cases. Can you remove that commit?
@JonnyFaeth while I appreciate your enthusiasm in contributing to the repo, having automated agent PR reviews is not helpful for the maintainer team. We can run our own agents if we wanted to. The highest value contributions are real users who participate in issues, discuss bugs and fixes etc. I ask that you please refrain from having your agent automatically reviewing others' PRs, especially when not requested. Thanks!
b6a4ae0 to
14b3431
Compare
|
Thank you for reviewing the PR and for the positive feedback for the fix ! I've just removed the second commit as requested and updated the description. The PR now only contains the original bug fix. I also reran the planner test module locally, with 22 passed and 6 skipped |
Description
Fix
CEMPlannerreturningNaNactions whentop_k=1andoptim_steps > 1.The planner previously called
best_actions.std(dim=K_DIM, keepdim=True). PyTorch usescorrection=1by default, so the standard deviation of a single elite candidate isNaN. This nonfinite spread then propagates to sampled actions during the next optimization step.This change:
correction=0only whentop_k=1, producing zero spread for the singleton elitecorrection=1fortop_k >= 2, preserving existing multi-elite behaviortop_k=2andtop_k=1and asserts that returned actions are finiteMotivation and Context
Fixes #4732.
The bug was reproduced using
TestPlanner.test_CEM_model_free_envon the repository's existing CPU fixture, withoptim_steps=2and batch sizes 3 and 5.Before the fix, the two
top_k=2cases passed and bothtop_k=1cases failed because all returned actions wereNaN. The existing action-spec check still returnedTruefor those nonfinite actions.After the fix, all four parameterized cases pass without the degrees-of-freedom warning
The zero-spread behavior for
top_k=1prevents nonfinite outputs but does not add exploration after the first iteration. This limitation is documented.Types of changes
Testing
Executed on Windows 11 x64 with Python 3.12.10, PyTorch 2.15.0+cpu, TensorDict 0.15.0+g74a8cd2b and TorchRL built from source.
Focused regression:
Result:
4 passedPlanner test module:
Result:
22 passed, 6 skipped. The skipped tests require Hydra, which was not installed locally.git diff --checkandgit diff --cached --checkcompleted without errors.Checklist