Skip to content

Fix PPO timeout targets, SAC replay ownership, and checkpoint loading - #427

Open
ViktorM wants to merge 16 commits into
masterfrom
fix/rollout-review-nov22
Open

ViktorM wants to merge 16 commits into
masterfrom
fix/rollout-review-nov22

Conversation

@ViktorM

@ViktorM ViktorM commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Created with OpenAI Codex (GPT-6). The network, normalization and logging fixes, the removal of the restricted checkpoint loader, the merge with master and the two later rollout and playback fixes were added with Claude Code.

Rollout and SAC fixes

  • PPO now bootstraps time limits from the critic value at the final observation. Both rollout paths handle next-step autoreset and same-step adapters that supply a final observation. Same-step simulators that discard it retain the pre-step estimate. The Ray and manual Gymnasium adapters preserve the observation across worker resets, including per-agent timeouts.
  • A recurrent central value with a feed-forward actor was trained from hidden states the rollout never used: the non-recurrent rollout loop neither recorded nor reset the central value's RNN state. It now does the same bookkeeping as the recurrent loop. Runs without a recurrent central value are unaffected.
  • SAC snapshots the pre-action observation before stepping a simulator that reuses its buffers, so replay keeps the original state and its actual successor. The compactor aux (obs_aux, added by SAC: FlashSAC options #395) is snapshotted the same way.
  • A CLI seed override works with bundled configs that omit env_config. Distributed training applies the rank offset once to the environment seed.

Checkpoints and playback

  • Checkpoints are loaded with full pickle, as on master. An earlier revision of this PR made PyTorch's restricted loader the default, with a --trust-checkpoint opt-in. That is removed: it rejected checkpoints written by master, which store last_mean_rewards as a NumPy scalar (PPO) or a 0-d array (SAC), and any environment with custom env_state. There is no trusted_checkpoint key and no --trust-checkpoint flag.
  • The evaluation watcher loads a new checkpoint with a single restore() call instead of a torch.load probe followed by restore().
  • player.evaluation: True without player.dir_to_monitor raised AttributeError on the first checkpoint check. It is now a no-op.
  • Playback honors the configured device (player.device, then device_name, then device) and can load CUDA-saved weights on CPU.
  • New checkpoints save last_mean_rewards as a plain float.

Network, normalization and logging fixes

  • LayerNorm2d (conv2d trunk with normalization: layer_norm) used batch statistics with no running estimate, and its gamma/beta were constant buffers with beta equal to one. It is now a per-sample layer norm (GroupNorm(1, C)) with learnable scale and shift. The conv1d layer norm, which raised unless the sequence length equalled the channel count, uses the same.
    • Old checkpoints still load: gamma/beta become weight/bias, with a warning. Their outputs change, because the statistics do. Resuming training from such a checkpoint with its saved optimizer state fails, because the layer has two new parameters.
  • D2RLNet applied activation then normalization on its first layer and the reverse on the others. Every layer now applies activation then normalization, as the sequential MLP and conv builders do. A d2rl network trained with a normalization computes a different function after this change.
  • normalize_rms_advantage: True with normalize_advantage: False raised AttributeError. The flag is now ignored with a warning in that case.
  • self_play_config.check_scores: True raised AttributeError. The score meter is read from the observer.
  • Discrete PPO called the observer's after_print_stats twice per epoch. It is called once, as in continuous PPO.

No bundled config combines a conv trunk with layer_norm, d2rl with a normalization, or a recurrent central value with a feed-forward actor.

The base branch includes the recurrent fixes from #391 and #405, and FlashSAC and SAC multi-GPU from #395 and #396.

Verification

On the current head, merged with master at bd6b04b, on CPU with torch 2.15, NumPy 2.5 and Python 3.13:

  • Full suite: 1087 passed, 23 skipped.
  • Timeout targets: a deterministic PPO regression uses a reward of 1, discount of 0.99, pre-action value of 4, and final value of 5. Feedforward and recurrent rollouts both return the expected target of 5.95. In an ad hoc check with real networks on a next-step env, the bootstrap value matches the value of the final observation under the post-step hidden state to 1e-8, for a feedforward policy, an LSTM policy, and LSTM and GRU central values.
  • Recurrent central value: recomputing its first training minibatch right after a rollout reproduces the stored values, for LSTM and GRU, feed-forward and recurrent actors, same-step (2 agents) and next-step autoreset. Before the fix the feed-forward-actor cases disagreed on 63 of 80 rows.
  • Checkpoints written by master's code load with default settings: PPO discrete, PPO continuous, SAC, and a PPO file rewritten to the NumPy 1.x pickle spelling.
  • SAC replay: with an environment that returns the same obs and obs_aux tensors every step, the stored transitions keep the pre-step values. Without the obs_aux snapshot the new test fails.

Not run on this head: NumPy 1.x, CUDA, and multi-GPU. The earlier description reported a run under NumPy 1.26.4 on revision d257823.

DenSumy and others added 3 commits October 27, 2026 20:25
…ral value, RnnWithDones resets with a single sequence

- central_value.update_multiagent_tensors reordered value_preds and returns
  from env-major to agent-major before taking the first batch_size rows, but
  not dones, so the central value row of env e trained with the dones of env
  e // num_agents. dones now get the same reorder. The old view on dones also
  failed for value_size > 1.
- RnnWithDones squeezed the batch dim away when a minibatch held one sequence,
  so any(dim=-1) reduced over time and no mid-sequence reset happened in
  training, while the rollout did reset. T=1, N=1 raised IndexError.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Carry terminal observations through the vector environment adapters and use them in feedforward and recurrent PPO. Snapshot SAC observations before simulator steps. Require explicit trust for legacy pickle checkpoints, honor the configured playback device, and apply CLI seed overrides consistently across ranks.

@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. The timeout bootstrap, the SAC pre-step snapshot, the Ray/manual final-observation plumbing, the player device precedence and the seed fixes all look right, and the += self.global_rank change is a real fix (master added seed + rank to the env seed, since self.seed already carries the rank). One blocker:

Every checkpoint saved by master fails to load by default. a2c_common.py:1598 sets self.last_mean_rewards = mean_rewards[0], a numpy float32, so any checkpoint written after the first reward log carries a numpy scalar. With weights_only=not trusted those all fail with the new UnpicklingError, and every user who resumes or plays an existing run has to add --trust-checkpoint. This PR casts to float() on save, which only helps new checkpoints. Verified with torch 2.12: torch.load(weights_only=True) on {"last_mean_rewards": np.float32(3.5)} raises; the same load inside torch.serialization.safe_globals([np._core.multiarray.scalar, np.dtype, type(np.dtype("float32"))]) returns the float32. That is what the old safe_load set up and then bypassed with weights_only=False. Keep that allowlist in the restricted path (numpy scalar, np.dtype, the dtype classes) so rl_games' own legacy checkpoints load without the flag, and reserve --trust-checkpoint for genuinely arbitrary pickles (custom env_state classes). Add a test that a checkpoint with a numpy last_mean_rewards loads untrusted.

Notes, no action needed:

  • _bootstrap_timeouts: timeouts.any() is a device sync per step on the next_step / final-observation paths (same-step sims without a final obs skip it). Fine for gymnasium-style envs; worth knowing if an envpool-on-GPU setup shows a step-time regression.
  • RayWorker.step now masks an env-provided time_outs with ~terminated too. Correct, just a behaviour change for envs that set both.
  • The central_value.py / recurrent.py / test_recurrent_dones.py hunks are #391, already on master; they vanish on merge.

Recognize the NumPy 1.x and 2.x spellings used by historical best-reward checkpoints. Decode float32 and float64 reward scalars while keeping custom simulator objects behind explicit trust. Cover direct restore, watched evaluation, and preservation of caller-registered safe globals.
@ViktorM

ViktorM commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

@Denys88, you were right. I reproduced the failure with a best checkpoint written by upstream master. My original smoke test ended before the trainer saved a NumPy best reward, so it missed the compatibility break.

Fixed in d257823. The restricted loader now reads the NumPy 1.x and 2.x representations of float32 and float64 rewards. Custom simulator objects and NumPy arrays in env_state still require explicit trust.

I trained CartPole on cc0dc93 with NumPy 1.26.4 and opened its checkpoint on this branch with NumPy 2.4.6. With default settings, playback completed an episode and training resumed from epoch 1 to epoch 2 with the original best reward of 29.5. The checkpoint tests passed under both NumPy versions, and the full local suite passed with 1,019 tests and 3 skips. Original review

Created with OpenAI Codex (GPT-6).

torch_ext.LayerNorm2d (conv2d with normalization: layer_norm) computed
mean/std over batch and spatial dims per channel -- batch statistics with
no running estimate, so a sample's output depended on its batch mates and
the layer was a different function on a rollout batch and on a training
minibatch. gamma/beta were buffers (never trained) and beta was ones, so
the output mean was 1.0.

It is now nn.GroupNorm(1, C): per-sample statistics over (C, H, W) with
learnable per-channel weight (1) and bias (0). eps follows the torch
default (1e-5, inside the sqrt).

Old checkpoints: the layer's gamma/beta buffers ([C, 1, 1]) are loaded as
weight/bias, with a warning. That keeps strict loading working and carries
the affine part over exactly (including the +1 shift the downstream layers
were trained against); the statistics cannot be carried over, so outputs
differ from the ones the checkpoint was trained with. Players and
weight-only restores of such checkpoints work. A full training resume does
not: the layer now has two trainable parameters that the saved optimizer
state has no entries for, and optimizer.load_state_dict rejects it.

_build_cnn1d applied torch.nn.LayerNorm(C) to a [B, C, L] tensor, which
normalizes the last dim and raises unless L == C; it now uses
nn.GroupNorm(1, C) as well.

No shipped config combines a conv trunk with normalization: layer_norm.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
advantage_mean_std is created only when both normalize_advantage and
normalize_rms_advantage are set, but set_eval, set_train,
get_stats_weights, set_stats_weights and PpoDiagnostics.epoch checked
normalize_rms_advantage alone. normalize_advantage: False with
normalize_rms_advantage: True raised "'A2CAgent' object has no attribute
'advantage_mean_std'".

The flag is now resolved once where it is read: without
normalize_advantage it is turned off with a warning, so every later check
agrees with whether the module exists. RMS statistics are only ever used
inside the normalize_advantage branch, so nothing that worked changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
With check_scores: True SelfPlayManager.update read algo.game_scores,
which the algorithm never had: the meter is
DefaultAlgoObserver.game_scores. It now reads
algo.algo_observer.game_scores.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
DiscreteA2CBase.train called algo_observer.after_print_stats right
after write_stats, which already calls it, so discrete PPO invoked the
observer (and wrote its scalars) twice per epoch. ContinuousA2CBase.train
does not. The duplicate call is removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
D2RLNet.forward applied activation -> norm on the first layer and
norm -> activation on the remaining ones. All layers now use
activation -> norm.

That order was picked because it is what the same `normalization` option
means everywhere else in the builder (_build_sequential_mlp, _build_cnn2d,
_build_cnn1d: layer -> activation -> norm), so switching d2rl on changes
only the dense connections, and the hidden block concatenated with the
input is the normalized one. Only matters when a normalization is
configured. Checkpoint keys are unchanged, but a d2rl network trained with
a normalization computes a different function in layers 2..N after this
change. No shipped config combines d2rl with a normalization.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
The regrouping fixed by #391 is unit-tested on a stub in
tests/test_recurrent_dones.py. This runs it on the tensors a real rollout
produces: a 2-agent PPO agent with a central value (MLP and LSTM), where
every central-value row at train time must carry the done flag of the env
its state row belongs to.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
Checkpoints are loaded with full pickle again, as on master. The switch
to PyTorch's weights-only reader was not needed by any fix in this
branch, and it rejected every existing checkpoint: master saved
last_mean_rewards as a NumPy scalar (PPO) or a 0-d NumPy array (SAC),
and environments store arbitrary objects in env_state.

Removed with it: the NumPy reward decoder and its process-wide lock, the
trusted_checkpoint config key, runner.py --trust-checkpoint and the
CONFIG_PARAMS section.

Kept, because they do not depend on it: the single restore() call in the
evaluation watcher, map_location='cpu' for playback, and saving
last_mean_rewards as a plain float.

safe_load is now one torch.load(weights_only=False) call. Master wrapped
that call in a safe_globals() block that had no effect on a full-pickle
load and touched the deprecated np.core.

Tests: checkpoints holding a NumPy scalar, a 0-d NumPy array or a custom
env_state object load by default, directly and through the evaluation
watcher.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
Master gained FlashSAC (#395) and SAC multi-GPU (#396). Two conflicts:

- sac_agent.py: #395 added replay_rewards and the compactor aux to the
  _store_transitions call whose first argument this branch had changed to
  the pre-step snapshot. Both are kept. obs_aux is read before env.step()
  the same way as the observation, so it is snapshotted too: with only
  the observation snapshot, an env that reuses its tensors stores the aux
  of step t+1 for step t (new test in tests/test_sac_flash.py).
- vecenv.py: #395 appended the POINT_MASS_TRACKING registration at the
  end of the file, where this branch had only added the final newline.
  Master's lines are kept.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
BasePlayer created checkpoint_mutex only when player.dir_to_monitor was
set, but run() calls maybe_load_new_checkpoint() whenever
player.evaluation is on, and that takes the mutex. evaluation: True
without dir_to_monitor raised "'PpoPlayerContinuous' object has no
attribute 'checkpoint_mutex'". The mutex is now always created; with
nothing watched the call is a no-op.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ
play_steps, the rollout loop used when the actor has no RNN, never
recorded the central value's RNN state at sequence starts and never
reset it at episode ends; only play_steps_rnn did. With a recurrent
central value and a feed-forward actor, training therefore replayed the
critic from states the rollout never used: recomputing the first
central-value minibatch right after a rollout disagreed with the stored
values on 63 of 80 rows (4 envs x 2 agents, horizon 20).

play_steps now does the same bookkeeping as play_steps_rnn, all of it
behind "the central value is recurrent": pre_step_rnn at each step,
post_step_rnn at episode ends, and for next-step autoreset the re-zero
after a filler row plus the matching train-time done flag. Runs without
a recurrent central value take none of the new branches.

No bundled config combines a recurrent central value with a
feed-forward actor.

Test: for LSTM and GRU central values, feed-forward and recurrent
actors, same-step (2 agents) and next-step autoreset, the recomputed
minibatch equals the rollout values. The four feed-forward-actor cases
fail without this change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZraKcmCfYG6e8EBiqJ

ViktorM commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@Denys88, the blocker is resolved a different way than you asked. The restricted loader is removed: checkpoints load with full pickle, exactly as on master, so nothing master wrote can fail to load. Even with the allowlist it still rejected SAC checkpoints (they store last_mean_rewards as a 0-d array) and any custom env_state, which was too much breakage for what it protected. The earlier reply about d257823 is superseded. Kept from that part: one restore() call in the evaluation watcher, CPU mapping for playback, and float() on save.

New since you read the diff, all listed in the description:

Could you take another look?


Generated by Claude Code

_bootstrap_timeouts added the bootstrap with rewards.add_(x, alpha=gamma). That may fuse the multiply and
the add, which rounds differently from master's gamma * values followed by an add. On same-step envs
without a final observation (Isaac Lab and other GPU simulators), where the pre-step value is kept, the
returns of some time-out rows moved by one float step and fixed-seed runs no longer matched master.
The product is now formed first, as on master.

tests/test_ppo_default_digest.py pins that path: the stored rollout rewards equal master's expression
bit for bit (fails on the old line, MLP and LSTM), and losses and final weights of three fixed-seed runs
reproduce the values recorded on master bd6b04b.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZqz94VdW57VEwskjHB

@ViktorM ViktorM left a comment

Copy link
Copy Markdown
Collaborator Author

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 compared fixed-seed PPO training between master (bd6b04b) and this branch on CPU. The individual fixes are mostly right. One commit pushed (4c8cad7), and four things are still open before merge.

Pushed: 4c8cad7. The same-step path without a final observation (Isaac Lab) had stopped being bit-identical to master because of how the bootstrap was added to the rewards. It matches master again, with a regression test. Full suite: 1092 passed, 23 skipped.

Fixed-seed runs against master (MLP and LSTM), after 4c8cad7:

Env type Final weights against master
Same-step, no final observation Identical
Same-step with a final observation Differ, as intended
Next-step with time-outs (envpool style) Differ, as intended
Next-step, terminations only Identical

Open before merge:

  1. The D2RL reorder silently changes what existing checkpoints compute (inline).
  2. No training evidence for the new time-out targets. They change the targets of every PPO run on envpool or Gymnasium envs, and the validation is unit tests only. Two or three next-step benchmarks with a few seeds each, before and after, would settle it.
  3. The untested configurations are ones this PR touches. The description says CUDA, multi-GPU and NumPy 1.x were not run on this head, while the PR changes multi-GPU env seeding and CUDA-to-CPU playback loading.
  4. Re-review. The earlier blocker (the restricted loader) is resolved by removing it, but five unrelated fixes were added after that review.

Smaller:

  • The title names three fixes; the PR carries about fifteen behaviour changes. Splitting off the network changes (LayerNorm2d, D2RL) would make it easier to review and bisect.
  • PPO now depends on infos['final_observation'] being a full batch with an optional _final_observation mask. That contract is not documented.

Checked and correct:

  • --seed with a config that has no env_config raises KeyError on master and works here.
  • The bootstrap query does not advance a recurrent central value's state.
  • No bundled config combines a conv trunk with layer_norm, or d2rl with a normalization, as the description says.

Nothing here was run on a GPU.


Generated by Claude Code

x = self.linears[i](x)
x = self.norm_layers[i](x)
x = self.activations[i](x)
x = self.activations[i](x)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Must fix: this silently changes what existing d2rl + normalization checkpoints compute. I saved a d2rl + layer_norm network on master and loaded it on this branch: all keys match, no warning, and the output differs (the last layer's output is now normalized). Unlike LayerNorm2d, nothing tells the user.

The old order was inconsistent with the sequential MLP but not broken, and there is no evidence the new one trains better. Suggest dropping it from this PR, or putting the new order behind a config key that defaults to the old one.


Generated by Claude Code

values = torch.where(valid, values, previous_values)
# gamma * values first, as master did: add_(x, alpha=gamma) may fuse the multiply and the add, which
# rounds differently and changes fixed-seed runs on envs that keep the pre-step value
rewards.add_(torch.where(timeouts, self.gamma * values, 0.0))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4c8cad7. This line was rewards.add_(torch.where(timeouts, values, 0.0), alpha=self.gamma), which rounds differently from master's gamma * values followed by an add. On same-step envs without a final observation (Isaac Lab), values and observations matched master but some returns moved by one float step (2 of 60 rows in a test rollout, max 2.4e-7), so fixed-seed runs diverged.

With the product formed first, fixed-seed runs on that path match master exactly (MLP and LSTM, with and without input/value normalization). tests/test_ppo_default_digest.py pins it.


Generated by Claude Code

if not timeouts.any():
return
if self.autoreset_mode == 'next_step':
values = self.get_values(self.obs)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

One time-out anywhere in the batch triggers a value pass over every env. I measured it at 0.91x of an acting forward pass (4,096 envs, CPU). With staggered 1,000-step episodes a time-out occurs on about 23% of steps at 256 envs and 98% at 4,096, so on large next-step env counts rollout inference nearly doubles.

For a feed-forward policy without a central value, evaluating only the timed-out rows avoids it. Not a blocker; worth a follow-up or a note in the docs.


Generated by Claude Code


def restore(self, fn):
checkpoint = torch_ext.load_checkpoint(fn)
checkpoint = torch_ext.load_checkpoint(fn, map_location='cpu')

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

map_location='cpu' applies to the whole checkpoint, and restore then passes checkpoint['env_state'] to env.set_env_state. A GPU simulator that keeps tensors in its env state now receives them on the CPU, where master handed them over on the device they were saved on.

map_location=self.device fixes CUDA-saved weights on a CPU player without that side effect. The same applies to the other two players below.


Generated by Claude Code

"gamma/beta were loaded as weight/bias, but the layer now normalizes each sample "
"over (C, H, W), so outputs differ from the ones the checkpoint was trained with. "
"weight/bias are new trainable parameters: optimizer state saved with this "
"checkpoint does not match the model.")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The warning is right, but a full resume then fails later inside the optimizer load with a generic size-mismatch error that does not name this layer. Raising a clear error at that point (or skipping the saved optimizer state with a message) would save the user the search.


Generated by Claude Code

if self.check_scores:
data = algo.game_scores
# the score meter lives on the observer (DefaultAlgoObserver.game_scores), not on the algo
data = algo.algo_observer.game_scores

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Nit: only DefaultAlgoObserver has game_scores, so check_scores with a custom observer still ends in AttributeError. A getattr with a message that names the requirement would be clearer.


Generated by Claude Code

@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.

Re-read the whole diff at 4c8cad7 (24 files). Also ran the full suite on 4c8cad7 on a 2× RTX PRO 6000 Blackwell machine (torch 2.12.0+cu130, NCCL 2.29, Python 3.12) in a scratch clone: 1112 passed, 3 skipped, including the two-GPU NCCL tests in test_sac_multigpu.py and the CUDA-graph tests. That covers the CUDA half of your "not run on this head" list; multi-node and NumPy 1.x were not run.

Dropping the restricted loader rather than allowlisting was the right call once SAC's 0-d array and custom env_state entered the picture; float() on save plus full pickle on load is the simplest contract that keeps every existing checkpoint loading.

Checked and correct

  • _bootstrap_timeouts: next-step reads V(self.obs) which is the terminal obs at that point; same-step uses final_observation only when it carries states under a central value, else falls back to the pre-step value; update_rnn_states: False on the central value and the un-stored self.rnn_states read on the shared model mean neither path advances a recurrent state. The gamma * values ordering restores bit-identity on the Isaac path.
  • Ray and manual gymnasium adapters: time_outs masked by ~terminated, final obs deep-copied before reset, _final_observation = per-agent dones masked to workers that produced one, final_observation stripped before dicts_to_dict_with_arrays. _batch_observations dedupe is a straight refactor.
  • Recurrent central value with a feed-forward actor mirrors play_steps_rnn exactly (pre_step at sequence starts, post_step on dones and on filler reset rows, rnn_dones override under mask_autoreset_rows).
  • LayerNorm2d → GroupNorm(1, C): the old layer was batch statistics with constant gamma/beta=1, so a behaviour change is unavoidable and the _load_from_state_dict warning is the right amount of noise. load_state_dict copies the dict before calling it, so the pop/setdefault is safe.
  • Single after_print_stats per epoch (the write_stats call remains), RMS-advantage flag resolved once in __init__, setdefault('env_config'), += self.global_rank, SAC replay_obs/replay_obs_aux snapshot.
  • #432 landed on master (0e30436) with the same checkpoint_mutex hunk; this branch needs one more master merge.

Before merge (both already noted in your own inline comments; confirming them as blockers)

  1. rl_games/algos_torch/d2rl.py: drop the reorder from this PR. It silently changes what every d2rl + normalization checkpoint computes, with no warning and no training evidence. The old order was inconsistent, not broken. If you want consistency, land it separately behind a config key that defaults to the old order.
  2. rl_games/algos_torch/players.py (3× restore): map_location=self.device, not 'cpu'. 'cpu' also relocates tensors inside checkpoint['env_state'], which set_env_state then hands to a GPU simulator on the wrong device.

Should have
3. Training evidence for the new time-out targets. Every PPO run on envpool or gymnasium next-step envs now bootstraps from V(final_obs) instead of V(s_t). Bit-identity on Isaac is good, but "differ, as intended" is not evidence that the new target trains at least as well. Two envpool mujoco benchmarks (e.g. Ant and Humanoid from the bundled configs) × 3 seeds, before and after, would settle it, plus the step-time delta at 256 and 4096 envs given the whole-batch value pass you measured.
4. Document the final_observation / _final_observation contract (full batch, optional per-row mask) in docs/ENVPOOL.md or the vecenv docs, since custom vecenvs now get better targets if they follow it.

Nits

  • self_play_manager.py:18: getattr(algo.algo_observer, 'game_scores', None) with a message naming DefaultAlgoObserver, as you noted.
  • torch_ext.py:387: the resume-with-old-optimizer-state failure deserves a clear error instead of the generic size mismatch.
  • Title and description cover the scope now, but this is ~15 behaviour changes in one unit. I'll take it as is once (1) and (2) are in rather than ask for a split at this point.

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.

4 participants