Skip to content

[BUG] FrameSkipTransform keeps stepping after done and re-runs the same transition for stateless envs #4704

Open

Description

@kaanutkuy

Describe the bug

FrameSkipTransform._step has two problems:

  1. It never looks at the done flags. GymLikeEnv's built-in frame skip stops as soon as read_done reports done.any(); the transform keeps stepping the base env past the end of the episode and sums the rewards of those extra steps. The returned done / terminated are those of the last repeated step, so if the env's done flag does not stay set the end of the episode is reported as done=False.
  2. It calls parent._step(tensordict) with the original input tensordict on every repeat. Envs that keep their state internally advance anyway, but envs that read their state from the tensordict re-run the same transition frame_skip times: the next state is only one step ahead and the reward is frame_skip times the single-step reward.

To Reproduce

import torch
from torchrl.envs import FrameSkipTransform, TransformedEnv
from torchrl.envs.custom import PendulumEnv
from torchrl.envs.utils import step_mdp
from torchrl.testing.mocking_classes import CountingEnv


# 1. the base env keeps being stepped after the episode ended, and done can be lost
class DoneOnlyOnFinalStep(CountingEnv):
    """Like CountingEnv, but done is True only on the step where the episode ends."""

    def _step(self, tensordict):
        out = super()._step(tensordict)
        flag = self.count == self.max_steps + 1
        out["done"] = flag.clone()
        out["terminated"] = flag.clone()
        return out


for cls in (CountingEnv, DoneOnlyOnFinalStep):
    env = TransformedEnv(cls(max_steps=1), FrameSkipTransform(5))  # the episode ends on base step 2
    td = env.reset()
    td["action"] = torch.ones(1, dtype=torch.bool)
    out = env.step(td)
    print(cls.__name__, "| base steps taken:", env.base_env.count.item(), "| done:", out["next", "done"].item())

# 2. stateless env (state lives in the tensordict): the state is not advanced between the skipped frames
torch.manual_seed(0)
base = PendulumEnv()
base.set_seed(0)
td = base.reset()
td["action"] = torch.tensor([1.0])

# reference: apply the action 3 times with the plain env, feeding each next state back in
ref, reward = td.clone(), 0.0
for _ in range(3):
    out = base.step(ref.clone())
    reward = reward + out["next", "reward"]
    ref = step_mdp(out, keep_other=True, exclude_action=False)

env = TransformedEnv(PendulumEnv(), FrameSkipTransform(3))
out = env.step(td.clone())
print("expected th, reward:", ref["th"].item(), reward.item())
print("got      th, reward:", out["next", "th"].item(), out["next", "reward"].item())

Output on main (003c5f4):

CountingEnv | base steps taken: 5 | done: True
DoneOnlyOnFinalStep | base steps taken: 5 | done: False
expected th, reward: 0.10196471214294434 -0.14805155992507935
got      th, reward: 0.009919881820678711 -0.09099115431308746

In part 2 the "got" state equals the state after a single plain step (th=0.00992) and the "got" reward is exactly 3x the single-step reward (-0.03033).

Expected behavior

  1. Both envs in part 1 should stop at the step where the episode ends: 2 base steps taken and done: True, as GymLikeEnv's frame skip does (gym_like.py, the loop in _step that breaks on read_done's do_break).
  2. FrameSkipTransform(n) should give the same result as applying the action n times, whether the env keeps its state internally or in the tensordict.

System info

  • Installed from source (editable) at 003c5f4; torchrl.__version__ reports the commit of the build, not of the code
  • torch 2.15.0+cu132, tensordict 0.15.0+gcd3eeaa6, gymnasium 1.4.0
0.14.0+g0553f1cd3 2.5.4 3.12.16 (main, Oct 26 2026, 15:28:01) [GCC 15.2.0] linux

Additional context

  • With gymnasium, TransformedEnv(GymEnv("CartPole-v1"), FrameSkipTransform(4)) returns a different observation than GymEnv("CartPole-v1", frame_skip=4) on the steps where an episode ends: with set_seed(0), torch.manual_seed(0) and random actions (env.rollout(30, break_when_any_done=False)), 6 episodes end and the observation differs on 5 of the 30 outer steps. The reward and done flags still match there, but only because CartPole returns a reward of 0 after termination and its terminated flag stays set. The same happens deterministically with Pendulum-v1, which is truncated at 200 base steps: with frame_skip=3 (200 is not a multiple of 3) and the same seed and actions, the transform differs from GymEnv("Pendulum-v1", frame_skip=3) at exactly the outer steps where an episode ends (the 67th and 134th in a 150-step rollout), while frame_skip=2 and 4 match. sota-implementations/dreamer/dreamer_utils.py applies an explicit FrameSkipTransform to gym envs, so this path is used.
  • common.py (around lines 344-356) adds a FrameSkipTransform automatically to wrappers with frame_skip > 1 and _has_frame_skip = False. JumanjiWrapper and BraxWrapper both fall in that group and both read tensordict.get("state") in _step without modifying it, so I expect problem 2 to hit them. I read this from the code and have not run it (no jax installed here); the PendulumEnv repro goes through the same code path.
  • The existing test_transform_env compares against GymEnv(Pendulum, frame_skip=n) for 10 steps, which never terminates, so neither problem is covered. I found no frame_skip test for Brax or Jumanji.

Reason and Possible fixes

In _step, before each repeat: stop if any done / terminated / truncated entry is set (the _terminated_or_truncated helper that EnvBase already uses), then build the next input from the state reached so far with parent.step_mdp, on a copy so that the caller's tensordict and any transform after this one see no change. Entries the caller preset in "next" (for example the next recurrent state written by the policy) have to be carried over, since step_mdp drops them and a TensorDictPrimer after the frame skip would then reset them. I have this implemented with regression tests whose expected values come from stepping the plain env or from GymEnv's built-in frame skip, and will open a PR shortly.

Two design points I would like your view on:

  • For a batched parent, the loop stops as soon as any sub-env is done, so the others get a shorter skip on that step. This is the same rule GymLikeEnv uses (done.any()); per-element masking would be a larger change.
  • A transform that keeps its state in the tensordict and sits before FrameSkipTransform (e.g. Compose(StepCounter(), FrameSkipTransform(3))) now advances per base step: step_count goes 3, 6, 9 instead of 1, 2, 3, matching the base env's count. I found no use of that order outside the tests; the order produced by the auto-append (frame skip first) is unchanged.

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 7, 2026
  2. kaanutkuy commented on Nov 7, 2026

    @kaanutkuy
    Author

    /assign

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

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions