Repository navigation
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
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
perf(flash_sac): the residual blocks of the ensemble critic produce their weight gradient contiguous in[ensemble, out, in]throughEnsembleBlockLinear(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 defaultfalse, 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:FlatAdamruns 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 joinedobs/next_obsrows.fix(base): the eager masked autoreset body keepsself._statebound to the objectupdate_statereturned, sostep()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.loss_rows_onlychanges where BatchNorm statistics come from.Why these are UniLab-layer changes, and what was left out
unilab.rl.algosfuse_learner_stepsunilab.rl.algos.flash_sacloss_rows_only(not an exact rewrite, so opt-in)unilab.rl.algos.flash_sac.layersunilab.baseBenefit 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.
FlatAdamandTableLerpare 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 rejectsfuse_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).RowRenormalizercovers the six unit-parameter layers; a module with any othernormalize_parametersowner, or rows wider than 4096, keeps the eager walk.fuse_learner_stepsonly 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 withFlatAdam, verified equal to the stock fallback.loss_rows_onlyis rejected for custom actors (actor_config), whose auxiliary losses may read every row.Linked Work
mainValidation
make test-allequivalents on the final local head, run as the individual commands withuv run --no-sync(RTX 4090, CPython 3.13.14, torch 2.14.0+cu130, unisim-core 2.9.2):tests/rl/algos/test_flash_sac_fast_path.py,tests/base/test_torch_env_masked_state_binding.py, 13 tests):FlatAdamvstorch.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.EnsembleBlockLinearvs the einsum path: forward, input gradient and weight gradient bitwise on CUDA (fp32 and bf16 autocast); frozen weight yields no weight gradient.RowRenormalizervs the eager walk,TableLerpvs per-parameterlerp_.set_gradient_syncis rejected; the flag is a no-op off the whole-cycle path.loss_rows_onlyequals the joined objective (loss and gradients) once BatchNorm uses running statistics; custom actors are rejected.update_statereturns its own state object publishes that step's reward / terminated / reset rows through the eager masked body; fails onmain.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.
learning_timefuse_learner_steps+loss_rows_onlyfuse_learner_steps+loss_rows_onlyNumerics/*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
fuse_learner_stepsis rejected rather than validated; the two-GPU DP graph test was not run with the fused path.loss_rows_onlychanges 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.fuse_learner_stepson is a one-line follow-up once another task has soaked on it.