Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions docs/sphinx/source/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 / 修复
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 标量上报间隔(迭代数) |
Expand Down
4 changes: 4 additions & 0 deletions src/unilab/base/torch_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
2 changes: 2 additions & 0 deletions src/unilab/conf/flashsac/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
224 changes: 224 additions & 0 deletions src/unilab/rl/algos/common/flat_adam.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading