Repository navigation
Conversation
…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>
…llout-review-nov22
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
left a comment
There was a problem hiding this comment.
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.stepnow masks an env-providedtime_outswith~terminatedtoo. Correct, just a behaviour change for envs that set both.- The
central_value.py/recurrent.py/test_recurrent_dones.pyhunks 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.
|
@Denys88, you were right. I reproduced the failure with a best checkpoint written by upstream Fixed in I trained CartPole on 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
|
@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 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
left a comment
There was a problem hiding this comment.
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:
- The D2RL reorder silently changes what existing checkpoints compute (inline).
- 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.
- 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.
- 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_observationmask. That contract is not documented.
Checked and correct:
--seedwith a config that has noenv_configraisesKeyErroron 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, ord2rlwith 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) |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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') |
There was a problem hiding this comment.
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.") |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 readsV(self.obs)which is the terminal obs at that point; same-step usesfinal_observationonly when it carriesstatesunder a central value, else falls back to the pre-step value;update_rnn_states: Falseon the central value and the un-storedself.rnn_statesread on the shared model mean neither path advances a recurrent state. Thegamma * valuesordering restores bit-identity on the Isaac path.- Ray and manual gymnasium adapters:
time_outsmasked by~terminated, final obs deep-copied before reset,_final_observation= per-agentdonesmasked to workers that produced one,final_observationstripped beforedicts_to_dict_with_arrays._batch_observationsdedupe is a straight refactor. - Recurrent central value with a feed-forward actor mirrors
play_steps_rnnexactly (pre_step at sequence starts, post_step on dones and on filler reset rows,rnn_donesoverride undermask_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_dictwarning is the right amount of noise.load_state_dictcopies the dict before calling it, so thepop/setdefaultis safe.- Single
after_print_statsper epoch (thewrite_statscall remains), RMS-advantage flag resolved once in__init__,setdefault('env_config'),+= self.global_rank, SACreplay_obs/replay_obs_auxsnapshot. - #432 landed on master (0e30436) with the same
checkpoint_mutexhunk; this branch needs one more master merge.
Before merge (both already noted in your own inline comments; confirming them as blockers)
rl_games/algos_torch/d2rl.py: drop the reorder from this PR. It silently changes what everyd2rl+ 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.rl_games/algos_torch/players.py(3×restore):map_location=self.device, not'cpu'.'cpu'also relocates tensors insidecheckpoint['env_state'], whichset_env_statethen 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 namingDefaultAlgoObserver, 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.
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
obs_aux, added by SAC: FlashSAC options #395) is snapshotted the same way.env_config. Distributed training applies the rank offset once to the environment seed.Checkpoints and playback
--trust-checkpointopt-in. That is removed: it rejected checkpoints written by master, which storelast_mean_rewardsas a NumPy scalar (PPO) or a 0-d array (SAC), and any environment with customenv_state. There is notrusted_checkpointkey and no--trust-checkpointflag.restore()call instead of atorch.loadprobe followed byrestore().player.evaluation: Truewithoutplayer.dir_to_monitorraisedAttributeErroron the first checkpoint check. It is now a no-op.player.device, thendevice_name, thendevice) and can load CUDA-saved weights on CPU.last_mean_rewardsas a plain float.Network, normalization and logging fixes
LayerNorm2d(conv2d trunk withnormalization: layer_norm) used batch statistics with no running estimate, and itsgamma/betawere constant buffers withbetaequal 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.gamma/betabecomeweight/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.D2RLNetapplied 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: Truewithnormalize_advantage: FalseraisedAttributeError. The flag is now ignored with a warning in that case.self_play_config.check_scores: TrueraisedAttributeError. The score meter is read from the observer.after_print_statstwice per epoch. It is called once, as in continuous PPO.No bundled config combines a conv trunk with
layer_norm,d2rlwith 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:obsandobs_auxtensors every step, the stored transitions keep the pre-step values. Without theobs_auxsnapshot 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.