Skip to content

fix(logging_utils): preserve logger hierarchy and eliminate global class mutation - #194

Merged
NINGBENZHE merged 2 commits into
redai-studio:mainfrom
xcosmosbox:fix/rollout-metrics-logger
Aug 10, 2026
Merged

NINGBENZHE merged 2 commits into
redai-studio:mainfrom
xcosmosbox:fix/rollout-metrics-logger

Conversation

@xcosmosbox

@xcosmosbox xcosmosbox commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

What

get_logger() had two independent defects, both silent:

  1. It could return a logger detached from the logging hierarchy, causing
    every INFO record emitted through it to be discarded.
  2. It mutated process-global logging state on every call.

The original implementation:

# Set the logger class for this logger
logging.setLoggerClass(LazyConfiguredLogger)
logger = logging.getLogger(name)
logging.setLoggerClass(logging.Logger)  # Reset to default for other loggers

if not isinstance(logger, LazyConfiguredLogger):
    # If logger already exists and is not our class, create a new instance
    logger = LazyConfiguredLogger(name)

return logger

This PR upgrades the already-registered instance in place, drops the
setLoggerClass dance entirely, and adds regression tests for both defects.

Why

Defect 1 — detached logger swallows INFO

Constructing a Logger directly (rather than via logging.getLogger) bypasses
Logger.manager, so the resulting object is not part of the logger tree:

  • parent is None
  • handlers is []
  • logging.getLogger(name) is not logger

Logger.callHandlers walks self.parent looking for handlers; with no parent
and no handlers it finds none and falls back to logging.lastResort, which is
fixed at WARNING level. Every INFO record therefore disappears without any
error. isEnabledFor(logging.INFO) still returns True on such a logger,
which makes the problem hard to spot.

This is reachable in normal operation: Ray/cloudpickle reconstructs
@ray.remote class namespaces by value, and unpickles their module-global
loggers through logging.getLogger(name) using the default logger class. That
registers the name as a plain logging.Logger before the canonical module is
imported and calls get_logger() for the same name. The repository already
documents this reconstruction behaviour in the _LOCAL_ROLLOUT_MANAGER note in
relax/distributed/ray/rollout.py.

