From 305401f20b4541e5275b87f2c09dd1338e691a00 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 17:58:05 +0800 Subject: [PATCH 1/5] perf(flash_sac): produce contiguous block weight gradients in the ensemble 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 --- src/unilab/rl/algos/flash_sac/layers.py | 51 ++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/src/unilab/rl/algos/flash_sac/layers.py b/src/unilab/rl/algos/flash_sac/layers.py index 1e3eb8092..c475bd443 100644 --- a/src/unilab/rl/algos/flash_sac/layers.py +++ b/src/unilab/rl/algos/flash_sac/layers.py @@ -168,6 +168,53 @@ def normalize_parameters(self) -> None: self.weight.copy_(F.normalize(self.weight, dim=-1, eps=1e-8)) +class _BlockLinear(torch.autograd.Function): + """``bmm(x, w^T)`` for ``x[ensemble, rows, in]`` and ``w[ensemble, out, in]``. + + The compiled backward of the einsum path delivers the bmm's weight gradient to + AccumulateGrad as a transposed view, which AccumulateGrad cannot adopt: every block weight + gradient (2.1M elements, four per critic update) is cloned. This Function runs the same + three GEMMs with the same shapes and layouts and returns the weight gradient contiguous in + ``[ensemble, out, in]``. Like the einsum path it saves the autocast operands the forward + GEMM consumed, so the backward GEMMs need no extra casts. + """ + + @staticmethod + def forward(ctx, x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + ctx.weight_dtype = weight.dtype + weight = weight.to(x.dtype) + ctx.save_for_backward(x, weight) + return torch.bmm(x, weight.transpose(1, 2)) + + @staticmethod + def backward( + ctx, *grad_outputs: torch.Tensor + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + x, weight = ctx.saved_tensors + grad_out = grad_outputs[0].to(x.dtype) + grad_x = torch.bmm(grad_out, weight) if ctx.needs_input_grad[0] else None + grad_w = torch.bmm(grad_out.transpose(1, 2), x) if ctx.needs_input_grad[1] else None + if grad_w is not None: + grad_w = grad_w.to(ctx.weight_dtype) + return grad_x, grad_w + + +class EnsembleBlockLinear(EnsembleUnitLinear): + """Residual-block linear whose weight gradient is produced contiguous (#2690). + + The embedder and the categorical head stay on the einsum path: their narrow weights save + in the contiguous orientation about as much as the separate backward costs them. + """ + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # The cast autocast would apply inside the matmul, made explicit so that the Function + # can save the cast operand for its backward. + device_type = x.device.type + if torch.is_autocast_enabled(device_type): + x = x.to(torch.get_autocast_dtype(device_type)) + return cast(torch.Tensor, _BlockLinear.apply(x, self.weight)) + + class EnsembleUnitBatchNorm(nn.Module): running_mean: torch.Tensor running_var: torch.Tensor @@ -239,9 +286,9 @@ def forward(self, x: torch.Tensor, training: bool) -> torch.Tensor: class EnsembleBlock(nn.Module): def __init__(self, num_ensemble: int, hidden_dim: int, expansion: int = 4): super().__init__() - self.w1 = EnsembleUnitLinear(num_ensemble, hidden_dim, hidden_dim * expansion) + self.w1 = EnsembleBlockLinear(num_ensemble, hidden_dim, hidden_dim * expansion) self.norm1 = EnsembleUnitBatchNorm(num_ensemble, hidden_dim * expansion) - self.w2 = EnsembleUnitLinear(num_ensemble, hidden_dim * expansion, hidden_dim) + self.w2 = EnsembleBlockLinear(num_ensemble, hidden_dim * expansion, hidden_dim) self.norm2 = EnsembleUnitBatchNorm(num_ensemble, hidden_dim) def forward(self, x: torch.Tensor, training: bool) -> torch.Tensor: From 4cea00d57d7bead1aee5bcb4aa99c801850e63a6 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 17:58:05 +0800 Subject: [PATCH 2/5] perf(flash_sac): fuse whole-cycle learner steps and add loss_rows_only 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 --- src/unilab/conf/flashsac/config.yaml | 2 + src/unilab/rl/algos/common/flat_adam.py | 224 ++++++++ src/unilab/rl/algos/common/kernels.py | 105 ++++ .../rl/algos/flash_sac/double_buffer.py | 2 + src/unilab/rl/algos/flash_sac/kernels.py | 175 +++++++ src/unilab/rl/algos/flash_sac/learner.py | 184 +++++-- src/unilab/structured_configs.py | 7 + tests/rl/algos/test_flash_sac_fast_path.py | 479 ++++++++++++++++++ 8 files changed, 1148 insertions(+), 30 deletions(-) create mode 100644 src/unilab/rl/algos/common/flat_adam.py create mode 100644 src/unilab/rl/algos/common/kernels.py create mode 100644 src/unilab/rl/algos/flash_sac/kernels.py create mode 100644 tests/rl/algos/test_flash_sac_fast_path.py diff --git a/src/unilab/conf/flashsac/config.yaml b/src/unilab/conf/flashsac/config.yaml index aa4adc43b..8605f2a2a 100644 --- a/src/unilab/conf/flashsac/config.yaml +++ b/src/unilab/conf/flashsac/config.yaml @@ -62,6 +62,8 @@ algo: compile_full_objectives: true dp_whole_cycle_cuda_graph: true use_whole_cycle_cuda_graph: true + fuse_learner_steps: false + loss_rows_only: false training: task_name: G1WalkFlat diff --git a/src/unilab/rl/algos/common/flat_adam.py b/src/unilab/rl/algos/common/flat_adam.py new file mode 100644 index 000000000..ad1b3e116 --- /dev/null +++ b/src/unilab/rl/algos/common/flat_adam.py @@ -0,0 +1,224 @@ +"""Adam over one flat buffer per parameter group, for whole-cycle CUDA graphs. + +UniLab arms every optimizer step on device: ``found_inf`` / ``grad_scale`` live on the +optimizer, ``lr`` is staged as a CUDA tensor before each captured ``step()``, and a non-finite +loss has to leave parameters, moments and step counters untouched. +``torch.optim.Adam(fused=True, capturable=True)`` meets that contract, but its multi-tensor +kernel is latency bound at FlashSAC's sizes: it gives one 512-thread block to each 16k-element +chunk, so a step costs about the same for the actor's 1.2M and the critic's 9M elements. +:class:`FlatAdam` keeps the contract, the state layout and ``state_dict`` while laying the +group's parameters, gradients and moments out as 16-element aligned segments of one flat CUDA +buffer each, so a single compiled kernel serves the whole group. + +The re-layout happens before anything is compiled or captured: parameters keep their identity +and ``p.data`` becomes a view, autograd accumulates into gradient views, and ``state[p]`` holds +views plus the group's shared step counter. +""" + +from __future__ import annotations + +from typing import Any + +import torch +from torch.optim.optimizer import ( + _use_grad_for_differentiable, # pyright: ignore[reportPrivateImportUsage] +) + +ALIGN = 16 # elements per segment boundary: 64-byte aligned starts for every parameter + + +def _round_up(value: int, multiple: int) -> int: + return (value + multiple - 1) // multiple * multiple + + +@torch.compile(dynamic=False) +def _adam_scalars( + step: torch.Tensor, lr: torch.Tensor, found_inf: torch.Tensor, betas: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return the fused kernel's per-step scalars and advance the step counter. + + Bias corrections and ``lr / bias_correction1`` are evaluated in float64 and rounded to + float32 (``opmath_t``), exactly like the kernel; ``step`` moves by ``1 - found_inf`` (the + kernel path adds one before and subtracts ``found_inf`` after the launch). Kept apart from + the elementwise kernel so the float64 ``pow`` is not recomputed per element. + """ + skip = found_inf != 0 + next_step = step + 1 - skip.to(torch.float32) + step64 = next_step.to(torch.float64) + bias1 = (1 - torch.pow(betas[0], step64)).to(torch.float32) + bias2_sqrt = torch.sqrt(1 - torch.pow(betas[1], step64)).to(torch.float32) + step_size = (lr.to(torch.float64) / bias1).to(torch.float32) + step.copy_(next_step) + return step_size, bias2_sqrt, skip + + +@torch.compile(dynamic=False) +def _adam_elements( + flat_p: torch.Tensor, + flat_g: torch.Tensor, + flat_m: torch.Tensor, + flat_v: torch.Tensor, + grad_scale: torch.Tensor, + coef: torch.Tensor, + eps: torch.Tensor, + step_size: torch.Tensor, + bias2_sqrt: torch.Tensor, + skip: torch.Tensor, +) -> None: + """Apply one fused-Adam step over the flat buffers; ``skip`` leaves every output unchanged. + + ``coef`` is ``[beta1, beta2, 1 - beta1, 1 - beta2]`` in float64: the fused kernel forms the + moments with float64 products and rounds them to float32 (``opmath_t``), and so does this. + The parameter update and the denominator are float32 in both, as in the kernel. + """ + f32, f64 = torch.float32, torch.float64 + grad = (flat_g / grad_scale).to(f64) # exact for grad_scale == 1, which UniLab always uses + m = (coef[0] * flat_m.to(f64) + coef[2] * grad).to(f32) + v = (coef[1] * flat_v.to(f64) + coef[3] * grad * grad).to(f32) + denom = (torch.sqrt(v) / bias2_sqrt + eps).to(f32) + p = flat_p - step_size * m / denom + flat_p.copy_(torch.where(skip, flat_p, p)) + flat_m.copy_(torch.where(skip, flat_m, m)) + flat_v.copy_(torch.where(skip, flat_v, v)) + + +class FlatAdam(torch.optim.Adam): + """``torch.optim.Adam`` whose group state lives in one flat CUDA buffer per role. + + The optimizer contract of the capturable fused Adam is unchanged: ``found_inf`` and + ``grad_scale`` are read from the optimizer at every step, ``lr`` may be a device tensor, + and a checkpoint written by either optimizer loads into the other. Construction re-lays + the parameters out, so it has to happen before anything captures their addresses. + """ + + def __init__(self, params, **kwargs) -> None: + for name in ("amsgrad", "maximize", "decoupled_weight_decay"): + if kwargs.get(name): + raise ValueError(f"FlatAdam does not support {name}") + if kwargs.get("weight_decay", 0): + raise ValueError("FlatAdam does not support weight_decay") + super().__init__(params, capturable=True, foreach=False, fused=False, **kwargs) + (group,) = self.param_groups + # Keep the fused optimizer's flags in param_groups: they are part of the checkpoint and + # a stock fused Adam resuming this state must stay fused. + group.update(fused=True, foreach=None) + device = group["params"][0].device + self._never = torch.zeros((), device=device) + self._ones = torch.ones((), device=device) + betas = group["betas"] + self._betas = torch.tensor(betas, dtype=torch.float64, device=device) + self._one_minus = torch.tensor( + [1 - beta for beta in betas], dtype=torch.float64, device=device + ) + self._step = torch.zeros((), dtype=torch.float32, device=device) + self._segments: list[tuple[torch.Tensor, int, int]] = [] # (parameter, offset, numel) + self._relayout() + self._coef = torch.cat((self._betas, self._one_minus)) + self._eps = torch.tensor(group["eps"], dtype=torch.float64, device=device) + + @property + def _params(self) -> list[torch.Tensor]: + return [p for group in self.param_groups for p in group["params"]] + + def _relayout(self) -> None: + params = self._params + if any( + p.device.type != "cuda" or p.dtype != torch.float32 or not p.is_contiguous() + for p in params + ): + raise ValueError("FlatAdam needs contiguous float32 CUDA parameters") + self._segments, total = [], 0 + for p in params: + self._segments.append((p, total, p.numel())) + total = _round_up(total + p.numel(), ALIGN) + self._flat = { + name: torch.zeros(total, device=params[0].device) for name in ("p", "g", "m", "v") + } + with torch.no_grad(): + for p, offset, numel in self._segments: + flat_p = self._flat["p"][offset : offset + numel] + flat_p.copy_(p.detach().reshape(-1)) + p.data = flat_p.view(p.shape) + self._adopt_state(stepping=False) + + def _adopt_state(self, *, stepping: bool) -> None: + """Point ``state[p]`` and ``p.grad`` at flat views, folding tensors that are not views. + + UniLab replaces ``p.grad`` with plain tensors in its cold paths and autograd hands over + a fresh tensor whenever ``.grad`` was unset before the backward; both are copied into + the flat gradient buffer here, in one ``_foreach_copy_`` launch. + """ + flat_g, stale = self._flat["g"], [] + for p, offset, numel in self._segments: + entry = self.state.get(p) + if entry and entry["exp_avg"].data_ptr() != self._flat["m"].data_ptr() + 4 * offset: + self._flat["m"][offset : offset + numel].copy_(entry["exp_avg"].reshape(-1)) + self._flat["v"][offset : offset + numel].copy_(entry["exp_avg_sq"].reshape(-1)) + self._step.copy_(entry["step"]) + self.state[p] = { + "step": self._step, + "exp_avg": self._flat["m"][offset : offset + numel].view(p.shape), + "exp_avg_sq": self._flat["v"][offset : offset + numel].view(p.shape), + } + if p.grad is None: + if stepping: + raise RuntimeError( + f"FlatAdam: parameter of shape {tuple(p.shape)} has no gradient" + ) + elif p.grad.data_ptr() != flat_g.data_ptr() + 4 * offset: + stale.append((p.grad.reshape(-1), flat_g[offset : offset + numel])) + p.grad = flat_g[offset : offset + numel].view(p.shape) + if stale: + torch._foreach_copy_( + [destination for _source, destination in stale], + [source for source, _destination in stale], + ) + + def state_dict(self) -> dict[str, Any]: + """Return the fused Adam checkpoint layout: standalone tensors, one step per parameter. + + The update works on shared flat buffers and one step counter. Handing those objects + out would make a stock Adam that resumes the checkpoint misbehave: its foreach + kernels coalesce state tensors that are views of one storage, and it would advance a + shared step counter once per parameter. + """ + packed: dict[str, Any] = super().state_dict() + packed["state"] = { + key: {name: value.clone() for name, value in entry.items()} + for key, entry in packed["state"].items() + } + for entry in packed["state"].values(): + entry["step"] = self._step.clone() + return packed + + def load_state_dict(self, state_dict: dict) -> None: + super().load_state_dict(state_dict) + self._adopt_state(stepping=False) + + @_use_grad_for_differentiable + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + (group,) = self.param_groups + lr = group["lr"] + if not torch.is_tensor(lr): + lr = torch.tensor(float(lr), device=self._step.device) + self._adopt_state(stepping=True) + found_inf = getattr(self, "found_inf", self._never) + grad_scale = getattr(self, "grad_scale", self._ones) + step_size, bias2_sqrt, skip = _adam_scalars(self._step, lr, found_inf, self._betas) + _adam_elements( + self._flat["p"], + self._flat["g"], + self._flat["m"], + self._flat["v"], + grad_scale, + self._coef, + self._eps, + step_size, + bias2_sqrt, + skip, + ) + return loss diff --git a/src/unilab/rl/algos/common/kernels.py b/src/unilab/rl/algos/common/kernels.py new file mode 100644 index 000000000..be4aa5e3b --- /dev/null +++ b/src/unilab/rl/algos/common/kernels.py @@ -0,0 +1,105 @@ +"""Device-table Triton kernels shared by the off-policy learners. + +The kernels address a list of existing tensors through small device tables (pointer and +shape per tensor, one entry per program), so each call is a handful of launches with stable +addresses and nothing on the host side that a CUDA graph capture would reject. The tables bake +in the tensor addresses: build them after the optimizers re-lay the parameters out, and rebuild +after anything that re-allocates a parameter (#2689). +""" + +from __future__ import annotations + +from collections.abc import Callable + +import torch +import torch.nn as nn +import triton +import triton.language as tl + + +@triton.jit +def _lerp_rows(target, source, piece, offset, size, weight, BLOCK: tl.constexpr): + pid = tl.program_id(0) + i = tl.load(piece + pid) + start = tl.load(offset + pid) + t_ptr = tl.load(target + i).to(tl.pointer_type(tl.float32)) + start + s_ptr = tl.load(source + i).to(tl.pointer_type(tl.float32)) + start + offs = tl.arange(0, BLOCK) + valid = offs < tl.load(size + i) - start + t = tl.load(t_ptr + offs, mask=valid) + s = tl.load(s_ptr + offs, mask=valid) + w = tl.load(weight) + tl.store(t_ptr + offs, t + w * (s - t), mask=valid) + + +class TableLerp: + """``target_i += weight * (source_i - target_i)`` for every pair, in one kernel launch. + + ``torch._foreach_lerp_`` with a tensor weight performs a prohibited host sync while a CUDA + graph is being captured, so the Polyak update of a device-gated ``tau`` falls back to one + ``lerp_`` per parameter (19 kernels for the FlashSAC critic). This kernel does the same + ``t + w * (s - t)`` arithmetic with the weight read from the device. + """ + + BLOCK = 2048 + + def __init__(self, targets: list[torch.Tensor], sources: list[torch.Tensor]): + if len(targets) != len(sources) or not targets: + raise ValueError("TableLerp needs equally many targets and sources") + if any( + t.device != targets[0].device + or t.dtype != torch.float32 + or s.dtype != torch.float32 + or t.shape != s.shape + or not t.is_contiguous() + or not s.is_contiguous() + for t, s in zip(targets, sources, strict=True) + ): + raise ValueError("TableLerp needs contiguous float32 pairs of one device") + device = targets[0].device + # Host-side pointer snapshot (no device read): the tables bake in these addresses. + self._pointers = [ + (t.data_ptr(), s.data_ptr()) for t, s in zip(targets, sources, strict=True) + ] + blocks = [ + (i, start) for i, t in enumerate(targets) for start in range(0, t.numel(), self.BLOCK) + ] + + def column(values, dtype): + return torch.tensor(values, dtype=dtype, device=device) + + self._tables = ( + column([t for t, _s in self._pointers], torch.int64), + column([s for _t, s in self._pointers], torch.int64), + column([i for i, _s in blocks], torch.int32), + column([start for _i, start in blocks], torch.int32), + column([t.numel() for t in targets], torch.int32), + ) + self._targets, self._sources = targets, sources + + def __call__(self, weight: torch.Tensor) -> None: + if [ + (t.data_ptr(), s.data_ptr()) for t, s in zip(self._targets, self._sources, strict=True) + ] != self._pointers: + raise RuntimeError("TableLerp tensors were re-allocated; rebuild the tables") + target, source, piece, offset, size = self._tables + _lerp_rows[(piece.numel(),)]( + target, + source, + piece, + offset, + size, + weight, + BLOCK=self.BLOCK, + num_warps=4, # pyright: ignore[reportCallIssue] + ) + + +def build_polyak_update( + target: nn.Module, source: nn.Module +) -> Callable[[torch.Tensor], None] | None: + """Return a one-kernel Polyak update for the parameter pairs, or ``None`` if unsupported.""" + try: + return TableLerp(list(target.parameters()), list(source.parameters())) + except ValueError: + return None diff --git a/src/unilab/rl/algos/flash_sac/double_buffer.py b/src/unilab/rl/algos/flash_sac/double_buffer.py index 1784f22bc..f83645c9a 100644 --- a/src/unilab/rl/algos/flash_sac/double_buffer.py +++ b/src/unilab/rl/algos/flash_sac/double_buffer.py @@ -136,6 +136,8 @@ def build_double_buffer_runner( "critic_normalize_parameters": bool( _algo_param(cfg.algo, "critic_normalize_parameters", True) ), + "fuse_learner_steps": bool(_algo_param(cfg.algo, "fuse_learner_steps", False)), + "loss_rows_only": bool(_algo_param(cfg.algo, "loss_rows_only", False)), } learner = FlashSACLearner(device=device, **learner_kwargs) diff --git a/src/unilab/rl/algos/flash_sac/kernels.py b/src/unilab/rl/algos/flash_sac/kernels.py new file mode 100644 index 000000000..8fb918807 --- /dev/null +++ b/src/unilab/rl/algos/flash_sac/kernels.py @@ -0,0 +1,175 @@ +"""One Triton kernel for FlashSAC's post-step parameter normalization. + +The kernel addresses a list of existing tensors through small device tables (pointer and +shape per tensor, one entry per program), so each call is a handful of launches with stable +addresses and nothing on the host side that a CUDA graph capture would reject. The tables bake +in the tensor addresses: build them after the optimizers re-lay the parameters out, and rebuild +after anything that re-allocates a parameter (#2689). +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn as nn +import triton +import triton.language as tl + +from unilab.rl.algos.flash_sac import layers + +EPS = 1e-8 +# UnitLinear divides by max(||row||, eps); the normalization layers scale by sqrt(D) * rsqrt. +CLAMP, JOINT = tl.constexpr(1), 0 +MAX_ROW = 4096 # elements per row the single-block-per-row kernel handles +_WARPS = {256: 2, 512: 4, 1024: 4, 2048: 8, 4096: 16} + + +@triton.jit +def _renorm_rows(base, joint, len_a, len_b, gain, eps, mode, group, row, BLOCK: tl.constexpr): + pid = tl.program_id(0) + g = tl.load(group + pid) + r = tl.load(row + pid) + la = tl.load(len_a + g) + lb = tl.load(len_b + g) + a_ptr = tl.load(base + g).to(tl.pointer_type(tl.float32)) + r * la + b_ptr = tl.load(joint + g).to(tl.pointer_type(tl.float32)) + r * lb + offs = tl.arange(0, BLOCK) + in_a, in_b = offs < la, (offs >= la) & (offs < la + lb) + a = tl.load(a_ptr + offs, mask=in_a, other=0.0) + b = tl.load(b_ptr + offs - la, mask=in_b, other=0.0) + total = tl.sum(a * a, axis=0) + tl.sum(b * b, axis=0) + e = tl.load(eps + g) + denom = tl.maximum(tl.sqrt_rn(total), e) + factor = tl.load(gain + g) * tl.rsqrt(total + e) + clamp = tl.load(mode + g) == CLAMP + # F.normalize divides; div_rn is the IEEE division ATen uses (Triton's "/" is div.full.f32). + tl.store(a_ptr + offs, tl.where(clamp, tl.math.div_rn(a, denom), a * factor), mask=in_a) + tl.store(b_ptr + offs - la, tl.where(clamp, tl.math.div_rn(b, denom), b * factor), mask=in_b) + + +def _groups(module: nn.Module) -> list[tuple[torch.Tensor, torch.Tensor | None, int, float]]: + """Return ``(first array, joint array or None, mode, gain)`` in the eager walk's order. + + Every child that owns a ``normalize_parameters`` method has to be one of the unit-parameter + layers the kernel knows; anything else raises so the caller keeps the eager walk. + """ + out = [] + for child in module.modules(): + if child is module or not callable(getattr(child, "normalize_parameters", None)): + continue + if isinstance(child, (layers.UnitLinear, layers.EnsembleUnitLinear)): + weight = child.w.weight if isinstance(child, layers.UnitLinear) else child.weight + out.append((weight, None, CLAMP, 1.0)) + elif isinstance(child, (layers.UnitBatchNorm, layers.EnsembleUnitBatchNorm)): + out.append((child.weight, child.bias, JOINT, math.sqrt(child.weight.shape[-1]))) + elif isinstance(child, (layers.UnitRMSNorm, layers.EnsembleUnitRMSNorm)): + out.append((child.weight, None, JOINT, math.sqrt(child.weight.shape[-1]))) + else: + raise TypeError( + f"RowRenormalizer does not know how to fuse {type(child).__name__}" + ".normalize_parameters" + ) + return out + + +def _fusable(groups: list[tuple[torch.Tensor, torch.Tensor | None, int, float]]) -> bool: + for first, joint, _mode, _gain in groups: + width = first.shape[-1] + (joint.shape[-1] if joint is not None else 0) + if ( + first.device.type != "cuda" + or first.dtype != torch.float32 + or not first.is_contiguous() + or triton.next_power_of_2(width) > MAX_ROW + ): + return False + if joint is not None and ( + joint.device != first.device + or joint.dtype != torch.float32 + or joint.shape != first.shape + or not joint.is_contiguous() + ): + return False + return True + + +class RowRenormalizer: + """Launch tables for one module; call to re-normalize all of its parameters in place. + + After every optimizer step FlashSAC calls ``module.normalize_parameters()``, which walks the + module tree and runs each unit-parameter layer as eager ops: about 30 small kernels for the + critic, each weight read and written three to five times. Every one of those operations is a + row-wise rescale, so the whole module fits one kernel per row-length class; a program loads + one row (a linear weight's row, or the (weight, bias) pair of a normalization layer), + reduces its sum of squares and writes the rescaled row back. The arithmetic per element is + the eager one; only the summation order of each row's sum of squares differs, so results + agree to the last couple of ulps. + """ + + @classmethod + def build(cls, module: nn.Module) -> RowRenormalizer | None: + """Return a renormalizer for ``module``, or ``None`` when the eager walk has to stay.""" + groups = _groups(module) + if not groups or not _fusable(groups): + return None + return cls(groups) + + def __init__(self, groups: list[tuple[torch.Tensor, torch.Tensor | None, int, float]]): + device = groups[0][0].device + + def column(values, dtype): + return torch.tensor(values, dtype=dtype, device=device) + + self._tables = ( + column([first.data_ptr() for first, _j, _m, _g in groups], torch.int64), + column( + [ + (joint if joint is not None else first).data_ptr() + for first, joint, _m, _g in groups + ], + torch.int64, + ), + column([first.shape[-1] for first, _j, _m, _g in groups], torch.int32), + column( + [joint.shape[-1] if joint is not None else 0 for _f, joint, _m, _g in groups], + torch.int32, + ), + column([gain for _f, _j, _m, gain in groups], torch.float32), + column([EPS] * len(groups), torch.float32), + column([mode for _f, _j, mode, _g in groups], torch.int32), + ) + # Host-side pointer check (no device read): the tables bake in these addresses. + self._pointers = [first.data_ptr() for first, _j, _m, _g in groups] + self._launches: list[tuple[torch.Tensor, torch.Tensor, int]] = [] + classes: dict[int, list[tuple[int, int]]] = {} + for index, (first, joint, _mode, _gain) in enumerate(groups): + width = first.shape[-1] + (joint.shape[-1] if joint is not None else 0) + rows = first.numel() // first.shape[-1] + classes.setdefault(triton.next_power_of_2(width), []).extend( + (index, r) for r in range(rows) + ) + for block, items in sorted(classes.items()): + self._launches.append( + ( + column([g for g, _r in items], torch.int32), + column([r for _g, r in items], torch.int32), + block, + ) + ) + + def __call__(self) -> None: + base, joint, len_a, len_b, gain, eps, mode = self._tables + for group, row, block in self._launches: + _renorm_rows[(row.numel(),)]( + base, + joint, + len_a, + len_b, + gain, + eps, + mode, + group, + row, + BLOCK=block, + num_warps=_WARPS.get(block, 16), # pyright: ignore[reportCallIssue] + ) diff --git a/src/unilab/rl/algos/flash_sac/learner.py b/src/unilab/rl/algos/flash_sac/learner.py index 8f80da23d..cd47a5c3e 100644 --- a/src/unilab/rl/algos/flash_sac/learner.py +++ b/src/unilab/rl/algos/flash_sac/learner.py @@ -12,6 +12,7 @@ import torch.optim as optim from unilab.rl.algos.common.compile import get_torch_compile_for_device +from unilab.rl.algos.common.flat_adam import FlatAdam from unilab.rl.algos.common.learner_base import ( WholeCycleLearnerMixin, fused_adam_supported, @@ -225,6 +226,8 @@ def __init__( dp_whole_cycle_cuda_graph: bool = False, actor_normalize_parameters: bool = True, critic_normalize_parameters: bool = True, + fuse_learner_steps: bool = False, + loss_rows_only: bool = False, actor_config: Mapping[str, Any] | None = None, ): self.actor_normalize_parameters = bool(actor_normalize_parameters) @@ -316,6 +319,12 @@ def __init__( "whole-cycle CUDA graph; set " "algo.algo_params.use_whole_cycle_cuda_graph=false" ) + if loss_rows_only: + raise ValueError( + "FlashSAC loss_rows_only only supports the built-in actor: the auxiliary " + "losses of a custom actor may read every row of its forward" + ) + self._loss_rows_only = bool(loss_rows_only) self._aux_loss_names: tuple[str, ...] | None = None if self._actor_spec is not None: self.actor = build_custom_actor( @@ -395,18 +404,36 @@ def __init__( else None ) lr_peak = learning_rate_peak if learning_rate_peak > 0 else actor_lr - # Fused Adam collapses the per-parameter host loop (and its per-param - # blocking `.item()` syncs on MPS) into one kernel; `capturable` - # stays CUDA-only. - _fused = fused_adam_supported(self.device.type) - optimizer_kwargs: dict[str, Any] = {"fused": _fused} - if _fused and self._performance_tier.supports_capturable_optimizer: - optimizer_kwargs["capturable"] = True - self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=lr_peak, **optimizer_kwargs) - self.critic_optimizer = optim.Adam(self.critic.parameters(), lr=lr_peak, **optimizer_kwargs) - self.temperature_optimizer = optim.Adam( - self.temperature.parameters(), lr=lr_peak, **optimizer_kwargs + # Whole-cycle capture wraps compiled objectives, so disabling compile + # also disables this dependent layer. The graph switch otherwise does + # not change which objective boundary Inductor compiles. + self._compile_full_update_cycle = bool( + graph_requested and self.use_compile and self._nvidia_cuda ) + # Fused learner steps (#2689) fuse the non-GEMM steps of an update into + # a few kernels. They only exist on the NVIDIA CUDA whole-cycle path. + self._fuse_learner_steps = bool(fuse_learner_steps and self._compile_full_update_cycle) + if self._fuse_learner_steps: + self.actor_optimizer: optim.Optimizer = FlatAdam(self.actor.parameters(), lr=lr_peak) + self.critic_optimizer = FlatAdam(self.critic.parameters(), lr=lr_peak) + self.temperature_optimizer = FlatAdam(self.temperature.parameters(), lr=lr_peak) + else: + # Fused Adam collapses the per-parameter host loop (and its per-param + # blocking `.item()` syncs on MPS) into one kernel; `capturable` + # stays CUDA-only. + _fused = fused_adam_supported(self.device.type) + optimizer_kwargs: dict[str, Any] = {"fused": _fused} + if _fused and self._performance_tier.supports_capturable_optimizer: + optimizer_kwargs["capturable"] = True + self.actor_optimizer = optim.Adam( + self.actor.parameters(), lr=lr_peak, **optimizer_kwargs + ) + self.critic_optimizer = optim.Adam( + self.critic.parameters(), lr=lr_peak, **optimizer_kwargs + ) + self.temperature_optimizer = optim.Adam( + self.temperature.parameters(), lr=lr_peak, **optimizer_kwargs + ) self._pending_actor_metric_values: torch.Tensor | None = None scheduler_fn = build_lr_lambda( @@ -438,12 +465,9 @@ def __init__( self._update_cycle_lr_cursors: dict[int, int] = {} self._capture_update_cycle = False self._update_cycle_capture_failed = False - # Whole-cycle capture wraps compiled objectives, so disabling compile - # also disables this dependent layer. The graph switch otherwise does - # not change which objective boundary Inductor compiles. - self._compile_full_update_cycle = bool( - graph_requested and self.use_compile and self._nvidia_cuda - ) + self._target_polyak: Callable[[torch.Tensor], None] | None = None + if self._fuse_learner_steps: + self._install_fused_learner_steps() if self._compile_full_update_cycle and self.scaler is not None: raise ValueError( "FlashSAC CUDA compile mode requires bf16 (or fp32); " @@ -485,8 +509,61 @@ def _whole_cycle_finite_gate(self) -> torch.Tensor: def _whole_cycle_target_modules(self) -> tuple[nn.Module, nn.Module]: return self.target_critic, self.critic + def _install_fused_learner_steps(self) -> None: + """Bind the one-kernel parameter normalization and Polyak update (#2689). + + Both bake parameter addresses into device tables, so they are built after the flat + optimizers re-laid the parameters out. A module whose layers the normalization kernel + does not cover keeps the eager walk; so does a non-CUDA device. + """ + # Triton is only guaranteed on the CUDA tiers that reach this method. + from unilab.rl.algos.common.kernels import build_polyak_update # noqa: PLC0415 + from unilab.rl.algos.flash_sac.kernels import RowRenormalizer # noqa: PLC0415 + + for module, normalize in ( + (self.actor, self.actor_normalize_parameters), + (self.critic, self.critic_normalize_parameters), + ): + if not normalize: + continue + renormalizer = RowRenormalizer.build(module) + if renormalizer is not None: + cast(Any, module).normalize_parameters = renormalizer + if self._device_type == "cuda": + target, source = self._whole_cycle_target_modules() + self._target_polyak = build_polyak_update(target, source) + + def _zero_optimizer_gradients(self, optimizer: optim.Optimizer) -> None: + """Drop gradients on the fused path so autograd hands its fresh tensors to ``.grad``. + + AccumulateGrad adopts the backward's output tensor when ``.grad`` is unset, and the + flat optimizer copies it into its buffer. In-place zeroing would instead make the + engine add every parameter's gradient onto a zero buffer (12 instead of 8 bytes per + critic element, plus a kernel per parameter). + """ + if not self._fuse_learner_steps: + super()._zero_optimizer_gradients(optimizer) + return + for group in optimizer.param_groups: + for parameter in group["params"]: + parameter.grad = None + + def soft_update_target(self) -> None: + """Polyak-average the target critic, gated by critic-update finiteness.""" + if self._target_polyak is None: + super().soft_update_target() + return + with self._whole_cycle_target_update_range(): + weight = self._target_tau * self._whole_cycle_finite_gate().to(self._target_tau.dtype) + self._target_polyak(weight) + def set_gradient_sync(self, sync: Callable[[Iterable[torch.Tensor]], None] | None) -> None: """Attach DP reduction; graph collectives require explicit opt-in hooks.""" + if sync is not None and self._fuse_learner_steps: + raise ValueError( + "FlashSAC fuse_learner_steps is not validated on the data-parallel path; " + "set algo.algo_params.fuse_learner_steps=false" + ) if sync != self._gradient_sync: self._reset_update_cycle_graph() self._gradient_graph_hooks = None @@ -676,26 +753,45 @@ def _full_critic_objective( critic_obs: torch.Tensor, critic_next_obs: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: - """Full critic forward/target/projection/loss objective.""" + """Full critic forward/target/projection/loss objective. + + Both critics run on the rows of ``obs`` and ``next_obs`` joined along the batch + axis, and each output keeps one half. With ``loss_rows_only`` (#2691) every network + only sees the rows its loss reads: the target critic the ``next_obs`` rows, the + online critic the ``obs`` rows. With equal batch statistics the loss and the + parameter gradients are those of the joined objective; what changes is where the + training-mode BatchNorm statistics come from. + """ gamma = self.gamma**self.n_step - obs_all = torch.cat([critic_obs, critic_next_obs], dim=0) + rows_only = self._loss_rows_only with torch.no_grad(): with self._autocast(): next_actions, actor_info = self.actor(next_obs, training=False) actor_entropy = self.temperature().detach() * actor_info["log_prob"] - act_all = torch.cat([actions, next_actions], dim=0) - qs_all, q_info_all = self.target_critic(obs_all, act_all, training=True) - next_q_values = qs_all.chunk(2, dim=1)[1] - next_q_log_probs_full = q_info_all["log_prob"].chunk(2, dim=1)[1] + if rows_only: + joined_obs, joined_actions = critic_next_obs, next_actions + else: + joined_obs = torch.cat([critic_obs, critic_next_obs], dim=0) + joined_actions = torch.cat([actions, next_actions], dim=0) + qs, q_info = self.target_critic(joined_obs, joined_actions, training=True) + next_q_log_probs = q_info["log_prob"] + if not rows_only: + qs = qs.chunk(2, dim=1)[1] + next_q_log_probs = next_q_log_probs.chunk(2, dim=1)[1] + next_q_values = qs support = cast(torch.Tensor, self.target_critic.predictor.support) with self._autocast(): - _, pred_info_all = self.critic(obs_all, act_all, training=True) - pred_log_probs = pred_info_all["log_prob"].chunk(2, dim=1)[0] + if rows_only: + _, pred_info = self.critic(critic_obs, actions, training=True) + pred_log_probs = pred_info["log_prob"] + else: + _, pred_info = self.critic(joined_obs, joined_actions, training=True) + pred_log_probs = pred_info["log_prob"].chunk(2, dim=1)[0] critic_loss = self._critic_objective( next_q_values, - next_q_log_probs_full, + next_q_log_probs, support, rewards, dones, @@ -724,11 +820,17 @@ def _full_actor_objective( (empty for the built-in actor); they are already included in ``actor_loss`` and are returned separately only for diagnostics. """ - obs_all = torch.cat([obs, next_obs], dim=0) with self._autocast(): - actions_all, actor_info_all = self.actor(obs_all, training=True) - actions = actions_all.chunk(2, dim=0)[0] - log_probs = actor_info_all["log_prob"].chunk(2, dim=0)[0] + # With ``loss_rows_only`` (#2691) the training actor only sees the ``obs`` + # rows; ``next_obs`` joined to them would only feed its batch statistics. + actor_rows = obs if self._loss_rows_only else torch.cat([obs, next_obs], dim=0) + actions_all, actor_info_all = self.actor(actor_rows, training=True) + if self._loss_rows_only: + actions = actions_all + log_probs = actor_info_all["log_prob"] + else: + actions = actions_all.chunk(2, dim=0)[0] + log_probs = actor_info_all["log_prob"].chunk(2, dim=0)[0] q_values, _ = self.critic(critic_obs, actions, training=False) actor_loss, entropy = self._actor_objective( log_probs, q_values, actions, expert_actions, self.temperature() @@ -806,6 +908,28 @@ def update_actor( batch: dict[str, torch.Tensor], *, read_metrics: bool = True, + ) -> dict[str, float]: + if self._fuse_learner_steps: + # No critic weight gradients while the actor updates (#2689). The loss comes + # from a compiled joint graph whose backward computes every input gradient + # before the engine drops the critic's; freezing the critic parameters removes + # those GEMMs from the compiled backward. The actor gradients are unchanged. + critic_parameters = list(self.critic.parameters()) + requires_grad = [parameter.requires_grad for parameter in critic_parameters] + for parameter in critic_parameters: + parameter.requires_grad_(False) + try: + return self._update_actor(batch, read_metrics=read_metrics) + finally: + for parameter, flag in zip(critic_parameters, requires_grad, strict=True): + parameter.requires_grad_(flag) + return self._update_actor(batch, read_metrics=read_metrics) + + def _update_actor( + self, + batch: dict[str, torch.Tensor], + *, + read_metrics: bool = True, ) -> dict[str, float]: obs = batch["obs"].to(self.device) next_obs = batch["next_obs"].to(self.device) diff --git a/src/unilab/structured_configs.py b/src/unilab/structured_configs.py index b77158545..411a1a8ab 100644 --- a/src/unilab/structured_configs.py +++ b/src/unilab/structured_configs.py @@ -145,6 +145,13 @@ class FlashSACAlgoParams: compile_full_objectives: bool = True # Capture the whole training cycle in a CUDA graph. use_whole_cycle_cuda_graph: bool = True + # Fuse the non-GEMM steps of each whole-cycle update (Adam, parameter + # normalization, Polyak update) into a few kernels. NVIDIA CUDA whole-cycle + # path only; rejected on the data-parallel path. + fuse_learner_steps: bool = False + # Run each network of the training objectives only on the rows its loss + # reads, instead of the joined obs / next_obs rows. + loss_rows_only: bool = False @dataclass diff --git a/tests/rl/algos/test_flash_sac_fast_path.py b/tests/rl/algos/test_flash_sac_fast_path.py new file mode 100644 index 000000000..16e2f1912 --- /dev/null +++ b/tests/rl/algos/test_flash_sac_fast_path.py @@ -0,0 +1,479 @@ +"""Fused FlashSAC learner steps on the NVIDIA CUDA whole-cycle path (#2689, #2690, #2691).""" + +from __future__ import annotations + +import copy +from typing import Any +from unittest import mock + +import pytest +import torch + +from unilab.rl.algos.common.flat_adam import FlatAdam +from unilab.rl.algos.flash_sac.layers import ( + EnsembleBlockLinear, + EnsembleUnitBatchNorm, + EnsembleUnitLinear, + UnitBatchNorm, +) +from unilab.rl.algos.flash_sac.learner import FlashSACLearner +from unilab.rl.algos.flash_sac.network import FlashSACActor, FlashSACDoubleCritic + +_CUDA = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA-only whole-cycle path") +_MODULES = ("actor", "critic", "target_critic", "temperature") +_OPTIMIZERS = ("actor_optimizer", "critic_optimizer", "temperature_optimizer") +_CYCLE = { + "updates_per_step": 4, + "policy_frequency": 2, + "target_frequency": 1, + "policy_before_critic": False, +} + + +def _cuda_learner(**overrides: Any) -> FlashSACLearner: + kwargs: dict[str, Any] = { + "obs_dim": 4, + "action_dim": 2, + "critic_obs_dim": 6, + "actor_hidden_dim": 16, + "critic_hidden_dim": 16, + "actor_num_blocks": 1, + "critic_num_blocks": 1, + "num_atoms": 5, + "device": "cuda:0", + "use_compile": True, + } + kwargs.update(overrides) + return FlashSACLearner(**kwargs) + + +def _batch(rows: int, device: str = "cuda:0") -> dict[str, torch.Tensor]: + generator = torch.Generator(device=device).manual_seed(5) + + def randn(*shape: int) -> torch.Tensor: + return torch.randn(*shape, device=device, generator=generator) + + return { + "obs": randn(rows, 4), + "critic": randn(rows, 6), + "actions": torch.tanh(randn(rows, 2)), + "rewards": randn(rows), + "next_obs": randn(rows, 4), + "next_critic": randn(rows, 6), + "dones": torch.zeros(rows, device=device), + "truncated": torch.zeros(rows, device=device), + } + + +def _cycle(learner: FlashSACLearner, seed: int, batch: dict[str, torch.Tensor]) -> dict[str, float]: + torch.manual_seed(seed) + learner.update_cycle(batch, **_CYCLE) + return learner.read_deferred_cycle_metrics() + + +def _assert_same_learners(left: FlashSACLearner, right: FlashSACLearner, *, atol: float) -> None: + for name in _MODULES: + torch.testing.assert_close( + getattr(left, name).state_dict(), + getattr(right, name).state_dict(), + rtol=1e-4, + atol=atol, + ) + for name in _OPTIMIZERS: + left_state = list(getattr(left, name).state.values()) + right_state = list(getattr(right, name).state.values()) + assert len(left_state) == len(right_state) + for entry_left, entry_right in zip(left_state, right_state, strict=True): + for key in ("step", "exp_avg", "exp_avg_sq"): + torch.testing.assert_close(entry_left[key], entry_right[key], rtol=1e-4, atol=atol) + + +def _sync_modules(target: FlashSACLearner, source: FlashSACLearner) -> None: + for name in _MODULES: + getattr(target, name).load_state_dict(getattr(source, name).state_dict()) + + +# --- FlatAdam --------------------------------------------------------------------- + + +@_CUDA +def test_flat_adam_matches_capturable_fused_adam_and_shares_checkpoints() -> None: + torch.manual_seed(0) + shapes = [(16, 8), (8,), (1,), (3, 5, 7)] + + def build(optimizer_type: type[torch.optim.Optimizer]) -> tuple[list, torch.optim.Optimizer]: + torch.manual_seed(0) + parameters = [torch.randn(shape, device="cuda") for shape in shapes] + return parameters, optimizer_type(parameters, lr=3e-4) + + def arm(optimizer: torch.optim.Optimizer, found_inf: torch.Tensor) -> None: + optimizer.found_inf = found_inf + optimizer.grad_scale = torch.ones((), device="cuda") + + def stock_adam(parameters: list, lr: float) -> torch.optim.Optimizer: + return torch.optim.Adam(parameters, lr=lr, fused=True, capturable=True) + + reference_params, reference = build(stock_adam) + flat_params, flat = build(FlatAdam) + assert flat_params[0].grad is not None + assert flat_params[0].grad.data_ptr() == flat._flat["g"].data_ptr() + for step in range(5): + torch.manual_seed(step) + gradients = [torch.randn_like(parameter) for parameter in reference_params] + found_inf = torch.zeros((), device="cuda") + for parameter, gradient in zip(reference_params, gradients, strict=True): + parameter.grad = gradient.clone() + for parameter, gradient in zip(flat_params, gradients, strict=True): + # Plain tensors rather than flat views: the optimizer has to fold them in. + parameter.grad = gradient.clone() + arm(reference, found_inf) + arm(flat, found_inf) + reference.step() + flat.step() + for expected, actual in zip(reference_params, flat_params, strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-6, atol=1e-7) + + # A non-finite loss skips the step: parameters, moments and counters stay put. + found_inf = torch.ones((), device="cuda") + for parameter in flat_params: + parameter.grad = torch.full_like(parameter, float("nan")) + before = [parameter.detach().clone() for parameter in flat_params] + moments = [entry["exp_avg"].clone() for entry in flat.state.values()] + counts = [entry["step"].item() for entry in flat.state.values()] + arm(flat, found_inf) + flat.step() + for parameter, saved in zip(flat_params, before, strict=True): + torch.testing.assert_close(parameter, saved, rtol=0, atol=0) + for entry, saved in zip(flat.state.values(), moments, strict=True): + torch.testing.assert_close(entry["exp_avg"], saved, rtol=0, atol=0) + assert [entry["step"].item() for entry in flat.state.values()] == counts + + # The checkpoint is the fused Adam layout: one step tensor per parameter, so a + # stock Adam that resumes it advances each counter exactly once per step. + state = flat.state_dict() + assert len({id(entry["step"]) for entry in state["state"].values()}) == len(shapes) + reference.load_state_dict(state) + torch.manual_seed(99) + resumed = [torch.randn_like(parameter) for parameter in reference_params] + for parameter, gradient in zip(reference_params, resumed, strict=True): + parameter.grad = gradient.clone() + for parameter, gradient in zip(flat_params, resumed, strict=True): + parameter.grad = gradient.clone() + arm(reference, torch.zeros((), device="cuda")) + arm(flat, torch.zeros((), device="cuda")) + reference.step() + flat.step() + assert [entry["step"].item() for entry in reference.state.values()] == [6.0] * len(shapes) + for expected, actual in zip(reference_params, flat_params, strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-6, atol=1e-7) + flat.load_state_dict(reference.state_dict()) + assert [entry["step"].item() for entry in flat.state.values()] == [6.0] * len(shapes) + + +# --- contiguous block weight gradients (#2690) ------------------------------------- + + +@pytest.mark.parametrize("device", ["cpu", "cuda"] if torch.cuda.is_available() else ["cpu"]) +def test_block_linear_matches_the_einsum_path_exactly(device: str) -> None: + torch.manual_seed(0) + ensemble, rows, inputs, outputs = 2, 16, 8, 32 + reference = EnsembleUnitLinear(ensemble, inputs, outputs).to(device) + block = EnsembleBlockLinear(ensemble, inputs, outputs).to(device) + block.load_state_dict(reference.state_dict()) + gradient = torch.randn(ensemble, rows, outputs, device=device) + + rows_input = torch.randn(rows, inputs, device=device) + + def run(module: EnsembleUnitLinear) -> tuple[torch.Tensor | None, torch.Tensor | None]: + x = rows_input.clone().requires_grad_() + # The critic feeds an expanded view of the joined rows. + out = module(x.unsqueeze(0).expand(ensemble, -1, -1)) + out.backward(gradient) + return x.grad, module.weight.grad + + reference_x_grad, reference_w_grad = run(reference) + block_x_grad, block_w_grad = run(block) + # cuBLAS is bitwise; the CPU GEMM backends differ in their summation order. + tolerance = {"rtol": 0, "atol": 0} if device == "cuda" else {"rtol": 1e-4, "atol": 1e-6} + torch.testing.assert_close(block_x_grad, reference_x_grad, **tolerance) + torch.testing.assert_close(block_w_grad, reference_w_grad, **tolerance) + assert block_w_grad is not None and block_w_grad.is_contiguous() + + if device == "cuda": + with torch.autocast("cuda", dtype=torch.bfloat16): + reference_x_grad, reference_w_grad = run(reference) + block_x_grad, block_w_grad = run(block) + torch.testing.assert_close(block_x_grad, reference_x_grad, rtol=0, atol=0) + torch.testing.assert_close(block_w_grad, reference_w_grad, rtol=0, atol=0) + assert block_w_grad is not None + assert block_w_grad.dtype == torch.float32 and block_w_grad.is_contiguous() + + # A frozen critic (the fused actor update) yields no weight gradient. + reference.weight.grad = None + block.weight.grad = None + for module in (reference, block): + module.weight.requires_grad_(False) + reference_x_grad, reference_w_grad = run(reference) + block_x_grad, block_w_grad = run(block) + assert reference_w_grad is None and block_w_grad is None + torch.testing.assert_close(block_x_grad, reference_x_grad, **tolerance) + + +def test_residual_blocks_use_the_block_linear() -> None: + critic = FlashSACDoubleCritic( + num_blocks=2, input_dim=7, hidden_dim=8, num_bins=5, min_v=-1, max_v=1 + ) + linears = [ + type(module) for module in critic.modules() if isinstance(module, EnsembleUnitLinear) + ] + assert linears.count(EnsembleBlockLinear) == 4 + assert linears.count(EnsembleUnitLinear) == 2 # embedder and categorical head + + +# --- fused kernels (#2689) --------------------------------------------------------- + + +@_CUDA +def test_row_renormalizer_matches_the_eager_walk() -> None: + triton = pytest.importorskip("triton") # noqa: F841 + from unilab.rl.algos.flash_sac.kernels import RowRenormalizer + + for module in ( + FlashSACActor(num_blocks=2, input_dim=6, hidden_dim=16, action_dim=3, device="cuda"), + FlashSACDoubleCritic( + num_blocks=2, input_dim=9, hidden_dim=16, num_bins=5, min_v=-1, max_v=1, device="cuda" + ), + ): + torch.manual_seed(0) + reference = copy.deepcopy(module) + with torch.no_grad(): + for parameter, other in zip(module.parameters(), reference.parameters(), strict=True): + parameter.copy_(other * 1.5 + 0.25) + other.copy_(parameter) + reference.normalize_parameters() + renormalizer = RowRenormalizer.build(module) + assert renormalizer is not None + renormalizer() + for parameter, other in zip(module.parameters(), reference.parameters(), strict=True): + torch.testing.assert_close(parameter, other, rtol=1e-5, atol=1e-6) + + # Rows wider than the single-block kernel fall back to the eager walk. + wide = FlashSACActor(num_blocks=1, input_dim=8, hidden_dim=2048, action_dim=2, device="cuda") + assert RowRenormalizer.build(wide) is None + + +@_CUDA +def test_table_lerp_matches_per_parameter_lerp() -> None: + pytest.importorskip("triton") + from unilab.rl.algos.common.kernels import TableLerp + + torch.manual_seed(0) + sources = [torch.randn(shape, device="cuda") for shape in ((16, 8), (5,), (1,), (3000,))] + targets = [torch.randn_like(source) for source in sources] + reference = [target.clone() for target in targets] + weight = torch.tensor(0.0037, device="cuda") + TableLerp(targets, sources)(weight) + for target, expected, source in zip(targets, reference, sources, strict=True): + expected.lerp_(source, weight) + torch.testing.assert_close(target, expected, rtol=1e-6, atol=1e-7) + zero = torch.zeros((), device="cuda") + TableLerp(targets, sources)(zero) + for target, expected in zip(targets, reference, strict=True): + torch.testing.assert_close(target, expected, rtol=1e-6, atol=1e-7) + + +# --- the fused learner on the whole-cycle path ------------------------------------- + + +@_CUDA +def test_fused_whole_cycle_learner_matches_the_stock_learner() -> None: + torch.manual_seed(0) + stock = _cuda_learner() + fused = _cuda_learner(fuse_learner_steps=True) + _sync_modules(fused, stock) + assert all(isinstance(getattr(fused, name), FlatAdam) for name in _OPTIMIZERS) + assert all(type(getattr(stock, name)) is not FlatAdam for name in _OPTIMIZERS) + from unilab.rl.algos.flash_sac.kernels import RowRenormalizer + + assert isinstance(fused.actor.__dict__["normalize_parameters"], RowRenormalizer) + assert isinstance(fused.critic.__dict__["normalize_parameters"], RowRenormalizer) + assert fused._target_polyak is not None + batch = _batch(16) + + for step in range(3): + stock_metrics = _cycle(stock, 100 + step, batch) + fused_metrics = _cycle(fused, 100 + step, batch) + assert fused._update_cycle_graph is not None + for key, value in stock_metrics.items(): + assert fused_metrics[key] == pytest.approx(value, rel=1e-4, abs=1e-5) + _assert_same_learners(stock, fused, atol=1e-6) + + # A non-finite critic loss skips the critic step and the Polyak update in the graph. + critic_before = [parameter.detach().clone() for parameter in fused.critic.parameters()] + target_before = [parameter.detach().clone() for parameter in fused.target_critic.parameters()] + moments = [entry["exp_avg"].clone() for entry in fused.critic_optimizer.state.values()] + counts = [entry["step"].item() for entry in fused.critic_optimizer.state.values()] + bad = {key: value.clone() for key, value in batch.items()} + bad["rewards"] = torch.full_like(batch["rewards"], float("nan")) + metrics = _cycle(fused, 7, bad) + assert metrics["Loss/critic"] != metrics["Loss/critic"] # NaN + for parameter, saved in zip(fused.critic.parameters(), critic_before, strict=True): + torch.testing.assert_close(parameter, saved, rtol=1e-4, atol=1e-6) + for parameter, saved in zip(fused.target_critic.parameters(), target_before, strict=True): + torch.testing.assert_close(parameter, saved, rtol=0, atol=0) + for entry, saved in zip(fused.critic_optimizer.state.values(), moments, strict=True): + torch.testing.assert_close(entry["exp_avg"], saved, rtol=0, atol=0) + assert [entry["step"].item() for entry in fused.critic_optimizer.state.values()] == counts + assert fused._critic_update_finite.item() == 0.0 + + # A fused-written checkpoint resumes in a stock learner and in a fused one alike. + state = fused.get_state_dict() + stock_resume = _cuda_learner() + fused_resume = _cuda_learner(fuse_learner_steps=True) + stock_resume.load_state_dict(copy.deepcopy(state)) + fused_resume.load_state_dict(copy.deepcopy(state)) + _cycle(stock_resume, 200, batch) + _cycle(fused_resume, 200, batch) + _cycle(stock_resume, 201, batch) + _cycle(fused_resume, 201, batch) + _assert_same_learners(stock_resume, fused_resume, atol=1e-6) + + +@_CUDA +def test_fused_learner_eager_fallback_matches_the_stock_fallback() -> None: + torch.manual_seed(0) + stock = _cuda_learner() + fused = _cuda_learner(fuse_learner_steps=True) + _sync_modules(fused, stock) + # A failed capture keeps the compiled objectives and runs the cycle eagerly. + for learner in (stock, fused): + learner._update_cycle_capture_failed = True + batch = _batch(16) + for step in range(2): + torch.manual_seed(300 + step) + stock.update_cycle(batch, **_CYCLE) + torch.manual_seed(300 + step) + fused.update_cycle(batch, **_CYCLE) + stock.read_deferred_cycle_metrics() + fused.read_deferred_cycle_metrics() + assert fused._update_cycle_graph is None + _assert_same_learners(stock, fused, atol=1e-6) + + +@_CUDA +def test_fused_learner_rejects_the_data_parallel_path() -> None: + fused = _cuda_learner(fuse_learner_steps=True) + with pytest.raises(ValueError, match="fuse_learner_steps"): + fused.set_gradient_sync(lambda _parameters: None) + fused.set_gradient_sync(None) + + +def test_fused_steps_need_the_whole_cycle_path() -> None: + learner = FlashSACLearner( + obs_dim=4, + action_dim=2, + critic_obs_dim=6, + actor_hidden_dim=8, + critic_hidden_dim=8, + num_atoms=5, + device="cpu", + use_compile=False, + fuse_learner_steps=True, + ) + assert learner._fuse_learner_steps is False + assert all(type(getattr(learner, name)) is not FlatAdam for name in _OPTIMIZERS) + + +# --- loss_rows_only (#2691) -------------------------------------------------------- + + +def _small_learner(**overrides: Any) -> FlashSACLearner: + kwargs: dict[str, Any] = { + "obs_dim": 4, + "action_dim": 2, + "critic_obs_dim": 6, + "actor_hidden_dim": 8, + "critic_hidden_dim": 8, + "actor_num_blocks": 1, + "critic_num_blocks": 1, + "num_atoms": 5, + "device": "cpu", + "use_compile": False, + } + kwargs.update(overrides) + return FlashSACLearner(**kwargs) + + +def test_loss_rows_only_matches_the_joined_objective_with_fixed_batch_statistics() -> None: + torch.manual_seed(0) + joined = _small_learner() + rows = _small_learner(loss_rows_only=True) + _sync_modules(rows, joined) + batch = _batch(8, device="cpu") + # With running statistics instead of batch statistics the two objectives read + # the same values for the rows their loss uses. + unit_forward = UnitBatchNorm.forward + ensemble_forward = EnsembleUnitBatchNorm.forward + with ( + mock.patch.object( + UnitBatchNorm, "forward", lambda self, x, training: unit_forward(self, x, False) + ), + mock.patch.object( + EnsembleUnitBatchNorm, + "forward", + lambda self, x, training: ensemble_forward(self, x, False), + ), + ): + arguments = ( + batch["actions"], + batch["rewards"], + batch["next_obs"], + batch["dones"], + batch["truncated"], + batch["critic"], + batch["next_critic"], + ) + torch.manual_seed(11) + joined_loss, joined_scale = joined._full_critic_objective(*arguments) + torch.manual_seed(11) + rows_loss, rows_scale = rows._full_critic_objective(*arguments) + torch.testing.assert_close(rows_loss, joined_loss) + torch.testing.assert_close(rows_scale, joined_scale) + joined_loss.backward() + rows_loss.backward() + for joined_parameter, rows_parameter in zip( + joined.critic.parameters(), rows.critic.parameters(), strict=True + ): + torch.testing.assert_close(rows_parameter.grad, joined_parameter.grad) + + for learner in (joined, rows): + learner.critic.zero_grad(set_to_none=True) + torch.manual_seed(12) + joined_actor = joined._full_actor_objective( + batch["obs"], batch["next_obs"], batch["actions"], batch["critic"] + ) + torch.manual_seed(12) + rows_actor = rows._full_actor_objective( + batch["obs"], batch["next_obs"], batch["actions"], batch["critic"] + ) + for rows_value, joined_value in zip(rows_actor, joined_actor, strict=True): + if isinstance(rows_value, dict): + assert rows_value.keys() == joined_value.keys() + else: + torch.testing.assert_close(rows_value, joined_value) + joined_actor[0].backward() + rows_actor[0].backward() + for joined_parameter, rows_parameter in zip( + joined.actor.parameters(), rows.actor.parameters(), strict=True + ): + torch.testing.assert_close(rows_parameter.grad, joined_parameter.grad) + + +def test_loss_rows_only_rejects_custom_actors() -> None: + with pytest.raises(ValueError, match="loss_rows_only"): + _small_learner( + loss_rows_only=True, + actor_config={ + "builder": "tests.rl.algos.flash_sac_actor_fixtures:build_scaled_tanh_actor" + }, + ) From cc907ba4310417f0f15f285acf370b19cf3dbe11 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 17:58:05 +0800 Subject: [PATCH 3/5] docs(flash_sac): document fuse_learner_steps and loss_rows_only --- docs/sphinx/source/changelog.md | 55 +++++++++++++++++++ .../2-user_guide/2-algorithms/4-flash_sac.md | 2 + .../2-user_guide/2-algorithms/4-flash_sac.md | 2 + 3 files changed, 59 insertions(+) diff --git a/docs/sphinx/source/changelog.md b/docs/sphinx/source/changelog.md index b63bfedbb..b16fe46ce 100644 --- a/docs/sphinx/source/changelog.md +++ b/docs/sphinx/source/changelog.md @@ -13,6 +13,61 @@ UniLab 遵循[语义化版本](https://semver.org/)。本共享页面以中英 PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完整提交历史请参阅 [UniLab 仓库](https://github.com/unilabsim/UniLab)。 +## Unreleased + +### Added / 新增 + +- FlashSAC learners on the NVIDIA CUDA whole-cycle path can fuse the non-GEMM + steps of an update into a few kernels with + `algo.algo_params.fuse_learner_steps=true` (off by default): the Adam steps + run over one flat buffer per parameter group, parameter normalization and the + Polyak update become one kernel each, autograd hands its fresh gradients to + `.grad`, and the actor update no longer computes critic weight gradients. + Parameters, checkpoints and the in-graph NaN gate are unchanged; the flag is + rejected on the data-parallel path + ([#2689](https://github.com/Motphys/UniLab/issues/2689)). +- `algo.algo_params.loss_rows_only=true` (off by default) runs each network of + the FlashSAC training objectives only on the rows its loss reads instead of + the joined `obs` / `next_obs` rows. GEMM and BatchNorm work per update + halves; the training-mode BatchNorm statistics then come from half the rows, + so this is not an exact rewrite + ([#2691](https://github.com/Motphys/UniLab/issues/2691)). +- NVIDIA CUDA whole-cycle 路径上的 FlashSAC learner 可用 + `algo.algo_params.fuse_learner_steps=true`(默认关闭)把一次更新里的非 GEMM + 步骤合成少量 kernel:Adam 按参数组在单个 flat buffer 上运行,参数归一化与 + Polyak 更新各合成一个 kernel,autograd 的新梯度直接接管 `.grad`,actor 更新 + 不再为 critic 权重求导。参数、checkpoint 与图内 NaN 门控不变;数据并行路径 + 下拒绝该开关([#2689](https://github.com/Motphys/UniLab/issues/2689))。 +- `algo.algo_params.loss_rows_only=true`(默认关闭)让 FlashSAC 训练目标里的 + 每个网络只算其 loss 读到的行,而非拼接后的 `obs` / `next_obs` 行。每次更新 + 的 GEMM 与 BatchNorm 工作量减半;训练态 BatchNorm 的统计量只来自一半的行, + 因此不是精确等价改写 + ([#2691](https://github.com/Motphys/UniLab/issues/2691))。 + +### Changed / 变更 + +- The residual blocks of the FlashSAC ensemble critic produce their weight + gradients contiguous in `[ensemble, out, in]`, removing one clone per block + weight gradient per critic update; forward outputs and gradients are + unchanged ([#2690](https://github.com/Motphys/UniLab/issues/2690)). +- FlashSAC 集成 critic 的残差块直接以连续的 `[ensemble, out, in]` 输出权重梯度, + 每次 critic 更新为每个块权重梯度省掉一次 clone;前向输出与梯度不变 + ([#2690](https://github.com/Motphys/UniLab/issues/2690))。 + +### Fixed / 修复 + +- The masked autoreset body executed by Python (the warm-up steps before + capture and any eager fallback) no longer rebinds the public step state to + UniLab's working object when an owner's `update_state` returns its own state + object. `step()` now publishes that object's terminated / obs / reward on + those steps, as a replayed body always did + ([#2685](https://github.com/Motphys/UniLab/issues/2685)). +- masked autoreset body 由 Python 执行时(捕获前的预热步与任何 eager 回退), + 不再把公开的 step state 重绑到 UniLab 的工作对象——当 owner 的 `update_state` + 返回自己的 state 对象时,`step()` 在这些步骤上发布的 terminated / obs / reward + 现在与图 replay 时一致 + ([#2685](https://github.com/Motphys/UniLab/issues/2685))。 + ## 1.6.5 (2026-12-03) ### Fixed / 修复 diff --git a/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md b/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md index 0d69e2a65..eaded9055 100644 --- a/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md +++ b/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md @@ -132,6 +132,8 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.compile_full_objectives` | bool | true | Compile complete actor/critic objectives instead of loss-tensor regions | | `algo.algo_params.use_whole_cycle_cuda_graph` | bool | true | Learner-owned whole-cycle CUDA Graph capture | | `algo.algo_params.dp_whole_cycle_cuda_graph` | bool | true | Whole-cycle capture on the data-parallel path; `false` disables DP capture only (field set in `config.yaml`) | +| `algo.algo_params.fuse_learner_steps` | bool | false | Fuse the non-GEMM steps of each whole-cycle update (Adam, parameter normalization, Polyak update, gradient handover) into a few kernels; NVIDIA CUDA whole-cycle path only, rejected with data parallel | +| `algo.algo_params.loss_rows_only` | bool | false | Run each network of the training objectives only on the rows its loss reads; halves the GEMM and BatchNorm work per update, but the training-mode BatchNorm statistics then come from half the rows | | `algo.seed` | int | 1 | Random seed | | `training.use_amp` | bool | true | Enable device-supported AMP; the dtype and device gates are controlled by `algo.algo_params.amp_dtype` | | `training.log_interval` | int | 1 | TensorBoard/W&B scalar reporting interval in iterations | diff --git a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md index 88f67a7da..b2b00fbf4 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md @@ -124,6 +124,8 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.compile_full_objectives` | bool | true | 编译完整 actor/critic objective,而非较小的 loss-tensor 区域 | | `algo.algo_params.use_whole_cycle_cuda_graph` | bool | true | learner 侧整轮 CUDA Graph 捕获 | | `algo.algo_params.dp_whole_cycle_cuda_graph` | bool | true | 数据并行路径上的整轮捕获;`false` 只关闭 DP 捕获(该字段设于 `config.yaml`) | +| `algo.algo_params.fuse_learner_steps` | bool | false | 把每次整轮更新里的非 GEMM 步骤(Adam、参数归一化、Polyak 更新、梯度接管)合成少量 kernel;仅 NVIDIA CUDA whole-cycle 路径,数据并行下拒绝 | +| `algo.algo_params.loss_rows_only` | bool | false | 训练目标里的每个网络只算其 loss 读到的行;每次更新的 GEMM 与 BatchNorm 工作量减半,但训练态 BatchNorm 的统计量只来自一半的行 | | `algo.seed` | int | 1 | 随机种子 | | `training.use_amp` | bool | true | 启用设备支持的 AMP;dtype 与设备门控由 `algo.algo_params.amp_dtype` 决定 | | `training.log_interval` | int | 1 | TensorBoard/W&B 标量上报间隔(迭代数) | From 68a161b608538928a9d08e02388cb07fd800e77a Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 17:58:05 +0800 Subject: [PATCH 4/5] fix(base): keep the step state bound through the eager masked autoreset 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 --- src/unilab/base/torch_env.py | 4 + .../test_torch_env_masked_state_binding.py | 114 ++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 tests/base/test_torch_env_masked_state_binding.py diff --git a/src/unilab/base/torch_env.py b/src/unilab/base/torch_env.py index 44ebb10f3..5749e33a5 100644 --- a/src/unilab/base/torch_env.py +++ b/src/unilab/base/torch_env.py @@ -966,6 +966,10 @@ def _masked_autoreset_body(self) -> None: new_obs, reset_info = self.reset(selection) # type: ignore[arg-type] finally: self._autoreset_reset_active = False + # The eager reset re-selects the working state (Manager-Based + # ``_reset``). This step publishes the object ``update_state`` + # returned; a replayed body never rebinds it. + self._state = state if not self._autoreset_scattered_reset_obs: self._validate_reset_observation_mask(new_obs) for name, values in new_obs.items(): diff --git a/tests/base/test_torch_env_masked_state_binding.py b/tests/base/test_torch_env_masked_state_binding.py new file mode 100644 index 000000000..726febc5b --- /dev/null +++ b/tests/base/test_torch_env_masked_state_binding.py @@ -0,0 +1,114 @@ +"""The eager masked autoreset body publishes the step's own state object (#2685).""" + +from __future__ import annotations + +from dataclasses import dataclass +from unittest.mock import MagicMock + +import gymnasium as gym +import numpy as np +import torch +from unisim.backend.base import ( + SimBackend, + TensorDataPlane, + TensorExecution, + TensorLifecycleCapabilities, +) + +from unilab.base.base import EnvCfg +from unilab.base.torch_env import TorchEnv, TorchEnvState + + +@dataclass +class _MaskedCfg(EnvCfg): + max_episode_seconds: float | None = 1.0 + ctrl_dt: float = 0.1 + sim_dt: float = 0.1 + masked_autoreset: bool = True + persistent_step_buffers: bool = True + + +def _backend() -> MagicMock: + backend = MagicMock(spec=SimBackend) + backend.backend_type = "mujoco" + backend.num_actuators = 4 + backend.get_tensor_execution.return_value = TensorExecution.HOST_BRIDGE + backend.get_tensor_capabilities.return_value = TensorLifecycleCapabilities( + execution=TensorExecution.HOST_BRIDGE, + state_fields=frozenset({"qpos", "qvel"}), + stepping=True, + selected_reset=True, + packed_host_bridge=True, + data_plane=TensorDataPlane.HOST_BRIDGE, + stream_event_ownership="test", + torch_devices=("cpu",), + ) + backend.step_tensor.return_value = None + return backend + + +class _OwnStateEnv(TorchEnv): + """Owner whose ``update_state`` returns a state object of its own. + + Every step produces a distinguishable state (reward equal to the step count, + alternating terminated rows), so the published state can be told apart from + the previous step's. + """ + + OBS_SPEC = {"obs": 3} + + def __init__(self, num_envs: int = 4) -> None: + super().__init__(_MaskedCfg(), _backend(), num_envs, device="cpu") + self.calls = 0 + + @property + def obs_groups_spec(self) -> dict[str, int]: + return self.OBS_SPEC + + @property + def action_space(self) -> gym.Space: + return gym.spaces.Box(-1.0, 1.0, shape=(4,), dtype=np.float32) + + def apply_action(self, actions: torch.Tensor, state: TorchEnvState) -> torch.Tensor: + return actions + + def update_state(self, state: TorchEnvState) -> TorchEnvState: + self.calls += 1 + rows = torch.arange(self.num_envs, device=self.device) + return state.replace( + obs={"obs": torch.full((self.num_envs, 3), float(self.calls), device=self.device)}, + reward=torch.full((self.num_envs,), float(self.calls), device=self.device), + terminated=(rows + self.calls) % 2 == 0, + truncated=torch.zeros((self.num_envs,), dtype=torch.bool, device=self.device), + ) + + def reset_selection_blockers(self) -> list[str]: + return [] + + def reset( + self, env_ids: torch.Tensor | None = None + ) -> tuple[dict[str, torch.Tensor], dict[str, object]]: + # Manager-Based ``_reset`` re-selects the working state; that is what + # rebinding ``self._state`` away from this step's object. + self._activate_working_state(copy_outputs=False) + return ( + {"obs": torch.full((self.num_envs, 3), -1.0, device=self.device)}, + {"row_metric": torch.arange(self.num_envs, dtype=torch.float32, device=self.device)}, + ) + + +def test_eager_masked_autoreset_publishes_the_step_state() -> None: + env = _OwnStateEnv() + actions = torch.zeros((env.num_envs, 4)) + + env.step(actions) + second = env.step(actions) + + rows = torch.arange(env.num_envs) + done = (rows + env.calls) % 2 == 0 + assert torch.equal(second.reward, torch.full((env.num_envs,), float(env.calls))) + assert torch.equal(second.terminated, done) + # Reset rows carry the reset observation; the other rows keep this step's. + step_obs = torch.full((env.num_envs, 3), float(env.calls)) + expected_obs = torch.where(done[:, None], -1.0, step_obs) + assert torch.equal(second.obs["obs"], expected_obs) From 08ccfa84f0b9ea247c5695c8caf28a4925ec7ad8 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 18:39:26 +0800 Subject: [PATCH 5/5] fix(rl): type-check the Triton kernel launches without triton installed 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 --- src/unilab/rl/algos/common/kernels.py | 13 +++++++++++-- src/unilab/rl/algos/flash_sac/kernels.py | 14 ++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/unilab/rl/algos/common/kernels.py b/src/unilab/rl/algos/common/kernels.py index be4aa5e3b..70727dc18 100644 --- a/src/unilab/rl/algos/common/kernels.py +++ b/src/unilab/rl/algos/common/kernels.py @@ -10,15 +10,21 @@ from __future__ import annotations from collections.abc import Callable +from typing import Any import torch import torch.nn as nn import triton import triton.language as tl +# ``triton`` is an optional dependency: where it is not installed (or not resolvable by the type +# checker) the decorated kernel is Unknown and its ``kernel[grid]`` launch does not type-check. +# Binding the kernel through an ``Any`` alias keeps both paths clean. +_lerp_rows: Any + @triton.jit -def _lerp_rows(target, source, piece, offset, size, weight, BLOCK: tl.constexpr): +def _lerp_rows_fn(target, source, piece, offset, size, weight, BLOCK: tl.constexpr): pid = tl.program_id(0) i = tl.load(piece + pid) start = tl.load(offset + pid) @@ -32,6 +38,9 @@ def _lerp_rows(target, source, piece, offset, size, weight, BLOCK: tl.constexpr) tl.store(t_ptr + offs, t + w * (s - t), mask=valid) +_lerp_rows = _lerp_rows_fn + + class TableLerp: """``target_i += weight * (source_i - target_i)`` for every pair, in one kernel launch. @@ -91,7 +100,7 @@ def __call__(self, weight: torch.Tensor) -> None: size, weight, BLOCK=self.BLOCK, - num_warps=4, # pyright: ignore[reportCallIssue] + num_warps=4, ) diff --git a/src/unilab/rl/algos/flash_sac/kernels.py b/src/unilab/rl/algos/flash_sac/kernels.py index 8fb918807..78025c4a1 100644 --- a/src/unilab/rl/algos/flash_sac/kernels.py +++ b/src/unilab/rl/algos/flash_sac/kernels.py @@ -10,6 +10,7 @@ from __future__ import annotations import math +from typing import Any import torch import torch.nn as nn @@ -25,8 +26,14 @@ _WARPS = {256: 2, 512: 4, 1024: 4, 2048: 8, 4096: 16} +# ``triton`` is an optional dependency: where it is not installed (or not resolvable by the type +# checker) the decorated kernel is Unknown and its ``kernel[grid]`` launch does not type-check. +# Binding the kernel through an ``Any`` alias keeps both paths clean. +_renorm_rows: Any + + @triton.jit -def _renorm_rows(base, joint, len_a, len_b, gain, eps, mode, group, row, BLOCK: tl.constexpr): +def _renorm_rows_fn(base, joint, len_a, len_b, gain, eps, mode, group, row, BLOCK: tl.constexpr): pid = tl.program_id(0) g = tl.load(group + pid) r = tl.load(row + pid) @@ -48,6 +55,9 @@ def _renorm_rows(base, joint, len_a, len_b, gain, eps, mode, group, row, BLOCK: tl.store(b_ptr + offs - la, tl.where(clamp, tl.math.div_rn(b, denom), b * factor), mask=in_b) +_renorm_rows = _renorm_rows_fn + + def _groups(module: nn.Module) -> list[tuple[torch.Tensor, torch.Tensor | None, int, float]]: """Return ``(first array, joint array or None, mode, gain)`` in the eager walk's order. @@ -171,5 +181,5 @@ def __call__(self) -> None: group, row, BLOCK=block, - num_warps=_WARPS.get(block, 16), # pyright: ignore[reportCallIssue] + num_warps=_WARPS.get(block, 16), )