Skip to content

[BUG] shifted=True value estimators bootstrap through a real termination on the last retained step #4789

Backlog

Description

@0xrichardlu

Describe the bug

With shifted=True, ValueEstimatorBase._prepare_shifted_tensordict marks the last retained transition of each row as a synthetic batch boundary:

# torchrl/objectives/value/advantages.py:1002-1009 (527edeb, same in v0.14.1 and v0.15.0)
tensordict.set(("next", self.tensor_keys.done), done.masked_fill(done_mask, True))
tensordict.set(("next", self.tensor_keys.terminated), terminated.masked_fill(done_mask, False))

Setting terminated=False there also erases a real termination on that step. The step is then treated as a truncation, and its target bootstraps gamma * V(terminal obs) where it should be r. With GAE / TD(λ) / TD(1) the error then propagates backwards through the rest of that episode. This affects GAE, TD0Estimator, TD1Estimator and TDLambdaEstimator, and nothing warns.

It happens whenever a row contains enough time-limit resets to use up shifted_budget (default 1) and the last retained step is a real termination.

To reproduce

import torch
from torch import nn
from tensordict import TensorDict
from tensordict.nn import TensorDictModule
from torchrl.objectives.value import TD0Estimator, GAE

T = 4
done = torch.tensor([1, 0, 1, 0], dtype=torch.bool).view(1, T, 1)  # truncation at t=0
term = torch.tensor([0, 0, 1, 0], dtype=torch.bool).view(1, T, 1)  # real termination at t=2
td = TensorDict({"obs": torch.randn(1, T, 1), "next": {"obs": torch.randn(1, T, 1),
     "reward": torch.zeros(1, T, 1), "done": done, "terminated": term}}, [1, T])
net = TensorDictModule(nn.Linear(1, 1), ["obs"], ["state_value"])
nn.init.zeros_(net.module.weight); nn.init.constant_(net.module.bias, 10.0)  # V == 10
for Est, kw in [(TD0Estimator, {}), (GAE, dict(lmbda=0.95))]:
    a = Est(gamma=0.9, value_network=net, shifted=False, **kw)(td.clone())
    b = Est(gamma=0.9, value_network=net, shifted=True, **kw)(td.clone())
    print(Est.__name__, a["value_target"].flatten().tolist(), b["value_target"].flatten().tolist())

Output:

TD0Estimator [9.0, 9.0, 0.0, 9.0] [9.0, 9.0, 9.0, 0.0]
GAE          [9.0, 0.45, 0.0, 9.0] [9.0, 8.145, 9.0, 0.0]

shifted_valid is [True, True, True, False], so t=2 is a retained sample. At t=2 the target is 9.0 instead of 0.0. With GAE, t=1 is also wrong (8.145 instead of 0.45).

Expected behavior

On retained samples, shifted=True should give the same targets as shifted=False. The synthetic boundary only needs done=True. A real terminated=True must be kept.

Impact

I simulated 4096 envs, T=50, γ=0.99, λ=0.95, with per-step termination and truncation probabilities:

p(term) / p(trunc) wrong retained samples rows affected mean abs. error on wrong samples
0.02 / 0.005 0.09% 0.24% 2.7 (target std 3.1)
0.02 / 0.02 0.38% 1.25% 2.9
0.05 / 0.02 0.65% 2.8% 3.2

The errors are always in the same direction: states that lead to a termination (e.g. a robot falling) get overestimated values. This setting is the default in examples/collectors/isaaclab_rnn_ppo_memory.py (--gae-shifted) and hard-coded in examples/microduck/ppo_mujoco.py:811.

The test reference _shifted_reference in test/objectives/test_values.py has the same terminated[last_valid] = False, but the test data there never terminates on the last retained step, so this case was not covered.

System info

torchrl main @ 527edeb (also present in v0.14.1 and v0.15.0), CPU, Windows, Python 3.12.

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions