Skip to content

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

Closed

Description

@ricardo55ribeiro

Describe the bug

CEMPlanner accepts top_k=1, but with optim_steps=2 it returns NaN actions.

In torchrl/modules/planners/cem.py, the selected action sequences update the sampling distribution using:

best_actions.std(dim=K_DIM, keepdim=True)

PyTorch's default correction=1 makes the standard deviation undefined when the selected-candidate axis has length one. PyTorch produces NaN standard deviations, which are then used when sampling the next set of candidate actions.

The constructor does not reject top_k=1, and its documentation does not specify a minimum of two.

To Reproduce

Reproduced on TorchRL main commit fdf01c1454231e30080ecd5119898c2c5bf9f46f using the existing test TestPlanner.test_CEM_model_free_env in test/modules/test_planners.py.

  1. Add this decorator directly above the test method, and add top_k as a test-method argument:

    @pytest.mark.parametrize("top_k", [2, 1])
    def test_CEM_model_free_env(self, device, batch_size, top_k, seed=1):
  2. In the existing CEMPlanner(...) call, change only top_k=2 to top_k=top_k. Keep planning_horizon=10, optim_steps=2, num_candidates=100 and the original batch sizes 3 and 5. The existing test seeds PyTorch with torch.manual_seed(1) and constructs a fresh MockBatchedUnLockedEnv for each case.

  3. Immediately after td = planner(td), add:

    action = td.get("action")
    finite = torch.isfinite(action).all().item()
    in_spec = env.action_spec.is_in(action)
    print(
        f"top_k={top_k}, batch_size={batch_size}, "
        f"finite={finite}, in_spec={in_spec}, action={action}"
    )
    assert finite, f"CEMPlanner returned nonfinite actions for top_k={top_k}"

    Keep the original action-shape, action-spec membership and TensorDict-preservation assertions.

  4. Run the following command from the repository root in Windows Command Prompt:

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

Observed results:

top_k Batch size Finite returned action action_spec.is_in(action) Test
2 3 True True PASSED
2 5 True True PASSED
1 3 False True FAILED
1 5 False True FAILED

The top_k=1 actions consisted entirely of NaN values in both batch sizes. PyTorch emitted the warning below at torchrl/modules/planners/cem.py:221:

UserWarning: std(): degrees of freedom is <= 0. Correction should be strictly less than the reduction factor (input numel divided by output numel).

Pytest summary:

2 failed, 2 passed, 2 warnings in 0.78s

The existing action_spec.is_in(action) assertion does not detect these nonfinite actions: it returns True for the tested NaN outputs.

Expected behavior

An accepted top_k value should not cause CEMPlanner to return nonfinite actions when the environment and initial candidate actions are finite. Alternatively, if singleton selection is unsupported by design, the constructor should reject top_k=1 with a clear validation error and document the restriction.

System info

Installed from the checked-out TorchRL source in editable mode, using a Python 3.12 virtual environment on Windows 11 x64.

Command from the official TorchRL bug-report template, run with the environment's Python:

.venv\Scripts\python.exe -c "import torchrl, numpy, sys; print(torchrl.__version__, numpy.__version__, sys.version, sys.platform)"

Actual output:

0.15.0+gfdf01c14 2.5.4 3.12.10 (tags/v3.12.10:0cc8128, Apr  8 2025, 12:21:36) [MSC v.1943 64 bit (AMD64)] win32

Additional dependency versions verified in the same virtual environment:

  • PyTorch: 2.15.0+cpu
  • TensorDict: 0.15.0+g74a8cd2b
  • pytest: 9.2.0
  • CPU-only test: PyTorch reported torch.cuda.is_available() == False; the test uses torch.manual_seed(1)

Reason and Possible fixes

One option is to use correction=0 only when top_k=1, giving the singleton a zero population spread. Later optimization iterations would then repeat the selected sequence rather than sampling new sequences. This would preserve the current standard deviation calculation for top_k >= 2.

Another option is to reject top_k=1 explicitly and document a minimum of two elites.

Using correction=0 for every top_k would change the sampling distribution for existing multi-elite configurations, so that broader change is not necessary for this bug.

I can contribute a focused fix and regression test once the intended singleton behavior is established.

Checklist

  • I have checked that there is no similar issue in the repo (required)
  • I have read the documentation (required)
  • I have provided a minimal working example to reproduce the bug (required)

Activity

  1. added
    bug
    on Nov 15, 2026
  2. ricardo55ribeiro commented on Nov 15, 2026

    @ricardo55ribeiro
    ContributorAuthor

    /assign

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions