Skip to content

Masked variance: centered two-pass moments; legacy wrappers on the gymnasium 5-tuple contract - #379

Open
ViktorM wants to merge 3 commits into
masterfrom
VM/fix/masked-variance-legacy-wrappers
Open

ViktorM wants to merge 3 commits into
masterfrom
VM/fix/masked-variance-legacy-wrappers

Conversation

@ViktorM

@ViktorM ViktorM commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

Two items deferred from #377.

  • Masked moments (torch_ext.get_mean_var_with_masks): the one-pass E[x^2] - E[x]^2 variance goes negative in float32 for nearly constant inputs; sqrt then turned every normalized advantage into NaN and the next update into NaN weights (a real agent on the validity-masked fixture reproduces it with constant advantages of 0.7 or 1.0). The path runs for every RNN rollout and every next-step-autoreset env, and the same helper feeds the masked RunningMeanStd and the masked diagnostics. Now a centered two-pass variance with the same clamps for 0/1 valid rows. Tests cover constant input, offsets up to 1000, multi-column pooled variance, degenerate masks, and prepare_dataset plus one optimizer step on a real agent.
  • Legacy wrappers on the gymnasium contract: wrappers.py imports gymnasium but fifteen wrapper classes still returned obs-only resets and 4-tuples, while RayWorker unpacks (obs, info) and 5-tuples, so every route built on them was dead (atari_gym, smac*, the Cnn walkers, TimeLimit). All converted: TimeLimit expiry is truncated (and no longer clobbers an inner truncation's time_outs), EpisodicLifeEnv life loss is terminated, MaxAndSkipEnv stops on either flag, reset kwargs (seeds) forward through the stack. 38 tests on CartPole plus synthetic ALE-shaped and SMAC-shaped envs, including RayWorker round trips. The dm_control RAY route is retired (zero configs; the gymnasium and envpool routes cover them). The CarRacing route is keyed to the -v3 id gymnasium actually registers.

Not verified here: real Atari (no ale_py) and SMAC (no StarCraft II); both are covered by synthetic stand-ins only. Open decision: pin SMAC v1 to rl-games 1.6.5 like Isaac Gym, or ship the routes API-correct but unverified.

Validation: 272 passed / 2 skipped on master 7ab5039.

🤖 Generated with Claude Code

ViktorM and others added 3 commits September 13, 2026 00:09
…ve and NaN'd PPO updates)

get_mean_var_with_masks computed Var as E[x^2] - E[x]^2, which cancels
catastrophically in float32 whenever the spread is small relative to the
mean: sixteen advantages of 0.1 with fifteen valid rows gave -9.98e-10,
sqrt made every normalized advantage NaN, and one optimizer step made the
parameters NaN. With a real agent on the validity-masked fixture, constant
advantages of 0.7 or 1.0 reproduce it. The masked path runs for every RNN
rollout and every next-step-autoreset env, and the same helper feeds the
masked RunningMeanStd and the masked diagnostics. Even without going
negative the old form was inaccurate at large offsets (1% error at
mean 100, std 0.1).

The variance is now the sum of centered squared deviations over the valid
elements divided by (n_valid - 1), clamped as before for 0/1 valid rows.
Tests cover constant input, offsets up to 1000, multi-column pooled
variance, degenerate masks, and prepare_dataset plus one update on a real
agent.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…contract

rl_games/common/wrappers.py imports gymnasium but a dozen wrappers still
implemented the pre-gymnasium API (reset() -> obs, step() -> 4-tuple), while
RayWorker unpacks `obs, info = env.reset()` and the 5-tuple from step(). Every
registered route that composes these wrappers was therefore dead on arrival:
atari_gym (7 shipped configs), smac (48), smac_cnn (8), smac_v2 (3),
BipedalWalkerCnn-v3, BipedalWalkerHardcoreCnn-v3, CarRacing-v2 and
multiwalker_env. `RayWorker(FrameStack(gym.make('CartPole-v1'), 4, False))`
failed on the first reset.

Converted to reset(**kwargs) -> (obs, info) and step() -> (obs, reward,
terminated, truncated, info): InfoWrapper, NoopResetEnv, FireResetEnv,
EpisodicLifeEnv, EpisodeStackedEnv, MaxAndSkipEnv, FrameStack,
BatchedFrameStack, BatchedFrameStackWithStates, ReallyDoneWrapper,
AllowBacktracking, StickyActionEnv, MontezumaInfoWrapper, TimeLimit and
ImpalaEnvWrapper. The _parse_reset_result/_parse_step_result down-converters
are gone; wrappers now forward reset kwargs (seeding works through the stack)
and the redundant pass-through step() overrides were dropped in favour of
gymnasium's Wrapper.

terminated vs truncated is chosen per wrapper, since getting it wrong silently
corrupts value targets:

  * TimeLimit: expiry sets truncated, never terminated, and info['time_outs']
    now mirrors the final truncated flag instead of being forced to False and
    then True -- an inner truncation is no longer clobbered into time_outs
    False. A None max_episode_steps no longer raises.
  * EpisodicLifeEnv: a lost life sets terminated (no value to bootstrap);
    was_real_done is terminated OR truncated, so a time-limited episode ends
    the life bookkeeping too. The no-op reset step falls back to a real reset
    if it ends the game (SB3 parity).
  * MaxAndSkipEnv: the skip loop breaks on terminated OR truncated and returns
    both flags unchanged.
  * NoopResetEnv/FireResetEnv: reset loops consume (obs, info) and the 5-tuple
    and re-reset on either flag.
  * EpisodeStackedEnv: the anti-stall cut resets the env in place, so the obs
    returned belongs to the next episode and there is nothing to bootstrap
    from -- reported as terminated, matching its -1 penalty.
  * ReallyDoneWrapper: only running out of lives terminates; it never
    truncates.
  * BatchedFrameStack/BatchedFrameStackWithStates forward SMAC's per-agent
    terminated/truncated arrays untouched.

RayWorker's contract is unchanged (it still injects info['time_outs'] from
truncated, scalar or array, and returns the merged done).