Observed impact: under colocate deployments the whole rollout metrics family
logged by _log_rollout_data — the perf N: {...} line carrying
rollout/response_len/*, rollout/repetition_frac, rollout/truncated_ratio,
rollout/zero_std/*, perf/* and friends — never reached the console. The
metrics were computed correctly every step; only the output channel was dead.
Because the affected logger belongs to a different module than the one whose
__init__ logging still worked, this looked like the metrics code was not
running at all.

Defect 2 — global setLoggerClass mutation

logging.setLoggerClass() sets a process-wide default. The reset was
unconditional (setLoggerClass(logging.Logger)) rather than restoring the
previous value, so a single get_logger() call:

  • destroyed any default logger class installed earlier by a third-party
    library, silently downgrading every logger that library created afterwards;
  • opened a window in which a concurrent logging.getLogger() on another thread
    received a LazyConfiguredLogger it never asked for.

Neither symptom raises an error, and both are invisible at the call site.

How

Look the name up normally, then upgrade the manager-registered instance in
place so the parent/handler chain is preserved:

logger = logging.getLogger(name)

if type(logger) is logging.Logger:
    logger.__class__ = LazyConfiguredLogger

return logger

Three details worth noting:

  • LazyConfiguredLogger declares no __init__ and no instance attributes — it
    only adds a class-level _configured flag plus patched log methods — so
    reassigning __class__ cannot skip initialisation or drop state. The
    instance __dict__ keeps all of name, level, parent, propagate,
    handlers, filters, disabled, manager, _cache.
  • setLoggerClass is no longer needed at all. A brand-new name is created by
    getLogger as a plain logging.Logger and then takes the same in-place
    upgrade path, so the two cases converge and no global state is touched.
  • The type(logger) is logging.Logger guard keeps the upgrade narrow: genuine
    third-party Logger subclasses are returned untouched rather than being
    silently rewritten.

Because that last case can now return something other than a
LazyConfiguredLogger, the return annotation is widened from
-> LazyConfiguredLogger to -> logging.Logger and the docstring says so.
This is a widening, not a break: callers only use the logging.Logger API.

Testing

Minimal reproduction of defect 1 (standard library only, no Relax imports):

import logging

class LazyConfiguredLogger(logging.Logger):
    _configured = False

name = "demo.orphan"
logging.getLogger(name)             # pre-register as a plain Logger
orphan = LazyConfiguredLogger(name) # previous fallback

print(orphan.parent)                              # None
print(orphan.handlers)                            # []
print(logging.getLogger(name) is orphan)          # False
print(orphan.isEnabledFor(logging.INFO))          # True  <-- misleading

logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.INFO)
orphan.info("this never appears")                 # silently dropped

Replacing the last construction with plain.__class__ = LazyConfiguredLogger
restores parent, keeps the logger in the manager tree, and the record is
emitted.

New tests — tests/utils/test_logging_utils.py:

Test Guards
test_get_logger_returns_lazy_configured_logger happy path still returns the registered instance
test_get_logger_upgrades_preregistered_plain_logger_in_place same object is upgraded, not replaced
test_upgraded_logger_stays_attached_to_hierarchy parent chain reaches the root logger
test_upgraded_logger_emits_info_records an INFO record actually reaches a handler
test_get_logger_leaves_global_logger_class_untouched a third-party default logger class survives get_logger
test_get_logger_preserves_logger_subclasses third-party Logger subclasses are left alone

Results on this branch:

$ pytest tests/utils/test_logging_utils.py
6 passed in 0.03s

$ pytest tests/utils/
182 passed, 4 skipped in 35.50s

$ pytest tests/
909 passed, 14 skipped in 270.47s

$ ruff check relax/utils/logging_utils.py tests/utils/test_logging_utils.py
All checks passed!

$ ruff format --check relax/utils/logging_utils.py tests/utils/test_logging_utils.py
2 files already formatted

$ pre-commit run --all-files
(15 hooks, all Passed or Skipped-by-file-type; no failures)

$ git diff --check
(clean)

Negative control — the tests fail without the fix. Restoring the previous
get_logger implementation and re-running:

5 failed, 1 passed

The single pass is test_get_logger_returns_lazy_configured_logger, which the
old code also satisfied; the five failures pin down the detached parent, the
replaced-instead-of-upgraded instance, the dropped INFO record, the clobbered
global logger class and the rewritten third-party subclass respectively. The
new tests therefore constrain the behaviour rather than passing
unconditionally.

End-to-end check on a single-GPU colocate run (Qwen3-0.6B, GSM8K, 1×A100):
before the fix no perf N: line ever reached the console across nine runs;
after the fix it appears on every rollout step, carrying the previously
invisible metrics, e.g. rollout/response_len/mean = 1094.625,
rollout/repetition_frac = 0.0, rollout/truncated_ratio = 0.125.

  • pre-commit run --all-files passes
  • Tests pass (pytest tests/ — 909 passed, 14 skipped, 0 failed)
  • New tests added (if applicable)
  • Documentation updated (if applicable)

Scope notes for reviewers:

  • The get_logger docstring is updated in place (return type and the
    third-party-subclass case). No prose documentation appeared to need a change,
    since the fix restores the behaviour the existing docs already describe.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • CI/CD or build changes

Screenshots / Logs

Before the fix — the rollout step completes and metrics are computed, but no
perf N: line is ever logged:

| INFO | relax.engine.rollout.sglang_rollout:905  Total yielded: 4/4 for step: 0
| INFO | relax.utils.utils:496                    Prepared rollout batch 4 with 16 samples for transfer
(no `perf 0:` line — rollout metrics silently dropped)

After the fix — same configuration, metrics now reach the console:

| INFO | relax.distributed.ray.rollout:3913  perf 0: {..., 'rollout/response_len/mean': 1094.625,
  'rollout/repetition_frac': 0.0, 'rollout/truncated_ratio': 0.125, 'perf/step_time': ..., ...}

When a logger name is already registered as a plain logging.Logger,
get_logger built a fresh LazyConfiguredLogger(name). Constructing a
Logger directly (not via getLogger) leaves parent=None and handlers=[],
so every record falls through to logging.lastResort, which only passes
WARNING and above -- all INFO output silently disappears.

Ray/cloudpickle reconstructs @ray.remote class namespaces by value and
unpickles their module-global loggers via getLogger(name) with the
default logger class, so this pre-registration happens in practice. The
result is that the entire rollout metrics family (perf N: ... including
response_len/*, repetition_frac, truncated_ratio, zero_std/*) is
invisible on the console under colocate deployments.

Upgrade the manager-registered instance in place instead, preserving the
parent/handler chain. Only plain logging.Logger instances are upgraded so
third-party Logger subclasses are left untouched.
…r class

Replace setLoggerClass with in-place instance upgrade to eliminate thread race conditions and overwrites of third-party default logger classes.
Also preserve pre-registered subclass instances to avoid forced type casting.
@NINGBENZHE

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 451630a011

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@xcosmosbox xcosmosbox mentioned this pull request Aug 1, 2026
11 of 16 tasks

@NINGBENZHE NINGBENZHE left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@NINGBENZHE
NINGBENZHE merged commit 9a5674a into redai-studio:main Aug 10, 2026
5 checks passed
NINGBENZHE pushed a commit that referenced this pull request Aug 18, 2026
## What

为 Relax 增加同步 RLOO(REINFORCE Leave-One-Out)训练支持,包括算法注册、leave-one-out
baseline/advantage、非裁剪 policy loss、Megatron 分发、训练诊断指标、参数守卫、分布式测试、recipe
与双语文档。

同时修复开发过程中发现的 RLOO 分支问题:参数派生前校验、测试镜像生产逻辑、非有限 reward 缺少定位信息、eval 伪 RLOO
指标、有效 token 统计口径、异常组不可观测,以及 CP reducer 和 Megatron loss dispatch
缺少生产路径测试。

## Why

RLOO 使用同一 prompt 的其他采样作为当前样本的 leave-one-out baseline,可在不引入 Critic 的情况下降低
policy-gradient 方差,并作为 GRPO 之外的重要公开基线。与 GRPO 不同,RLOO 不按组内标准差缩放
advantage,并使用不含 PPO ratio/clipping 的 REINFORCE
objective,因此需要独立的算法计算、启动约束、监控指标和正确性验证。

#194 仅修复特定 Ray/cloudpickle 场景下 rollout `INFO` 日志的可见性。它不参与 RLOO 的
baseline、advantage、loss、梯度、optimizer update 或指标计算,不影响本 PR
算法与功能的正确性。本地端到端实验临时应用 #194 以观察 `rollout/rloo/*`;本 PR 最终 diff 不包含
`logging_utils.py` 改动。

## How

- 在完整 prompt group、DP/CP 切分之前,按 `Sample.group_index` 计算:

 ```math
  b_i = \frac{1}{G-1}\sum_{j\ne i}r_j,
  \qquad
  A_i = r_i-b_i = \frac{G}{G-1}(r_i-\bar r)
  ```

- 将标量 advantage 广播到有效 response token,并计算非裁剪目标:

  ```math
\mathcal{L}_{i,t}^{\mathrm{RLOO}} = -\mathrm{stopgrad}(A_i)\,\log
\pi_\theta\left(y_{i,t}\mid x_i,y_{i,1:t-1}\right)
  ```

- 复用现有 loss mask 与 CP-aware reducer;RLOO 的 `train/pg_clipfrac` 按定义恒为
`0`。

- 只开放已验证的同步固定 batch 拓扑,并保证每个 rollout 只执行一次 optimizer update。

- 在训练 rollout 侧发布 `rollout/rloo/*` diagnostics;eval 和覆盖标准 advantage 的
custom hook 路径不发布可能与 optimizer 输入不一致的标准诊断。

- 使用生产参数校验、生产 CP reducer 和实际 Megatron loss dispatch
测试约束实现,而不是复制生产逻辑到测试中自证。


## Reduction 选择与本 PR 的交付边界

本 PR 严格实现 leave-one-out baseline、advantage,以及有效 token 上未归约的 REINFORCE 项:
> 自 review 修订后,global-valid-token reduction 已由 production validator 强制开启
`--calculate-per-token-loss` 锁定;关闭该参数、非零 `--kl-coef` 与 `--max-staleness
> 0` 的 RLOO 配置都会在启动时被拒绝,不再存在会静默改变或破坏 RLOO 语义的合法公共配置组合。

$$
\ell_{i,t}=-\mathrm{sg}(A_i)\,\log \pi_\theta\left(y_{i,t}\mid
x_i,y_{i,1:t-1}\right).
$$

recipe 启用 `--calculate-per-token-loss`,因此最终标量沿用 Relax 现有的
global-valid-token normalization:

$$
\mathcal L_{\mathrm{current}}
=-\frac{1}{N_{\mathrm{eff}}}\sum_i\sum_t
m_{i,t}\,\mathrm{sg}(A_i)\,\log \pi_{i,t},
$$

而论文直接展开的 sequence-level estimator 是:

$$
\mathcal L_{\mathrm{paper}}
=-\frac{1}{B}\sum_i \mathrm{sg}(A_i)\sum_t m_{i,t}\,\log \pi_{i,t}.
$$

两者在一个给定 batch 内具有相同分子和梯度方向,只相差公共尺度 $B/N_{\mathrm{eff}}$;但该尺度会随采样得到的有效
response 长度变化,因此本 PR 只声明元素级公式一致,**不声明最终 scalar reduction 与论文逐值相同**。暂不在本
PR 中新增 paper-faithful reducer,基于以下考虑:

1. **训练工程稳定性。** Global token mean 使不同 response 长度和动态 micro-batch
下的梯度尺度更稳定,便于沿用已有学习率和 Megatron 的全局 token normalizer;论文的 sequence
token-sum 会使 loss/gradient 尺度随平均 response 长度变化,Adam 能吸收部分公共缩放,但 gradient
clipping、Adam epsilon、weight decay 和调度仍可能改变训练轨迹。
2. **长度偏差需要区分 reducer。** 当前模式不是“每条 response 先除以自身长度”的 per-sample token
mean,因此不会在同一 batch 内给每条轨迹额外乘不同的 $1/L_i$,也不会改变样本间的相对权重;它与论文 reducer
的差异主要是 batch 级公共分母。Dr.GRPO 对随机长度分母的分析说明固定分母或 sequence token-sum
在理论上更干净,但目前没有足够的 RLOO 专项消融证明它在本任务上必然带来 reward 收益,因此不把理论动机写成未经实验验证的性能结论。
3. **公开实现没有统一 reducer 契约。** 对公开 RLOO/REINFORCE 实现的核对显示,TRL 当前采用 sequence
token-sum/sample mean;ms-swift、OpenRLHF 等实现则主要把 RLOO 作为 advantage
estimator,并复用既有 token-level policy loss/reducer;verl 进一步把
`token-mean`、`seq-mean-token-mean`、`seq-mean-token-sum`
等作为彼此独立的配置维度。这些实现差异通常来自 trainer 分层、分布式 normalizer 复用和超参数稳定性要求,不能据此推断某一
reducer 已经取得一致的质量优势;它说明 reducer 是需要显式选择和验证的工程/算法设计维度,而不是仅凭算法名即可推断的唯一实现。
4. **PR 交付范围与风险控制。** 这不是一行 reduction 修改。在 Relax 中,paper-faithful 支持需要为共享
CP reducer 增加独立模式,同时修改 `loss.py` 的 micro-batch、DP/DDP、CP/dynamic-CP 缩放与
normalizer 选择,定义空 response 是否计入 sample 分母,并补齐 padding、非全一 mask、空
response、DP/CP 2/4 rank 和日志统计测试。该路径位于多算法共享基础设施;本题同时要求默认算法行为不受影响。本 PR
因而将范围收敛在已经完成公式对照、分布式测试和小模型训练验证的 baseline、advantage、元素级
loss、监控及同步训练链路,不在缺少独立验证矩阵时顺带扩张共享 reducer。
5. **后续建议。** 本 PR 合入后,可以单独提交 reducer PR,显式增加
`seq-mean-token-sum`(论文原始形式),同时保留当前 `token-mean`,并用相同 rollout 做 `paper`
/ `token-mean` 配对消融,比较 reward、KL、response length、grad
norm、稳定性和吞吐,再基于数据决定默认值。若 reviewers 认为 paper-faithful scalar reduction
是本任务当前验收的硬性条件,请明确指出;届时应将它作为一项完整的共享 reducer 变更评审,而不是隐藏在 RLOO 元素级 loss 中。


参考:[RLOO](https://arxiv.org/abs/2402.14740)、[Dr.GRPO](https://arxiv.org/abs/2503.20783)、[TRL
RLOOTrainer](https://huggingface.co/docs/trl/main/en/rloo_trainer)、[ms-swift
RLOO](https://swift.readthedocs.io/en/latest/Instruction/GRPO/AdvancedResearch/RLOO.html)、[OpenRLHF](https://github.com/OpenRLHF/OpenRLHF)、[verl
loss aggregation](https://verl.readthedocs.io/en/latest/algo/grpo.html)。


## Testing

- [x] `pre-commit run --all-files` passes
- [x] Tests pass (`pytest tests/`)
- [x] New tests added (if applicable)
- [x] Documentation updated (if applicable)

验证摘要:

- RLOO 聚焦测试:`54 passed`。
- 全量测试:`784 passed, 7 skipped`,退出码 `0`。
- `pre-commit run --all-files`:全部 hooks 通过。
- 2-GPU canary:2/2 optimizer steps,RLOO 指标完整,Ray Job succeeded。
- 正式配对实验:GRPO A2 与 RLOO B2 各完成 60/60 steps;两臂均无非有限训练值、OOM、worker crash 或
SIGKILL,`probability tensor` / device-side assert / global restart 计数均为
0。
- 两次 60-step run 在同一个 Ray head(GCS PID、raylet PID、session 均不变)上串行完成:RLOO
60 → 无重启清理 → GRPO 60。

详细命令、测试矩阵和 A/B 数值见下方 `Verification`。

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Refactoring (no functional changes)
- [ ] Performance improvement
- [ ] CI/CD or build changes

## Detailed Delivery Review
#### Summary

- Closes #186
- 解决了什么问题:
- 为 Relax 增加同步 RLOO(REINFORCE Leave-One-Out)完整链路:算法注册、leave-one-out
baseline、advantage、非裁剪 REINFORCE loss、Megatron 分发、监控指标、测试、recipe。

- RLOO 不依赖 Critic。对同一 prompt 的 $G$ 条采样,以其他 $G-1$ 条样本的平均 reward 作为当前样本
baseline:

 ```math
  b_i = \frac{1}{G-1}\sum_{j\ne i}r_j,
  \qquad
  A_i = r_i-b_i = \frac{G}{G-1}(r_i-\bar r)
  ```

  - 策略损失为:

  ```math
\mathcal{L}_{i,t}^{\mathrm{RLOO}} = -\mathrm{stopgrad}(A_i)\,\log
\pi_\theta\left(y_{i,t}\mid x_i,y_{i,1:t-1}\right)
  ```

- 补齐了参数派生顺序、非有限 reward 定位、eval 伪 RLOO 指标、异常组可观测性、真实 CP reducer 测试和
Megatron loss 分发测试等审查中发现的问题。

- #194 是独立的 logger hierarchy 可观测性修复:它解决 Ray/cloudpickle 场景下 rollout
`INFO` 日志可能不可见的问题,但不参与 RLOO 的 baseline、advantage、loss、梯度、optimizer
update 或指标计算,因此不影响本 PR 算法与功能的正确性。本地端到端实验临时应用了该修复以便观察 `rollout/rloo/*`;本
PR 的最终 diff 不包含 `logging_utils.py` 改动,也不以 #194 合并作为算法可用性的前置条件。
- 为什么采用该方案:
  - LOO baseline 不使用当前样本自身 reward,提供 critic-free 的公开 policy-gradient 基线。
- 使用 $\\frac{G}{G-1}(r_i-\\bar r)$ 的向量化恒等式,避免逐元素构造 $G-1$ 个 reward,同时与暴力
leave-one-out 公式逐元素等价。
- RLOO 保留 reward 尺度,不像 GRPO 那样除以组内标准差;loss 不复用 PPO-Clip,避免实现成“使用 LOO
advantage 的 GRPO”。
- baseline 在 DP 切分前按完整 `group_index` 计算;token loss 继续复用现有 mask 和
CP-aware reducer,最小化对默认路径的影响。
- 当前只开放同步、固定 batch、每 rollout 一次 optimizer update 的已验证拓扑;未验证的
async/partial/dynamic-global-batch 组合启动时直接拒绝,而不是静默降级。

#### Changes

- 文件 / 核心函数 / 行为变化:
  - `relax/utils/training/ppo_utils.py`
- 新增 `compute_rloo_leave_one_out_rewards()`:只接受单组 1-D reward tensor,检查
$G\\ge2$ 和有限值。
- 新增 `compute_rloo_loss()`:逐 token 计算 `-(advantage.detach() *
log_prob)`;`pg_clipfrac` 按定义恒为 `0`。
  - `relax/utils/utils.py`
- `post_process_rewards()` 新增 RLOO 分组变换,在 DP 切分前按 `Sample.group_index`
计算完整组 advantage。
    - 组大小不符继续 fail-fast。
    - NaN/±Inf 报错现在包含 `group_index`、组内位置、原 batch sample 位置和非法值。
    - group-aware debug subsampling 纳入 RLOO,避免调试采样切碎 prompt group。
  - `relax/core/registry.py`
    - 注册 `ALGOS["rloo"]`,使用与 GRPO 一致的无 Critic 服务角色。
  - `relax/backends/megatron/loss.py`
    - advantage 标量广播路径纳入 RLOO。
    - `policy_loss_function()` 分发到非裁剪 `compute_rloo_loss()`。
  - `relax/components/advantages.py`
    - 同步更新 RLOO 标量 advantage 广播表和支持列表文档。
  - `relax/utils/arguments.py`
    - RLOO 启动守卫新增三条 fail-fast:
- 必须开启 `--calculate-per-token-loss`,锁定 global-valid-token
reduction;否则拒绝,避免 per-sample token mean 按 `1/T_i` 重新加权不等长 response。
- 拒绝非零 `--kl-coef`:reward-side KL shaping 尚未为 completion-level
leave-one-out 信号实现,避免 reference forward 只产生计算开销却完全不影响 objective;需要 KL
约束时要求使用 `--use-kl-loss --kl-loss-coef`。
- 强制 `--max-staleness 0`:非裁剪 objective 没有 importance-ratio
correction,不允许 stale rollout。
  - `relax/backends/megatron/cp_utils.py`
- 按 review 指令回退 shared zero-token 改动:`get_cp_local_num_tokens()` 恢复历史
per-sample `clamp_min(loss_mask.sum(), 1)` 计数口径(每个样本至少贡献 1 个
token),不再为空/全 mask response 做特殊处理。
  - `relax/backends/megatron/loss.py`、`relax/backends/megatron/model.py`
- 按 review 指令回退 shared zero-token 改动:移除 no-signal step 的指标归一化特殊处理与空
response 的切片分支,恢复历史行为;RLOO 不维护“空/全 mask response 是已支持正常路径”的语义承诺。
  - 测试:
- 不等长 response、fully-masked response 与真实 `response_length == 0` 的最终
scalar loss / gradient oracle,覆盖生产 `loss_function()` 的 reducer 与返回的
Megatron token normalizer。
- CP=2/4 验证 token denominator 与 numerator 均与未切分 reference 严格一致,包含空
response。

  - `relax/utils/metrics/metric_utils.py`
    - 新增训练侧指标:
      - `rollout/rloo/baseline_mean`
      - `rollout/rloo/adv_abs_mean`
      - `rollout/rloo/no_signal_frac`
      - `rollout/rloo/empty_response_frac`
      - `rollout/rloo/zero_adv_group_frac`
      - `rollout/rloo/dropped_group_frac`
- `no_signal_frac` 按有效 loss token 加权;`empty_response_frac` 保留字面空
response 语义。
    - 不完整组通过 `dropped_group_frac` 暴露,不再完全静默。
- 当用户配置 custom reward post-process 或 custom agentic advantage hook
时,hook 可以覆盖标准 RLOO advantage。此时 rollout 侧只有 raw reward,无法知道 hook 最终交给
optimizer 的 advantage;为避免发布与真实训练信号不一致的 `rollout/rloo/*`,仅关闭这组标准诊断指标,不影响
custom hook 本身的训练行为。
  - `relax/distributed/ray/rollout.py`
- eval 显式关闭训练分组口径的 RLOO diagnostics,避免使用 `n_samples_per_prompt` 产生误导性的
`eval/*/rloo/* = 0` 序列。
  - 测试:
- 数学公式、$G=2$、常量组、非法形状、非有限 reward、padding、mask、空 response、autograd 和与
PPO-Clip 的负向对照。
    - 参数测试直接调用生产 `slime_validate_args()`,不再测试手抄守卫。
- CP 测试调用生产 `get_sum_of_sample_mean()`,使用独立 reference、真实 shifted-token
zig-zag 切片、非全 1 mask、Gloo world size 2/4 和 token 唯一归属断言。
    - 新增实际 `policy_loss_function()` RLOO dispatch/backward 冒烟测试。
    - 新增 metrics 与真实 eval call-site 门禁测试。
  - `examples/algorithms/run-qwen3-0.6B-1xgpu-rloo.sh`
    - 新增可在 RLOO/GRPO 间切换的 Qwen3-0.6B + GSM8K recipe。
    - rollout 数、prompt batch、group size、global batch 可通过环境变量按硬件调整。
- 清洗数据写入可写且版本化的 artifact cache;prompt 要求最终答案使用 `\boxed{...}`,与 `math`
reward parser 契约一致。
-
`docs/en/examples/algorithms.md`、`docs/zh/examples/algorithms.md`、`examples/algorithms/README.md`
    - 增加 RLOO 公式、与 GRPO 的区别、启动约束、最终指标名、硬件适配关系和 quick start。
- CLI、配置或兼容性变化:
  - `--advantage-estimator` 新增 `rloo`;默认 estimator 和既有 GRPO 行为不变。
  - RLOO 启动约束:
    - `--n-samples-per-prompt >= 2`
    - reward normalization 必须开启
    - `--normalize-advantages` 必须关闭
    - `--num-steps-per-rollout` 不设置或等于 `1`
    - `rollout_batch_size * n_samples_per_prompt == global_batch_size`
- 不支持
`--fully-async`、`--hybrid`、`--partial-rollout`、`--use-dynamic-global-batch-size`
    - `--calculate-per-token-loss` 必须开启(锁定 global valid-token reduction)
- `--kl-coef` 必须为 `0`(reward-side KL shaping 暂不支持;KL 约束走 `--use-kl-loss
--kl-loss-coef`)
    - `--max-staleness` 必须为 `0`(不允许 stale rollout)
- 省略 `--rollout-batch-size` 时,会在首次使用前由 `global_batch_size /
n_samples_per_prompt` 派生;不能整除时明确报错,不再静默向下取整或触发 `NoneType * int`。
- `--eps-clip` / `--eps-clip-high` 不参与 RLOO policy loss;RLOO 的
`train/pg_clipfrac` 应恒为 `0`。
  - 无 checkpoint schema、数据格式或默认算法破坏性变更。

#### Verification

- 环境、硬件、commit:

  - 起点:`main@8a54679`
  - Python 3.12.3、PyTorch 2.11.0+cu129、CUDA 12.9、Ray 2.56.1
  - 正式 A/B:2 × NVIDIA A100-PCIE-40GB;20 个可用 CPU,Ray 声明 16 CPU
  - 模型:Qwen3-0.6B;数据:GSM8K train;reward:`math`
- 两臂相同配置:seed 42、rollout seed 42、60
rollouts、`ROLLOUT_BATCH_SIZE=4`、`N_SAMPLES=8`、`GLOBAL_BATCH_SIZE=32`、response
max length 2048、`clip-grad=0`

- 可复制命令:

  ```bash
  # RLOO 聚焦测试
  python -m pytest -p no:cacheprovider -q --no-header \
    tests/utils/test_arguments_rloo.py \
    tests/utils/test_metric_utils_rloo.py \
    tests/utils/training/test_rloo_advantages.py \
    tests/core/test_registry_rloo.py \
    tests/backends/megatron/test_rloo_cp_reduction.py \
    tests/backends/megatron/test_rloo_policy_loss_dispatch.py

  # 全仓静态门禁
  pre-commit run --all-files

  # RLOO 正式配置
  ADVANTAGE_ESTIMATOR=rloo \
  NUM_ROLLOUT=60 \
  ROLLOUT_BATCH_SIZE=4 \
  N_SAMPLES=8 \
  GLOBAL_BATCH_SIZE=32 \
  bash examples/algorithms/run-qwen3-0.6B-1xgpu-rloo.sh \
    --resource '{"actor": [1, 2], "rollout": [1, 2]}' \
    --seed 42 \
    --rollout-seed 42 \
    --train-memory-margin-bytes 1073741824

  # GRPO 对照:其余参数完全相同
  ADVANTAGE_ESTIMATOR=grpo \
  NUM_ROLLOUT=60 \
  ROLLOUT_BATCH_SIZE=4 \
  N_SAMPLES=8 \
  GLOBAL_BATCH_SIZE=32 \
  bash examples/algorithms/run-qwen3-0.6B-1xgpu-rloo.sh \
    --resource '{"actor": [1, 2], "rollout": [1, 2]}' \
    --seed 42 \
    --rollout-seed 42 \
    --train-memory-margin-bytes 1073741824
  ```

- 单元/集成/端到端测试结果:

  - RLOO 聚焦测试:`54 passed`。
- 全量回归 `pytest tests/`:`775 passed, 7 skipped, 48 warnings in
274.06s`,退出码 `0`。
  - 7 个 skip 均为仓库既有的环境/可选依赖条件跳过,不是本 PR 引入的失败。
- `pre-commit run --all-files`:全部 hooks 通过,包括
ruff、ruff-format、mdformat、clang-format、docformatter、gitleaks。
  - `ruff format --check .`:`427 files already formatted`。
- 2-GPU canary:2/2 optimizer steps,RLOO 指标
2/2,`dropped_group_frac=0`,`pg_clipfrac=0`,Ray Job succeeded。
- 正式 RLOO B2:60/60 steps,60/60 RLOO metrics,60/60 `pg_clipfrac=0`,60/60
`dropped_group_frac=0`,Ray Job succeeded。
- 正式 GRPO A2:60/60 steps,60/60 train metrics,0 条 RLOO 指标,60/60
`pg_clipfrac` 指标,Ray Job succeeded。
- 两臂在同一个 Ray head(GCS PID、raylet PID、session 均不变)上串行完成:RLOO 60 → 无重启清理 →
GRPO 60。

- 性能 before/after(若适用):

| 指标 | GRPO A2 | RLOO B2 | RLOO 相对 GRPO |
| ------------------------ | --------------: | --------------: |
-------------------------: |
| mean raw reward | 0.730208 | 0.722396 | -1.07% |
| mean train loss | 0.044097 | -0.024302 | 目标与尺度不同,不直接横比 |
| mean PPO KL diagnostic | 0.000606 | 0.000569 | -6.08% |
| mean step time | 98.996 s | 114.782 s | +15.95% |
| mean token throughput | 446.745 token/s | 389.424 token/s | -12.83% |
| mean response throughput | 419.681 token/s | 365.894 token/s | -12.82%
|
| mean grad norm | 0.817172 | 0.416955 | -48.98% |
| mean entropy | 0.485476 | 0.485813 | +0.07% |
| 最大单卡峰值显存 | 21825 MiB | 21823 MiB | -0.01% |


- 本次(8/13)复跑中 RLOO step time 比 GRPO 慢约 `16%`、吞吐低约 `13%`,与 8/5 的 `-0.1%`
不一致;两臂在同一 Ray head 上串行完成且 RLOO
臂先执行,差异是否含机器负载等环境因素未排除,因此本次**不**做“无性能回归”声明。
  - RLOO 梯度尺度较小(`-48.98%`),符合“保留 raw reward 尺度”与 GRPO“除组内标准差”的算法差异。

##### 核心验收曲线

以下图表由 `generate_charts.py` 直接读取正式运行的 TensorBoard event 生成。每个被绘制的 scalar
均已校验包含完整的 60 个 step;淡色线为逐 step 原始值,实色线为 5-step 移动平均。

###### Raw reward

![RLOO vs GRPO raw
reward](https://github.com/user-attachments/assets/f7596e1d-2c48-4b39-9e31-bfb9fcaeb205)


当前单 seed、60-step 实验用于验证训练可用性和趋势,不用于声称统计显著的质量差异。

###### PPO KL diagnostic

![RLOO vs GRPO PPO KL
diagnostic](https://github.com/user-attachments/assets/42efd01f-c050-417e-b145-1501cdeb8d34)


该指标用于比较相同配置下的策略漂移。两次运行的 KL 均保持有限且稳定。

###### Step time and throughput

![RLOO vs GRPO step time and
throughput](https://github.com/user-attachments/assets/96c835ec-df83-4774-9d60-c20dae73eb01)


图中同时展示 `perf/step_time`、`perf/step_token_per_s` 和
`perf/step_resp_token_per_s`。

###### Response length

![RLOO vs GRPO response
length](https://github.com/user-attachments/assets/b0aa4b3d-b9aa-44e8-a8f6-99d65d3b0b6c)


两种算法的平均 response length 接近,因此吞吐对比没有被显著的输出长度差异混淆。

##### 训练稳定性曲线

<details>
<summary><strong>展开 grad norm、entropy、train loss 和 PG clip
fraction</strong></summary>

###### Gradient norm

![RLOO vs GRPO gradient
norm](https://github.com/user-attachments/assets/6f4e0881-435e-4074-8057-a0f063b67f69)


RLOO 的梯度尺度较小,符合其保留 raw reward 尺度、而 GRPO 使用组内标准差归一化的算法差异。

###### Entropy

![RLOO vs GRPO
entropy](https://github.com/user-attachments/assets/ce268f41-6452-4b12-8680-090b7544958c)


两种算法的 entropy diagnostic 均保持有限,没有出现明显数值异常。

###### Train loss

![RLOO and GRPO train
loss](https://github.com/user-attachments/assets/0de5cd0b-1447-4830-9908-8877e77540ae)

> `train/loss` 仅用于检查各算法自身的训练稳定性。RLOO 与 GRPO 的 objective 和尺度不同,loss
绝对值不能直接用于算法质量比较。

###### Policy-gradient clip fraction

![RLOO vs GRPO PG clip
fraction](https://github.com/user-attachments/assets/26d5856e-9f74-48b1-a1cb-f8acbf43466c)

RLOO 使用非裁剪 REINFORCE,因此 `train/pg_clipfrac` 按定义恒为 `0`;GRPO 可以出现非零
clipping。该图用于验证算法行为,而不是比较模型质量。

</details>

##### RLOO 专属诊断

![RLOO-specific
diagnostics](https://github.com/user-attachments/assets/40398223-47dc-4573-81bc-b484916c289c)


该图展示:

- `rollout/rloo/baseline_mean`
- `rollout/rloo/adv_abs_mean`
- `rollout/rloo/no_signal_frac`
- `rollout/rloo/zero_adv_group_frac`
- `rollout/rloo/empty_response_frac`
- `rollout/rloo/dropped_group_frac`

正式运行中 `empty_response_frac` 与 `dropped_group_frac` 始终为 `0`。


##### 日志、曲线和原始实验产物:

- 完整产物目录(Google Drive):[RLOO / GRPO paired experiment
artifacts](https://drive.google.com/drive/folders/1UfIrQbzA1stu9XEtf8pn_jFKZ-gUg8ev?usp=sharing)
- RLOO
run:[task28-b2-rloo-reviewfix-s42-2xA100-rbs4-g8-gbs32-20260813-183905.console.log](https://drive.google.com/file/d/1p8gmOH3O4yYLKCy5sMEGygQCGzAfnnrv/view?usp=drive_link)
- GRPO
run:[task28-a2-grpo-reviewfix-s42-2xA100-rbs4-g8-gbs32-20260813-183905.console.log](https://drive.google.com/file/d/1lQYF9BtYYxIj-k4-oelbO_k7QT4I9OHA/view?usp=drive_link)
- 每个 arm 均提供 `console.log`、`driver.log`、退出码、10 秒间隔 GPU
utilization/memory/power CSV 和原始 TensorBoard event 文件。
- `generate_charts.py` 直接解析 TensorBoard event,并校验每项绘图指标均包含完整的 60 个
step;图表数据未手工录入。
- `plotted_scalars.csv` 保存所有图表使用的逐 step 原始数值,`SHA256SUMS.txt`
用于校验交付文件完整性。
- 图表包括 raw reward、PPO KL、step time、token/response-token
throughput、response length、grad norm、entropy、train loss、PG clip
fraction,以及六项 RLOO 专属 diagnostics。
- `train/loss` 仅用于观察各算法自身的稳定性;由于 RLOO 与 GRPO 的优化目标及归约尺度不同,其绝对值不用于横向质量比较。
  - 本产物包不包含数据集、checkpoint、密钥或访问令牌。


#### Risk & Rollback

- 已知限制:
  - 仅支持同步训练;fully-async 和 hybrid RLOO 不在本题范围。
- 不支持 partial rollout、dynamic global batch 或同一 rollout 多次 optimizer
update。
- custom reward post-process / custom agentic advantage hook 覆盖标准
advantage 时,标准 `rollout/rloo/*` diagnostics 会关闭;custom hook 训练路径本身不受影响。
- #194 仅修复特定 Ray/cloudpickle 场景下 rollout `INFO` 日志的可见性,不是 RLOO
算法正确性或训练可用性的依赖;其合并后可改善默认可观测性。
- 风险:
- RLOO 不做组内 std normalization,梯度尺度与 GRPO 不同;学习率、clip-grad
等超参不可机械照搬到所有模型和 reward 分布。
- 全同 reward 组会产生零 advantage 和零梯度;这是预期行为,通过 `no_signal_frac` 与
`zero_adv_group_frac` 监控。
- 组不完整时训练 reward 路径 fail-fast;diagnostics 同时通过 `dropped_group_frac`
暴露异常组。
- #194 合并前,Ray/cloudpickle 预注册 logger 的特定场景可能只影响 rollout `INFO`
指标展示;指标已经计算完成,RLOO baseline、advantage、loss、梯度和 optimizer 输入均不受影响。正式 A/B
实验为观察日志临时应用了 #194 修复,但本 PR 最终代码未包含该改动。
- 关闭开关:
  - RLOO 为 opt-in;不传 `--advantage-estimator rloo` 时默认算法行为不变。

#### Checklist

- [x] Diff 仅包含本任务必要改动
- [x] 新增/相关测试全部通过
- [x] 文档、脚本和默认值已更新
- [x] 不含密钥、数据集、checkpoint 或机器隐私信息
- [x] 已逐条回复 review comment

正式双卡 A/B 已在 revert 后的最终交付状态(HEAD `91af9a2`)重新完成;#194 仅改善日志可观测性,不阻塞本 PR
的算法正确性验收。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants