Repository navigation
Description
Describe the bug
FrameSkipTransform._step has two problems:
- It never looks at the done flags.
GymLikeEnv's built-in frame skip stops as soon asread_donereportsdone.any(); the transform keeps stepping the base env past the end of the episode and sums the rewards of those extra steps. The returneddone/terminatedare those of the last repeated step, so if the env's done flag does not stay set the end of the episode is reported asdone=False. - It calls
parent._step(tensordict)with the original inputtensordicton every repeat. Envs that keep their state internally advance anyway, but envs that read their state from the tensordict re-run the same transitionframe_skiptimes: the next state is only one step ahead and the reward isframe_skiptimes 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
- Both envs in part 1 should stop at the step where the episode ends: 2 base steps taken and
done: True, asGymLikeEnv's frame skip does (gym_like.py, the loop in_stepthat breaks onread_done'sdo_break). FrameSkipTransform(n)should give the same result as applying the actionntimes, 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 thanGymEnv("CartPole-v1", frame_skip=4)on the steps where an episode ends: withset_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 withPendulum-v1, which is truncated at 200 base steps: withframe_skip=3(200 is not a multiple of 3) and the same seed and actions, the transform differs fromGymEnv("Pendulum-v1", frame_skip=3)at exactly the outer steps where an episode ends (the 67th and 134th in a 150-step rollout), whileframe_skip=2and4match.sota-implementations/dreamer/dreamer_utils.pyapplies an explicitFrameSkipTransformto gym envs, so this path is used. common.py(around lines 344-356) adds aFrameSkipTransformautomatically to wrappers withframe_skip > 1and_has_frame_skip = False.JumanjiWrapperandBraxWrapperboth fall in that group and both readtensordict.get("state")in_stepwithout 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); thePendulumEnvrepro goes through the same code path.- The existing
test_transform_envcompares againstGymEnv(Pendulum, frame_skip=n)for 10 steps, which never terminates, so neither problem is covered. I found noframe_skiptest 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
GymLikeEnvuses (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
kaanutkuy commentedon Nov 7, 2026
/assign