Retires the dm_control route: create_dm_control_env, DMControlWrapper and
DMControlObsWrapper are deleted along with the 'dm_control' registration. Zero
shipped configs use it -- rl_games/configs/dm_control/*.yaml already run
through env_name: gymnasium (dm_control/cartpole-balance-v0 via shimmy) or
env_name: envpool. It was also the only route built on the dead dm2gym
package. The other routes are kept and fixed, not retired.

Our own env classes on these routes (SMACEnv, MultiDiscreteSmacWrapper,
SMACEnvV2, MultiWalker) were already on the gymnasium contract and are
unchanged.

tests/test_legacy_wrappers.py adds 38 tests (1 skipped without pettingzoo)
built on synthetic envs -- a fake ALE env exposing unwrapped.ale.lives() and
get_action_meanings(), and a SMAC-shaped multi-agent env -- so they need no
ale_py, ray, smac or pettingzoo: per-wrapper contract, the RayWorker+FrameStack
and RayWorker+BatchedFrameStackWithStates round trips with auto-reset, nested
MaxAndSkipEnv(InfoWrapper(CartPole)), the TimeLimit truncation semantics, the
EpisodicLifeEnv life-loss/no-op-reset behaviour, the full wrap_deepmind /
make_atari_deepmind / make_car_racing chains, and the batched stack shapes.
Suite: 214 passed / 1 skipped before, 252 passed / 2 skipped after.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The RAY route was keyed and built as CarRacing-v2, which gymnasium 1.x no
longer registers (only CarRacing-v3 exists), so it raised NameNotFound
before any wrapper ran. The shipped carracing_ppo.yaml already names
CarRacing-v3 and, being unregistered, fell through to the unwrapped classic
path instead of the make_car_racing chain it was written for. The route is
now keyed CarRacing-v3 and builds that id.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

@Denys88 Denys88 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read the full diff and the surrounding code; checked old vs new masked-variance formulas numerically. Both halves are correct — the variance fix is a genuine NaN-regression fix and every consumer route (RayWorker, player) already speaks the 5-tuple contract. A few things before merge:

Tests

  • tests/test_legacy_wrappers.py:633-636 asserts obs['state'].shape == (4, 7) for BatchedFrameStackWithStates(..., flatten=True), but the wrapper declares state_space=(28,) (wrappers.py:342) and RayWorker.get_env_info reports the unwrapped (7,); process_data (wrappers.py:370-372) never stacks a 1-D state. The test now pins a shape that disagrees with both declared spaces, so SMAC + frames>1 + central value is still unverified. Either fix the wrapper or don't cement the mismatch.
  • test_legacy_wrappers.py:682-685 comment says CarRacing "fell through to the unwrapped classic path" on master — it didn't; carracing_ppo.yaml hit a KeyError in create_vec_env (there is no fallback for creator-less names). With the -v3 rekey it now actually builds the RAY/box2d chain (box2d is not a declared extra). Worth saying in the description.
  • EpisodicLifeEnv new fallback (wrappers.py:122-126, no-op step ends the game → real reset) has no test; FakeAtariEnv(n_lives=2, steps_per_life=1) would hit it.
  • nit: tests/test_masked_variance.py:66-67 sys.path.insert is unnecessary (tests/__init__.py exists); test_degenerate_masks_stay_finite duplicates test_ppo_masking.py:584.

Pre-existing, but this PR makes these wrappers live again

  • MaxAndSkipEnv(use_max=False) returns a view into the persistent buffer (wrappers.py:192); FrameStack then stores k references to the same memory, so all stacked frames show the latest observation. The new use_max=False tests never stack over it. A .copy() there would do.
  • FireResetEnv (wrappers.py:75-83): if step(2) ends the episode the env is reset but the pre-reset obs is returned.
  • Masked RunningMeanStd path feeds unbiased var while the unmasked path uses unbiased=False, and passes input.size(0) rather than the valid count as batch_count.

Claim vs code: "reset kwargs (seeds) forward through the stack" is true of the wrappers, but no in-tree caller passes them — RayWorker.reset() (vecenv.py:132) is bare and RayWorker.seed (vecenv.py:125) calls a non-existent env.seed. Only tests exercise it.

Verified fine: two-pass variance is pooled scalar and unbiased exactly like before (old form gives −3e-8 on constant 0.7 over 16 rows, new gives 0; random data with offset 100 matches x[mask].var() to float precision); all three callers expect a scalar; TimeLimit now time_outs = truncated and no longer clobbers an inner truncation; all 15 wrappers return 5-tuples / (obs, info); dm_control RAY route removal is safe (depended on undeclared dm2gym, nothing references it).

Merge order: overlaps #381 on torch_ext.py and #368 on env_configurations.py.

🤖 Review drafted with Claude Code

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants