Skip to content

perf(flash_sac): opt-in fused whole-cycle learner steps and loss_rows_only, contiguous block weight gradients; fix the eager masked-autoreset state binding - #2692

Merged
TATP-233 merged 5 commits into
mainfrom
perf/issue-2689-flash-sac-learner-fast-path
Dec 3, 2026

Conversation

@TATP-233

@TATP-233 TATP-233 commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • perf(flash_sac): the residual blocks of the ensemble critic produce their weight gradient contiguous in [ensemble, out, in] through EnsembleBlockLinear (same three GEMMs as the einsum path). Forward outputs and gradients are unchanged — bitwise on CUDA; the CPU GEMM backends differ in summation order within 1e-6.
  • perf(flash_sac): two opt-in learner switches, both default false, so no existing config changes behavior:
    • algo.algo_params.fuse_learner_steps — on the NVIDIA CUDA whole-cycle path, the non-GEMM steps of an update are fused: FlatAdam runs the Adam step over one flat buffer per parameter group with the fused kernel's contract and checkpoint layout; parameter normalization and the Polyak update become one Triton kernel each through device pointer tables; autograd hands its fresh gradients to .grad; the actor update no longer computes critic weight gradients.
    • algo.algo_params.loss_rows_only — each network of the training objectives runs only on the rows its loss reads instead of the joined obs / next_obs rows.
  • fix(base): the eager masked autoreset body keeps self._state bound to the object update_state returned, so step() no longer publishes a stale state when the body runs in Python (the warm-up steps before capture, eager fallbacks) and the owner returns its own state object. No-op for UniLab's own owners.
  • Why: these were developed and measured in a downstream (lean-retarget#239, humanoid hand–object tracking, 2048 envs, UTD 16, RTX 6000D). Per update: learner 69 → 56 ms (fused steps: Adam −5.55, normalization −2.95, frozen critic −2.77, gradient handover −1.74, Polyak −0.36), block weight gradients −1.4 ms (clones removed), loss rows only −16 ms (GEMM and BatchNorm work halves). End to end on the downstream's stock physics stack, 90 → 67 ms/iteration.
  • User-facing / training impact: defaults unchanged. With the switches on, parameters agree with the stock path to a few ulps; trajectories are not bit-identical because kernel summation orders change and loss_rows_only changes where BatchNorm statistics come from.

Why these are UniLab-layer changes, and what was left out

Piece Owner In this PR
FlashSAC update steps (Adam, parameter normalization, Polyak, actor update) unilab.rl.algos yes — fuse_learner_steps
Objective row layout unilab.rl.algos.flash_sac yes — loss_rows_only (not an exact rewrite, so opt-in)
Ensemble linear backward layout unilab.rl.algos.flash_sac.layers yes — unconditional, exact
Masked autoreset state binding unilab.base yes — #2685
Collector step graph, reset-graph capture workarounds (#2681, #2686, #2687, #2688) UniLab gaps / task-side orchestration not implemented here
Physics kernels (mujoco-warp / unisim) unisim #603 / #604 not here
Fused BatchNorm / Inductor search-space experiments slower or noise-level not ported

Benefit for other tasks: the fused steps remove a fixed per-update cost, so every FlashSAC task on the NVIDIA whole-cycle path gains, most when networks are small and latency bound. FlatAdam and TableLerp are algorithm-agnostic (rl/algos/common); the continuous SAC learner also uses fused Adam and Polyak but has gradient clipping and a target actor, was not validated, and is not switched. The data-parallel whole-cycle path rejects fuse_learner_steps (not validated there).

Implementation notes

  • FlatAdam.state_dict() returns standalone tensors with one step per parameter. The live state shares one flat buffer and one step counter per group; handing those out made a stock fused Adam that resumed the checkpoint deviate by 1e-4 per step (its foreach kernels coalesce state tensors that are views of one storage).
  • RowRenormalizer covers the six unit-parameter layers; a module with any other normalize_parameters owner, or rows wider than 4096, keeps the eager walk.
  • fuse_learner_steps only takes effect on the whole-cycle path (_compile_full_update_cycle); on CPU / MPS / eager it is a no-op. A failed graph capture keeps running the compiled objectives eagerly with FlatAdam, verified equal to the stock fallback.
  • loss_rows_only is rejected for custom actors (actor_config), whose auxiliary losses may read every row.

Linked Work

Validation

  • make test-all equivalents on the final local head, run as the individual commands with uv run --no-sync (RTX 4090, CPython 3.13.14, torch 2.14.0+cu130, unisim-core 2.9.2):
uv run --no-sync ruff format --check .            # 566 files already formatted
uv run --no-sync ruff check .                     # All checks passed!
uv run --no-sync ruff check tests --select F401,F821,F811,F841 --output-format concise   # All checks passed!
uv run --no-sync mypy src/unilab                  # Success: no issues found in 215 source files
uv run --no-sync pyright                          # 0 errors, 1 warning (pre-existing: base/__init__.py:13)
uv run --no-sync interrogate src/unilab           # PASSED (minimum 40.0%, actual 49.6%)
uv run --no-sync pytest -m "not slow" --cov=src/unilab --cov-report=term-missing -q   # 3027 passed, 68 skipped
uv run --no-sync python scripts/benchmark/smoke_test.py   # module-mode 35/35, script-mode 36/36
  • New tests (tests/rl/algos/test_flash_sac_fast_path.py, tests/base/test_torch_env_masked_state_binding.py, 13 tests):
    • FlatAdam vs torch.optim.Adam(fused=True, capturable=True): five steps within 1e-7; a non-finite step leaves parameters, moments and counters untouched; checkpoint round trip in both directions, each counter advancing once per step.
    • EnsembleBlockLinear vs the einsum path: forward, input gradient and weight gradient bitwise on CUDA (fp32 and bf16 autocast); frozen weight yields no weight gradient.
    • RowRenormalizer vs the eager walk, TableLerp vs per-parameter lerp_.
    • Fused vs stock whole-cycle learner over three captured cycles (metrics equal, parameters within 1e-6); NaN reward skips the critic step and the Polyak update inside the graph; a fused-written checkpoint resumes equally in a fresh stock and a fresh fused learner; eager fallback after a failed capture equals the stock fallback; DP set_gradient_sync is rejected; the flag is a no-op off the whole-cycle path.
    • loss_rows_only equals the joined objective (loss and gradients) once BatchNorm uses running statistics; custom actors are rejected.
    • bug: masked autoreset body 由 Python 执行时 _reset 把 self._state 重绑到 _working_state,本步公开的 terminated/obs/reward 不是 update_state 的返回值;图 replay 时不重绑 #2685 regression: an owner whose update_state returns its own state object publishes that step's reward / terminated / reset rows through the eager masked body; fails on main.
  • Downstream end to end (lean-retarget#239 with its own learner-side implementation switched off, this branch's source first on PYTHONPATH, fuse_learner_steps=true loss_rows_only=true, RTX 5090, 2048 envs, UTD 16, capacity 1024, MPS, 3000 iterations):

Both runs rc=0, 3000 iterations completed, no numerical failure. Reference: the same downstream with its own learner-side implementation switched on (lean-retarget#239 defaults), same machine and launcher.

learner implementation seed iteration (step ≥ 1000) learning_time training wall tail steps/s final return final SR last-500 return / SR
this branch, fuse_learner_steps + loss_rows_only 42 58.18 ms 53.58 ms 183.0 s 35,091 7.79 96.5% 7.40 / 95.5%
this branch, fuse_learner_steps + loss_rows_only 43 57.93 ms 53.03 ms 182.3 s 35,437 7.16 95.9% 7.51 / 95.6%
downstream's own (lean-retarget#239 defaults) 42 58.53 ms 51.77 ms 183.1 s 34,370 7.49 96.0% 7.31 / 95.3%
downstream's own (lean-retarget#239 defaults) 43 (shared GPU, timing not comparable) 61.82 ms 53.07 ms 192.1 s 34,506 6.87 96.5% 7.37 / 95.3%

Numerics/* maxima are 0 in all four runs. Speed and training results agree with the downstream's own implementation; endpoints stay within the seed-to-seed spread. This branch's source ran against the downstream's environment (unisim-core 2.8.6, torch 2.9.0+cu128) rather than the pinned 2.9.2.

Caveats

  • Data-parallel whole-cycle training with fuse_learner_steps is rejected rather than validated; the two-GPU DP graph test was not run with the fused path.
  • loss_rows_only changes the training-mode BatchNorm statistics (2048 instead of 4096 rows at batch 2048); treat it as a training-recipe change, validated only on the downstream above.
  • Defaults are left off so no other FlashSAC downstream changes behavior on bump; flipping fuse_learner_steps on is a one-line follow-up once another task has soaked on it.

…emble critic

The compiled backward of EnsembleUnitLinear's einsum delivers the bmm weight
gradient to AccumulateGrad as a transposed view, which it cannot adopt: every
residual block weight gradient (2.1M elements, four per critic update) is
cloned. EnsembleBlockLinear runs the same three GEMMs and returns the weight
gradient contiguous in [ensemble, out, in]; forward outputs and gradients are
unchanged (bitwise on CUDA).

Refs #2690
algo.algo_params.fuse_learner_steps (off by default, NVIDIA CUDA whole-cycle
path only) replaces the per-tensor eager steps of an update: FlatAdam runs the
Adam step over one flat buffer per parameter group with the fused kernel's
contract and checkpoint layout, parameter normalization and the Polyak update
become one Triton kernel each through device pointer tables, autograd hands
its fresh gradients to .grad, and the actor update no longer computes critic
weight gradients. Parameters agree with the stock path to a few ulps; the
in-graph NaN gate and checkpoints are unchanged, and the flag is rejected on
the data-parallel path.

algo.algo_params.loss_rows_only (off by default) runs each network of the
training objectives only on the rows its loss reads instead of the joined
obs / next_obs rows. It halves the GEMM and BatchNorm work per update but
changes where the training-mode BatchNorm statistics come from, so it is not
an exact rewrite.

Refs #2689, #2691
…et body

The eager masked autoreset body calls reset(), and the Manager-Based _reset
re-selects the working state, so self._state ended up pointing at UniLab's
working object while the body kept writing the object update_state returned.
When that object is not the working state, step() published stale
terminated / obs / reward on every step the body runs in Python (the warm-up
before capture and eager fallbacks), unlike a replayed body. Restore the
binding after the reset.

Fixes #2685
The CI pyright environment does not resolve triton, so the decorated kernels are
Unknown there and their kernel[grid](...) launches were reported as errors. Bind
both kernels through an Any alias, as replay_pipelines/fused_gather.py does.

Refs #2689
@TATP-233
TATP-233 merged commit 3c0d9a5 into main Dec 3, 2026
12 checks passed
@TATP-233
TATP-233 deleted the perf/issue-2689-flash-sac-learner-fast-path branch December 3, 2026 10:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant