Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4705
Note: Links to docs will display an error until the docs builds have been completed.
|
|
Friendly ping: CI hasn’t run on this PR yet because the workflows are awaiting maintainer approval. Happy to adjust anything if neccessary! |
|
I added a mixed-lane regression for the documented batched early-stop rule on 467a74d. It wraps two actual The test asserts both lanes stop at the same repeat, their exact accumulated rewards/counts, per-lane done flags 4 added cases pass, and all 4 fail with Test-only patch using the existing fixturediff --git a/test/transforms/test_env_transforms.py b/test/transforms/test_env_transforms.py
index 4e9ddd8b..683e3999 100644
--- a/test/transforms/test_env_transforms.py
+++ b/test/transforms/test_env_transforms.py
@@ -1624,6 +1624,39 @@ class TestFrameSkipTransform(TransformBase):
out[env.reward_key], expected["next", env.reward_key].sum(0)
)
+ @pytest.mark.parametrize("nested", [False, True])
+ @pytest.mark.parametrize("terminal_repeat", [1, 2])
+ def test_frame_skip_mixed_batch_stops_all_lanes(self, nested, terminal_repeat):
+ prefix = ("agent",) if nested else ()
+ env = TransformedEnv(
+ SerialEnv(2, lambda: _StatelessEpisodeEnv(prefix)), FrameSkipTransform(4)
+ )
+ try:
+ initial = env.reset()
+ initial[(*prefix, "action")] = torch.tensor([[2 // terminal_repeat], [3]])
+ before = initial.clone()
+ out = env.step(initial)
+ torch.testing.assert_close(
+ out["next", (*prefix, "count")],
+ torch.tensor([[2], [3 * terminal_repeat]]),
+ )
+ torch.testing.assert_close(
+ out["next", (*prefix, "reward")],
+ torch.tensor(
+ [
+ [2.0 if terminal_repeat == 1 else 3.0],
+ [3.0 * terminal_repeat * (terminal_repeat + 1) / 2],
+ ]
+ ),
+ )
+ for key in env.done_keys:
+ torch.testing.assert_close(
+ out["next", key], torch.tensor([[True], [False]])
+ )
+ assert (out.exclude("next") == before).all()
+ finally:
+ env.close()
+
def test_frame_skip_keeps_next_preset(self):
"""Entries the policy writes in "next" before the step, such as the
next recurrent state, must survive the repeated steps."""
|
In a batched env, the repeats stop for every element as soon as any element is done. No test covered this: stopping only once all elements are done, or checking done after each repeat instead of before it, passed the existing tests. The new test steps a SerialEnv of two stateless counters where one is done on the first or the second step and the other never is. Suggested by JonnyFaeth in pytorch#4705. Co-authored-by: JonnyFaeth <[email protected]>
|
@JonnyFaeth thanks, this was a real gap. No existing test pinned the batched rule: a version of the transform that stops only once every element is done still passes all of them. I added it in 29fe4e2 with you as co-author, trimmed to two cases: done on the first step and done on the second. I left out the nested variant because the existing nested tests already cover that path. On the failing jobs from the 11-17 run: none of them reached |
Description
Fixes #4704.
One commit per problem described in the issue:
_stepchecks the done entries of the last step with_terminated_or_truncated(the helperEnvBasealready uses, which handles nested done keys) and stops if any is set. This matches the loop inGymLikeEnv._step, which breaks ondone.any().parent.step_mdp(tensordict.copy().set("next", next_tensordict)). Envs that keep their state internally behave as before; envs that read it from the tensordict (PendulumEnv, and from reading the codeBraxWrapperandJumanjiWrapper) now takeframe_skipreal steps. The copy leaves the caller's tensordict unchanged. Entries the caller preset in"next", such as the next recurrent state written by an LSTM/GRU policy, are carried over to every repeat:step_mdpdrops"next", and aTensorDictPrimerafter the frame skip would otherwise reset them..A third commit adds a test for the early stop of batched envs.
The class docstring now says that each repeat starts from the state reached so far and that the repetition stops early on done (for any element of a batched env).
Tests
Added to
TestFrameSkipTransform. The expected values come from the plain env, from GymEnv's built-in frame skip, or are worked out by hand, never from the transform.test_frame_skip_stops_at_done: the base env is done after 2 of 4 repeats; the transform must stop there with every done key set (flat and nested keys).test_transform_env_episode_end(gym):GymEnv(Pendulum, frame_skip=3)against the transform for 70 steps across the truncation at base step 200, which lands on the 2nd repeat of the 67th step.test_frame_skip_stateless_env(skip 2 and 3):PendulumEnvagainst the plain env rolled outskipsteps, and the input tensordict must be unchanged.test_frame_skip_stateless_done_on_terminal_step: a small stateless env whose done is set only on the terminal step (flat and nested keys).test_frame_skip_keeps_next_preset: a preset("next", "hidden")must survive the repeats with aTensorDictPrimerafter the frame skip.test_frame_skip_batched_stops_all_elements(third commit, suggested by JonnyFaeth): aSerialEnvof two stateless counters, one done on the 1st or 2nd step and one never done; both must stop at that step. Without it, stopping only once all elements are done, or checking done after each repeat instead of before it, passed the tests above.The tests of the first two commits fail on the code before them. The exception is the preset test, which guards the second commit's own change: it fails if the state advance is done without carrying
"next"over. The third commit only adds a test, and it fails on main.Behavior notes
These are also raised in #4704.
GymLikeEnvuses (done.any()).FrameSkipTransform, e.g.Compose(StepCounter(), FrameSkipTransform(3)), now advances once per base step, so step_count goes 3, 6, 9 instead of 1, 2, 3. Nothing in the repo uses that order, and the auto-appended transform comes first.step_mdpand copy cost about 30 to 40 us per extra repeat in a local CPU timing with no episode ends. On cheap envs (ContinuousActionVecMockEnv,PendulumEnv, gymPendulum-v1) that is +19% to +27% per step withframe_skip=2and +29% to +40% withframe_skip=4; envs with a more expensive step pay a smaller share. I did not add a benchmark since this is a correctness fix, and I can look at reducing this if it matters.Testing
test/transforms,test/envs,test/test_collectors.pyandtest/libs/test_gym.pypass with gymnasium 1.4.0.test/transformspasses in a local copy of the olddeps setup: Python 3.10, torch 2.11, gym 0.13, numpy 1.26, tensordict main.TestFrameSkipTransformpasses with tensordict main and with 0.15.5.TestFrameSkipTransform: 32 passed, 1 skipped), not in the olddeps copy or with tensordict 0.15.5.Not changed here
These are pre-existing and behave the same on main; I can open separate issues for them.
FrameSkipTransformis applied a second time on each repeat.KeyError.Motivation and Context
See #4704: on main the transform keeps stepping after the episode ends (summing rewards from past the end and possibly reporting
done=False), and on stateless envs it re-runs the same transitionframe_skiptimes.Types of changes
Checklist
I used Claude Code (Opus 5.5 xHigh) to help investigate, implement and test this change, and I reviewed all of it.