Skip to content

SAC: FlashSAC options - #395

Merged
Denys88 merged 7 commits into
masterfrom
VM/feature/sac-flash
Nov 23, 2026
Merged

Denys88 merged 7 commits into
masterfrom
VM/feature/sac-flash

Conversation

@ViktorM

@ViktorM ViktorM commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

SAC: FlashSAC options

Adds the pieces of large-scale FlashSAC-style training to the existing SAC as config options, so multi-hand tracking runs can use algo: sac instead of a separate learner. Every option is off by default; the default SAC path is unchanged.

  • n-step returns (n_step): folded at insertion per env. A termination stops the bootstrap; a time-out bootstraps from the true final obs with gamma^k, k = rewards summed. Works with both replay buffers and both autoreset modes.
  • flash_sac network: batch norm + unit-norm linear residual blocks + RMS norm, re-projected after every optimizer step; online and target critics run on [obs; next_obs] in one batch-norm pass. Optional Conv1d encoder over a trailing obs window (obs_window).
  • Grouped ensemble critic (action_groups): 2 x H members as one batched ensemble; one actor tower, reward column (infos['reward_heads']) and temperature per group; gated actor loss. Categorical head (critic: num_bins, C51 projection onto the min-Q twin's bins) or scalar Q. With one group it is plain twin-Q SAC.
  • Replay: replay_memory_efficient stores each obs once and reads the next obs by row offset, with a side pool for time-out final obs; replay_obs_dtype: float16; replay_storage: host keeps rows in page-locked host memory read by the GPU; replay_obs_compactor hook drops and rebuilds reconstructible obs columns.
  • Training knobs: per-group return-based reward scaling (normalize_reward), held exploration noise (held_noise, truncated zeta over 1-16 steps), cosine LR with warm-up (lr_schedule: cosine; lr_per_optimizer_step gives a half-rate actor/temperature schedule), target_entropy_sigma, min_alpha.
  • Example: sac_flash_point_mass.yaml on a new GPU-vectorized point-mass tracking task with two action groups. The new keys are documented in CONFIG_PARAMS.md.
  • Reference sizes: 645,644 / 683,584 parameters per actor tower and 77,813,556 / 79,011,924 for the critic (obs 3088 / 3360, 2 x 18 / 2 x 28 actions), checked by a test.

Validation: the default SAC reproduces master f7e4345 bit for bit on CPU: all 165 losses, actions and final weights of two fixed-seed runs; a new regression test checks this. Default-SAC HalfCheetah-v5 on GPU gives identical rewards to master at 40k / 60k / 80k frames (1218.7 at 80k). Full suite: 441 passed. The two-group point-mass task learns on CPU in 37 s: the summed reward per step goes from 0.14 to 0.36-0.74 across seeds 0-6. At reference size on one RTX 4090 it reaches 1.28 after 2.1M frames.

🤖 Generated with Claude Code

Viktor Makoviichuk and others added 3 commits November 5, 2026 00:54
Fixed-seed CPU runs of the default SAC on the fake next-step and same-step envs
must reproduce the losses, actions, weights and temperature recorded on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
All options, off by default:
- n_step: returns folded at insertion, gamma^k bootstrap per row.
- flash_sac network: batch norm, unit-norm residual blocks, RMS norm,
  weight re-projection, joint [obs; next_obs] critic pass, categorical
  or scalar head, optional Conv1d encoder over a trailing obs window.
- action_groups: one actor tower, Q twin pair, reward head and
  temperature per group, gated actor loss.
- Replay: memory-efficient ring (next obs by row offset), fp16 obs,
  page-locked host storage read by the GPU, obs compactor hook.
- Return-based reward scaling, held exploration noise, cosine LR.
- Point-mass tracking test task with two action groups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Solid work. The digest test protects the default path, and the n-step and replay tests are thorough. I also fuzzed MemoryEfficientReplayBuffer against VectorizedReplayBuffer (300 random streams, ring wraps, capacity not divisible by num_envs, mixed terminations and time-outs): every field matches. The comment on the entropy term vs the categorical support (sac_agent.py) matters most.

Two ideas beyond the inline comments:

  • Sample-time n-step folding in the memory-efficient ring. It already reads rows at fixed offsets, so folding there costs n small gathers. That would allow annealing n, λ-returns, or changing n on resume.
  • A CrossQ ablation. The online critic already runs the joint [obs; next_obs] pass and discards the next-obs half. Using that half (stop-grad) as the bootstrap drops the target forward pass and the 77.8M-parameter EMA, about 20% of the update FLOPs.

Splitting the PR into replay/n-step, network + grouped critic, and training knobs would make it easier to review and bisect.

Tested on CPU only: 45 passed, 7 GPU tests skipped.


Generated by Claude Code

with torch.no_grad():
probs = sac_helper.min_twin_log_probs(
q_t[:, n:].reshape(2, h * n), log_p_t[:, n:].reshape(2, h * n, bins)).exp()
target = sac_helper.project_categorical(

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 entropy term can eat the ±5 support. ReturnScaler bounds the reward part of the return, but not −α log π. At the target entropy H, the fixed point shifts Q by γⁿH/(1−γⁿ)·α.

At XHand size (18 dims per group, σ = 0.15 → H = −8.6, γ = 0.98) that is −422α for n = 1 and −81α for n = 5. So n = 1 at α = 0.01 already uses −4.2 of the support. n = 5 only fits because the n-step target drops the intermediate entropy terms. The toy task (H ≈ −1) can't show this.

Suggest logging the target mass in the two edge bins, and sizing v_min from this formula.


Generated by Claude Code

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 formula checks out. In our Sharpa recipe (28 dims per group at sigma 0.15, so H = -13.4; gamma 0.98, n 5) the shift is -126 alpha: -1.2 at the initial alpha 0.0097, about -0.03 once alpha settles near 2e-4. Added info/target_edge_low<h> / info/target_edge_high<h> (target mass on the edge bins) and the sizing formula in CONFIG_PARAMS. c91669e

Comment thread rl_games/algos_torch/sac_agent.py Outdated
log_prob = self._group_log_prob(dist, action)[:n] # (B, H)
q, _ = net.critic(obs, net.gate_actions(self.rescale_actions(action[:n])))
actor_q = q.reshape(2, h, n).amin(dim=0) # (H, B)
alpha = torch.max(self.alpha.detach(), self.min_alpha)

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.

min_alpha floors α here but not in the bootstrap bonus (line 656). Below the floor, the actor optimizes a different objective than the critic evaluates. Clamping log_alpha after the temperature step would give one α everywhere. The default path has the same split.


Generated by Claude Code

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 for the flash path: one floored alpha in the target and the actor loss, and log alpha clamped at the floor after every temperature step (no wind-up). The default path keeps upstream's behaviour, which the digest test pins. c91669e

page-locked host memory read by the GPU."""
obs_shape = self.env_info['observation_space'].shape
action_shape = self.env_info['action_space'].shape
obs_dtype = getattr(torch, config.get('replay_obs_dtype', 'float32'))

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.

Obs are stored raw, before any normalization. Near 50, fp16 resolves 0.031 and bf16 0.25, so absolute positions in metres lose centimetres to decimetres. A one-time per-column check of the quantization error at the first insert would make float16 safe to recommend.


Generated by Claude Code

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.

Added a one-time report at the first insert: the max round-trip error, plus the columns that lose more than 1e-3 with their magnitude. c91669e

def is_separate_critic(self):
return True

def gate_actions(self, actions):

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.

With this gating, tower g maximizes only Q_g; the effect of its actions on the other groups' Q is dropped. That's right for per-hand tracking. Coupled tasks (a handover, one shared object) would settle at a Nash point rather than the team optimum.

A cheap generalization: held + (m + lam * (1 - m)) * (actions - held) keeps the values and scales the cross-group gradient by lam (0 = current, 1 = cooperative on Σ Q_h).


Generated by Claude Code

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.

Agreed on the Nash point. Not adding the knob until a coupled task (handover, one shared object) needs it; then it is the one-line change you give.

in_dim = (self.encoder.out_dim if window else obs_dim) + action_dim
self.trunk = Trunk(in_dim, units, blocks, expansion, self.members, momentum)
out_dim = num_bins if num_bins else 1
self.out_proj = UnitLinear(units, out_dim, self.members)

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.

With num_bins: 0, Q = unit-norm row · RMS-normalized features + bias, so |Q − b| ≈ √units (≈ 32 at 1024). Without normalize_reward, larger returns can only come from the bias or from the RMS weights concentrating. Require normalize_reward for the scalar head, or add a learnable output scale?


Generated by Claude Code

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.

Right, the bound is Cauchy-Schwarz over the RMS-normalized features. Now a warning when the scalar head runs without normalize_reward, and a note in the docs. The categorical head is the recipe, so the scalar head stays as is. c91669e

Comment thread rl_games/algos_torch/sac_helper.py Outdated
def __call__(self, like):
if self.eps is None or self.eps.shape != like.shape or self.used >= self.hold:
self.eps = torch.randn_like(like)
self.hold = int(torch.multinomial(self.pmf, 1).item()) + 1

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 hold length for all envs means every env resamples on the same step, and the noise carries across resets. Per-env counters (a device tensor plus torch.where) fix both.

Side note: zeta(2) holds give roughly pink noise at periods up to 16 steps, so colored-noise exploration (Eberhard et al., ICLR 2023) is the natural baseline.


Generated by Claude Code

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: per-env hold counters on the device, fresh noise at every episode start. It also removes a host sync: the old draw called .item() on every resample, about 63% of steps. c91669e


@torch.no_grad()
def add(self, obs, action, reward, next_obs, done, truncated=None, live=None, obs_aux=None, next_obs_aux=None):
"""One env step for all envs; done = terminated. A step both terminated and truncated counts as terminated."""

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.

There are three conventions for a step that both terminates and times out:

  • here, termination wins;
  • the agent makes it a truncation (terminated = dones & ~truncated_mask), so it bootstraps through a failure;
  • the 1-step VectorizedReplayBuffer keeps both flags.

It can't happen through the agent today, but one rule would be cleaner (gymnasium: termination wins).


Generated by Claude Code

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 1-step path now also counts a step with both flags as terminated (gymnasium's rule, documented). The agent can't follow it: Isaac Lab's rl_games wrapper passes dones = terminated | time_outs plus time_outs, so a failure on the last step looks like a plain time-out there. c91669e

def _store_final(self, timeout, final_obs, final_aux):
"""Pool slot per env, -1 where the env did not time out at this step."""
slot = torch.full((self.num_envs,), -1, dtype=torch.int64, device=self.device)
envs = timeout.nonzero().squeeze(-1)

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.

nonzero() plus numel forces a host sync every env step. torch.nonzero_static with a size cap, plus an overflow check, avoids it.


Generated by Claude Code

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.

True, one sync per env step. nonzero_static alone doesn't remove it: the pool bookkeeping (slot ring, birth steps) lives on the host and needs the count. Moving it to the device is a follow-up; today it is 1 of ~113 GPU waits per env step in our tracking env.

Comment thread rl_games/common/experience.py Outdated
self.truncated = alloc((capacity,), torch.bool)
self.discount = alloc((capacity,), torch.float32) if n_step > 1 else None
# pool slot of the true final obs for time-out rows, -1 otherwise
self.final_slot = alloc((capacity,), torch.int64)

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: int32 is enough here and saves 200 MB at 50M rows. Also, in host mode host_tensors (line 282) keeps superseded pool tensors alive after the pool grows.


Generated by Claude Code

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.

Both done: int32 slots, and a grown host pool now releases its old pages. c91669e

Comment thread rl_games/common/experience.py Outdated
else:
self.truncated.zero_()
if self.discounts is not None:
self.discounts.copy_(state['discounts'].to(self.device))

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.

This raises KeyError when loading a 1-step checkpoint into an n-step buffer. state.get('discounts') with a fallback to γ for old rows avoids it.


Generated by Claude Code

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: discounts fall back to gamma for rows saved by a 1-step buffer. Test added. c91669e

- ReturnScaler resets G after the step that ends an episode (the terminal reward stayed out of its own return and leaked into the next one).
- Held noise is drawn per env, fresh at each episode start, and stays on the device (no host sync per draw).
- min_alpha in the flash path: one floored temperature in the critic target and the actor loss, log alpha clamped at the floor.
- Log the categorical target mass on the two edge bins; docs give the entropy shift for sizing v_min.
- Replay: loading a 1-step checkpoint into an n-step buffer fills discounts with gamma; the 1-step path also counts terminated + truncated as terminated; int32 final-obs slots; a grown host pool frees its old pages; a one-time report of 16-bit obs rounding.
- Warn when the scalar flash head runs without normalize_reward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ViktorM pushed a commit that referenced this pull request Nov 8, 2026
Conflicts: the return scaler keeps its cross-rank pooling and takes the previous-step done; the alpha floor clamp
moves into _actor_opt_step so the CUDA-graph update gets it too; the categorical edge mass is returned by
_critic_heads_loss and logged on the host (stats appended inside a captured graph would never update).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ViktorM

ViktorM commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Review fixes pushed in c91669e: return scaler episode end, n-step load from a 1-step checkpoint, per-env held noise, one floored alpha in the flash path, edge-bin target mass, int32 slots, host pool release, 16-bit obs rounding report, scalar-head warning. 80 SAC tests pass on CPU and the mapped-replay test on GPU.

@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 c91669e. The review fixes check out: ReturnScaler now closes the episode on its terminal step (your 1, 1.9, 2.71, 1.0 example passes), held noise is per env and on-device, one floored alpha in the flash target and actor loss with log_alpha clamped at the floor, discounts falls back to gamma for 1-step checkpoints, int32 final slots, released host pool pages. Locally the SAC suite passes on the new head (80 passed, 1 CUDA skip, gymnasium 1.3.0 / numpy 2.4.6 / torch 2.12), and the default-path digest still matches master.

Blocking: CI is red on all four Python versions. The 1-step VectorizedReplayBuffer.add now stores truncated & ~done, and that breaks 7 tests in tests/test_replay_oversized_batches.py from #384, which stores both flags independently (dones = id % 2 == 0, truncated = id % 3 == 0) and asserts they round-trip unchanged:

FAILED tests/test_replay_oversized_batches.py::test_oversized_add_matches_chronological_queue[2,3,5,8]
FAILED tests/test_replay_oversized_batches.py::test_checkpoint_restore_and_further_writes_preserve_ring_position
FAILED tests/test_replay_oversized_batches.py::test_sampling_returns_only_retained_and_aligned_transition_fields
FAILED tests/test_replay_oversized_batches.py::test_empty_and_single_wrap_controls_keep_original_contract
E   AssertionError: truncated

Either keep the 1-step path storing the flags as given (the n-step and memory-efficient paths can keep "termination wins", which is where it matters for the bootstrap), or update the #384 fixture so the two flags are exclusive and say so in the docstring. I'd prefer the first: the agent never produces a row with both flags, so the 1-step change buys nothing and costs a contract change.

Will approve once CI is green.

Brings the branch up to master acf0d8f (29 commits). No conflicts; players.py auto-merged
(the SAC player keeps action_groups and gains master's no-grad inference).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZqz94VdW57VEwskjHB
The 1-step VectorizedReplayBuffer.add masked truncated with ~done. That broke the store-as-given
contract that tests/test_replay_oversized_batches.py pins (7 failures), and it cannot change training:
the 1-step target reads only `done`, and the agent already passes exclusive flags
(terminated = dones & ~time_outs). Three fixed-seed runs through this path (exclusive flags,
coincident flags from the env, value_bootstrap off) end with bit-identical weights with and without
the mask. The mask would also clear every time-out flag for a caller whose `done` is
terminated | time_out. The n-step folder and the memory-efficient ring keep the documented rule
(a step with both flags counts as terminated), where it decides the bootstrap.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZqz94VdW57VEwskjHB
One 30-epoch run sat too close to the threshold: seeds 0-5 gave 0.29-0.58 against ~0.29, and CI got
0.27 at seed 3 where another machine got 0.42. A single run also dips (seed 0: 0.83 after 45 epochs,
0.29 after 60). The test now averages seeds 1-3 after 45 epochs (~0.57 here, about twice the threshold).

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

@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 3e98960 and 5d8b0dc on top of the master merge (clean, no conflict hunks). The 1-step buffer stores the flags as given again, which is the option I preferred; the n-step folder and the memory-efficient ring keep termination-wins where it decides the bootstrap. The point-mass learning test now averages three seeds over 45 epochs. CI green on 5d8b0dc; locally the replay, SAC digest, flash, correctness and terminal-obs files pass (115 passed, 1 CUDA skip). Approving.

@Denys88
Denys88 merged commit 81924de into master Nov 23, 2026
6 checks passed
ViktorM pushed a commit that referenced this pull request Nov 23, 2026
#395 landed on master as one squash commit (81924de), while this branch still carries its original
commits, so six files conflicted. Master's copies of every #395 file are identical to 5d8b0dc, which
this branch already contains, so each conflict resolves to this branch's side. The diff against master
is the multi-GPU work alone: 14 files, +803 / -64.

A merge rather than `git rebase --onto master 5d8b0dc`: the rebase would drop b5c6457, the merge
commit that carries the hand-written integration of the #395 review fixes into the CUDA-graph path
(alpha clamp inside the captured step, edge-bin stats returned from it).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZqz94VdW57VEwskjHB
ViktorM pushed a commit that referenced this pull request Nov 25, 2026
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
ViktorM added a commit that referenced this pull request Nov 25, 2026
A clean merge: no file needed a change by hand. Master brings the FlashSAC
options (#395), multi-GPU SAC with update_cuda_graph (#396) and the fix
series of #391 to #426. PBT still supports the PPO agents only and refuses
SAC. Both sides had changed README.md, central_value.py, a2c_common.py,
torch_runner.py and tests/test_release_blockers.py, in separate places.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

3 participants