Skip to content

[BugFix] Fix CEMPlanner NaN actions with top_k=1 - #4734

Merged
bsprenger merged 1 commit into
pytorch:mainfrom
ricardo55ribeiro:fix/cem-singleton-std
Nov 19, 2026
Merged

bsprenger merged 1 commit into
pytorch:mainfrom
ricardo55ribeiro:fix/cem-singleton-std

Conversation

@ricardo55ribeiro

@ricardo55ribeiro ricardo55ribeiro commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fix CEMPlanner returning NaN actions when top_k=1 and optim_steps > 1.

The planner previously called best_actions.std(dim=K_DIM, keepdim=True). PyTorch uses correction=1 by default, so the standard deviation of a single elite candidate is NaN. This nonfinite spread then propagates to sampled actions during the next optimization step.

This change:

  • Uses correction=0 only when top_k=1, producing zero spread for the singleton elite
  • Keeps correction=1 for top_k >= 2, preserving existing multi-elite behavior
  • Documents that subsequent optimization steps do not explore new actions once the singleton spread becomes zero
  • Parameterizes the existing CEM planner test over top_k=2 and top_k=1 and asserts that returned actions are finite

Motivation and Context

Fixes #4732.

The bug was reproduced using TestPlanner.test_CEM_model_free_env on the repository's existing CPU fixture, with optim_steps=2 and batch sizes 3 and 5.

Before the fix, the two top_k=2 cases passed and both top_k=1 cases failed because all returned actions were NaN. The existing action-spec check still returned True for those nonfinite actions.

After the fix, all four parameterized cases pass without the degrees-of-freedom warning

The zero-spread behavior for top_k=1 prevents nonfinite outputs but does not add exploration after the first iteration. This limitation is documented.

  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

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:

.venv\Scripts\python.exe -m pytest -v -s test/modules/test_planners.py::TestPlanner::test_CEM_model_free_env

Result: 4 passed

Planner test module:

.venv\Scripts\python.exe -m pytest -q test/modules/test_planners.py

Result: 22 passed, 6 skipped. The skipped tests require Hydra, which was not installed locally.

git diff --check and git diff --cached --check completed without errors.

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

@pytorch-bot

pytorch-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🔗 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 Failure

As of commit 14b3431 with merge base fdf01c1 (image):

NEW FAILURE - The following job has failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla

meta-cla Bot commented Nov 15, 2026

Copy link
Copy Markdown

Hi @ricardo55ribeiro!

Thank you for your pull request and welcome to our community.

Action Required

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

Process

In 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 CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ PR Title Label Error

PR title must start with a label prefix in brackets (e.g., [BugFix]).

Current title: Fix CEMPlanner NaN actions with top_k=1

Supported Prefixes (case-sensitive)

Your PR title must start with exactly one of these prefixes:

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]).

@ricardo55ribeiro ricardo55ribeiro changed the title Fix CEMPlanner NaN actions with top_k=1 [BugFix] Fix CEMPlanner NaN actions with top_k=1 Nov 15, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 15, 2026
@meta-cla

meta-cla Bot commented Nov 15, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@JonnyFaeth

Copy link
Copy Markdown

Additional numerical regression for 14b3431 below: it checks the selected action, not only finiteness, and protects the unchanged multi-elite correction. It reuses _TwoSequenceEnv and _fixed_planner_candidates, with real planner rollouts and deterministic candidate noise (2 and 6), for unbatched, [2], and [2, 3] inputs.

With one elite the expected first action is 6 and stays 6 on later iterations. With two elites the expected recurrence is mean_next = mean + 4 * std, std_next = sqrt(8) * std (the sample standard deviation of 2 and 6).

  • Head: 12 added cases pass; the complete planner module is 34 passed, 6 Hydra skips.
  • Parent cem.py: the three multi-iteration singleton cases fail with NaNs; 9 controls pass.
  • Mutation changing the new expression to unconditional correction=0: the three multi-iteration two-elite cases fail; 9 controls pass. This catches accidentally changing existing multi-elite behavior.

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 patch
diff --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()

@ricardo55ribeiro

Copy link
Copy Markdown
Contributor Author

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?

@JonnyFaeth

Copy link
Copy Markdown

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 14b3431 and is test-only. The multi-elite mutation check is what gives me confidence that it protects the existing behavior as well as the NaN fix. I’m happy for it to be included with the AI assistance disclosure already noted above.

@JonnyFaeth

Copy link
Copy Markdown

Thank you for incorporating the test and recording the coauthor credit in b6a4ae0. I checked the integrated commit in a clean checkout: the complete planner module is 34 passed, 6 skipped on Windows/Python 3.12.14 with torch 2.11 CPU and TensorDict nightly. The six skips are the existing Hydra-dependent cases; the missing C++ extension and torch-version deprecation warnings remain. No GPU/full-repository claim. Codex assisted with this integration check.

@ricardo55ribeiro

Copy link
Copy Markdown
Contributor Author

Thank you for your independent verification and confirming the results. I really appreciate your contribution and collaboration!

@bsprenger bsprenger left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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!

@ricardo55ribeiro

Copy link
Copy Markdown
Contributor Author

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

@bsprenger
bsprenger merged commit 67c64e9 into pytorch:main Nov 19, 2026
192 of 254 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BugFix CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Integrations/torch_geometric Integrations Modules

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] CEMPlanner returns NaN actions with top_k=1 and multiple optimization steps

3 participants