Skip to content

【NO.28】实现 RLOO advantage estimator - #205

Merged
NINGBENZHE merged 10 commits into
redai-studio:mainfrom
xcosmosbox:task/issue-186
Aug 18, 2026
Merged

NINGBENZHE merged 10 commits into
redai-studio:mainfrom
xcosmosbox:task/issue-186

Conversation

@xcosmosbox

@xcosmosbox xcosmosbox commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

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 计算:
$$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,并计算非裁剪目标:

    $$\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、Dr.GRPO、TRL RLOOTrainer、ms-swift RLOO、OpenRLHF、verl loss aggregation。

Testing

  • pre-commit run --all-files passes
  • Tests pass (pytest tests/)
  • New tests added (if applicable)
  • 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)
  • 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

Detailed Delivery Review

Summary

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

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

$$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)$$
  • 策略损失为:
$$\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 分发测试等审查中发现的问题。

  • fix(logging_utils): preserve logger hierarchy and eliminate global class mutation #194 是独立的 logger hierarchy 可观测性修复:它解决 Ray/cloudpickle 场景下 rollout INFO 日志可能不可见的问题,但不参与 RLOO 的 baseline、advantage、loss、梯度、optimizer update 或指标计算,因此不影响本 PR 算法与功能的正确性。本地端到端实验临时应用了该修复以便观察 rollout/rloo/*;本 PR 的最终 diff 不包含 logging_utils.py 改动,也不以 fix(logging_utils): preserve logger hierarchy and eliminate global class mutation #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@8a54679e971087566bfda939a5f75649e07fb861
    • 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
  • 可复制命令:

    # 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

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

PPO KL diagnostic

RLOO vs GRPO PPO KL diagnostic

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

Step time and throughput

RLOO vs GRPO step time and throughput

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

Response length

RLOO vs GRPO response length

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

训练稳定性曲线
展开 grad norm、entropy、train loss 和 PG clip fraction
Gradient norm

RLOO vs GRPO gradient norm

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

Entropy

RLOO vs GRPO entropy

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

Train loss

RLOO and GRPO train loss

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

Policy-gradient clip fraction

RLOO vs GRPO PG clip fraction

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

RLOO 专属诊断

RLOO-specific diagnostics

该图展示:

  • 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
  • RLOO run:task28-b2-rloo-reviewfix-s42-2xA100-rbs4-g8-gbs32-20260813-183905.console.log
  • GRPO run:task28-a2-grpo-reviewfix-s42-2xA100-rbs4-g8-gbs32-20260813-183905.console.log
  • 每个 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 训练路径本身不受影响。
    • fix(logging_utils): preserve logger hierarchy and eliminate global class mutation #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 暴露异常组。
    • fix(logging_utils): preserve logger hierarchy and eliminate global class mutation #194 合并前,Ray/cloudpickle 预注册 logger 的特定场景可能只影响 rollout INFO 指标展示;指标已经计算完成,RLOO baseline、advantage、loss、梯度和 optimizer 输入均不受影响。正式 A/B 实验为观察日志临时应用了 fix(logging_utils): preserve logger hierarchy and eliminate global class mutation #194 修复,但本 PR 最终代码未包含该改动。
  • 关闭开关:
    • RLOO 为 opt-in;不传 --advantage-estimator rloo 时默认算法行为不变。

Checklist

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

正式双卡 A/B 已在 revert 后的最终交付状态(HEAD 91af9a2)重新完成;#194 仅改善日志可观测性,不阻塞本 PR 的算法正确性验收。

@xcosmosbox
xcosmosbox marked this pull request as draft August 1, 2026 12:52
@xcosmosbox
xcosmosbox marked this pull request as ready for review August 1, 2026 17:30
@xcosmosbox
xcosmosbox requested a review from yxyOo as a code owner August 1, 2026 17:30

@yuanlehome yuanlehome left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

整体实现覆盖了 leave-one-out baseline、非裁剪 policy loss、同步单次更新约束、指标、文档和端到端验证,完成度较高;但当前仍有三处公开合法配置会静默改变或破坏 RLOO 训练语义,因此先请求修改:

  1. validator 没有锁定最终 reduction,CP=1 默认路径会按每条 response 长度重新加权样本;
  2. --kl-coef 会触发 reference/KL 计算,但 KL 数值没有进入 RLOO objective;
  3. 没有限制 --max-staleness 0,仍可能产生无 importance-ratio correction 的 stale rollout。

建议修复后补齐 production 参数测试,以及不等长 response 的最终 scalar loss/gradient oracle。另建议后续明确 custom converter、custom PG reducer、TIS/OPSM 等扩展与 RLOO 的兼容契约,避免 estimator 名称与实际 optimizer 输入不一致。

Comment thread relax/utils/arguments.py Resolved
Comment thread relax/backends/megatron/loss.py Resolved
Comment thread relax/utils/arguments.py Resolved
@xcosmosbox

Copy link
Copy Markdown
Contributor Author

整体实现覆盖了 leave-one-out baseline、非裁剪 policy loss、同步单次更新约束、指标、文档和端到端验证,完成度较高;但当前仍有三处公开合法配置会静默改变或破坏 RLOO 训练语义,因此先请求修改:

  1. validator 没有锁定最终 reduction,CP=1 默认路径会按每条 response 长度重新加权样本;
  2. --kl-coef 会触发 reference/KL 计算,但 KL 数值没有进入 RLOO objective;
  3. 没有限制 --max-staleness 0,仍可能产生无 importance-ratio correction 的 stale rollout。

建议修复后补齐 production 参数测试,以及不等长 response 的最终 scalar loss/gradient oracle。另建议后续明确 custom converter、custom PG reducer、TIS/OPSM 等扩展与 RLOO 的兼容契约,避免 estimator 名称与实际 optimizer 输入不一致。

感谢 yuanlehome 老师的审阅。我已针对三点意见全部完成修复:

  1. RLOO 现在强制要求 --calculate-per-token-loss,将 loss 锁定为 global-valid-token 归一化,并补充了不等长 response 的最终 scalar/gradient oracle;
  2. 非零 --kl-coef 会被拒绝,并引导使用受支持的直接 KL loss 路径(--use-kl-loss --kl-loss-coef);
  3. 强制 --max-staleness 0,保证同步 on-policy、单次更新语义。

PR 描述和相关文档已同步更新。同时我在同一个 Ray head 上重新完成了 RLOO/GRPO 各 60 步的配对验证(两臂均 60/60 完成,退出码 0,无非有限数值或崩溃),并将最新日志、TensorBoard 数据及全部图表上传到了 Google Drive,链接已附在 PR 中。再次,感谢您的审阅,祝好。

@xcosmosbox
xcosmosbox requested a review from yuanlehome August 5, 2026 04:57

@yuanlehome yuanlehome left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@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.

有冲突也需要解决一下

Comment thread relax/backends/megatron/cp_utils.py Resolved
@NINGBENZHE

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a4b838d9dc

ℹ️ 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".

Comment thread relax/backends/megatron/model.py Outdated
# CP degree under dynamic CP (and is a no-op under static CP, where the
# count previously carried the cancelling cp factor).
loss_reduced[key] = value / num_samples_or_tokens
if num_samples_or_tokens == 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Skip optimizer updates for zero-token steps

When every generated response has response_length == 0, this check identifies a no-signal step only after optimizer.step() has already run at line 1142 and the scheduler can advance at line 1166. The empty-response loss path deliberately connects a zero loss through 0 * logits.sum(), so an optimizer with existing momentum or nonzero weight decay can still change model parameters despite there being no training signal. Detect the globally reduced zero-token condition before the optimizer and skip both the parameter and scheduler updates while preserving required collectives.

Useful? React with 👍 / 👎.

@xcosmosbox xcosmosbox Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这一问题并不是 PR 自身的行为导致的,要想修复这一问题 必须在合入后提新的 issue或作为下一阶段的任务,理由如下:
- 这是 PR 前就存在的共享行为,PR 只是通过代码增强了可见性(在此之前,这个问题是默认失败,但不可见)
- 触发条件被 validator 和数据流程排除在正常路径之外,正常数据流下几乎不可能出现;真出现说明数据管线故障
- 修复必须动全部算法,风险过大,所以建议作为独立 issue 统一处理。修复需要在所有算法共用的 train_one_step 路径上插入新的全局通信(num_tokens 的 DP all-reduce + PP broadcast)或包装 finalize_model_grads 传回归约结果,还要处理跳过 optimizer.step() 时 grad_scaler 的状态管理——改动影响 PPO/GRPO/GSPO/SAPO/REINFORCE++ 全部算法。

不过我觉得这个问题确实比较关键,我可以现在就单独起个 issue 把这个修了。
@codex @NINGBENZHE

这一问题并不是 PR 自身的行为导致的,修复必须动全部算法,风险过大,不宜在本 PR 内处理。 (此前的顾虑在完成本地实验后已排除,见下)

不过我在本地对"最小修复方案"做了完整实验,结论与预期不同:改动范围很小,且已完成本地回归验证。具体方案如下。

修复方案(仅动 1 个生产文件)

在共享 trainer relax/backends/megatron/model.py 的 train_one_step 中,于 optimizer.step() 之前检测"全局零有效 token",全 rank 一致决定跳过参数与 LR 更新:

def _is_global_zero_token_step(losses_reduced) -> bool:
    signal = torch.zeros(1, dtype=torch.int64, device=torch.cuda.current_device())
    if mpu.is_pipeline_last_stage(ignore_virtual=True):
        num_tokens_local = sum(x["values"][0] for x in losses_reduced)
        torch.distributed.all_reduce(
            num_tokens_local,
            group=mpu.get_data_parallel_group(with_context_parallel=True),
        )
        signal[0] = 1 if num_tokens_local.item() == 0 else 0
    torch.distributed.broadcast(
        signal,
        src=mpu.get_pipeline_model_parallel_world_size() - 1,
        group=mpu.get_pipeline_model_parallel_group(),
    )
    return bool(signal.item())

train_one_step 中:

valid_step = True
if _is_global_zero_token_step(losses_reduced):
    logger.warning(
        "Training step %d has zero effective loss tokens globally; skipping "
        "optimizer and LR scheduler updates.", step_id)
    update_successful = True
    grad_norm = 0.0
else:
    update_successful, grad_norm, num_zeros_in_grad = optimizer.step()
    ...  # 原有 NaN/Inf 检测与 scheduler.step() 保持不变

关键点:

  • 每步仅新增 1 次标量 DP(+CP) all-reduce + 1 次 PP broadcast(PP=1 时 no-op),不包装 finalize_model_grads,不触碰 grad_scaler 状态——因为零 token 步梯度恒为 0,全 rank 一致跳过 optimizer.step() 是安全的,zero_grad 照常执行;
  • 正常路径行为完全不变,zero-token 分支只在全 batch 空/全 mask 时触发;
  • 该检测对 PPO/GRPO/GSPO/SAPO/REINFORCE++/RLOO 全部算法通用(共享 train_one_step)。

本地回归结果

关于提交

该修复目前没有提交为 commit。因为它并非本 PR 引入的问题(PR 前即存在,只是被 clamp_min 掩盖),是否应并入本 PR 存在归属争议,因此我先把方案、代码与回归结果仅做讨论展示,由 NINGBENZHE 您来决定:并入本 PR,还是作为独立 issue + 独立 PR 处理。如若同意,我可以立刻以本方案提交 commit。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@xcosmosbox

Copy link
Copy Markdown
Contributor Author

有冲突也需要解决一下

好的,我来解决下,这个冲突应该是因为一个小时前才合入 main 分支的更新导致的,昨天还是正常状态。我看看到底如何解决

Enforce valid configuration guardrails in RLOO production validator:
- Require calculate‑per‑token‑loss, reject False path, add unequal‑length oracle test
- Reject kl_coef != 0, guide to use‑kl‑loss path; full reward‑side KL shaping deferred to follow‑up PR (redai-studio#82)
- Enforce max_staleness=0 to prevent stale rollouts violating synchronous on‑policy semantics

Corresponding test updates and documentation changes are included.
Existing validated RLOO recipes are unaffected; other algorithms keep original behaviour.
Rebasing onto latest main auto-merged the RLOO argument guards twice:
the stale block inside `if not is_sft:` plus the updated block that
adds `--calculate-per-token-loss`, `--max-staleness 0`, and non-zero
`--kl-coef` rejection. Remove the old copy so `--num-steps-per-rollout 1`
is enforced before the batch-size consistency check and exactly one
RLOO validator remains.
@xcosmosbox

Copy link
Copy Markdown
Contributor Author

有冲突也需要解决一下

您好老师,

PR 已完成与最新 main 的冲突合并,冲突发生的原因并不是因为与最新代码发生了对同一处代码的修改,而是两个新的对同一空白位置进行了新代码的增加,并不存在冲突的功能代码。

在对齐最新 main 后,我同时发现 #202 引入的一个测试隔离问题:test_registry_reinforce_plus_plus.py 的 registry_module fixture 在 teardown 中弹出 sys.modules["relax.core.registry"] 后未恢复,导致同一 pytest 进程内的后续测试(如 test_registry_sft.py,以及本 PR 新增的 test_registry_rloo.py)在全量运行时因模块实例不一致而失败。该问题在纯 main 上同样存在,与本 PR 的改动相互独立。

因此我没有将这一修复并入本 PR,而是同步提交了一个独立的 PR #250 ,以避免扩大这个 PR 的改动范围。两者代码相互独立,不构成合入依赖。

烦请您验收现在的代码并对我在 codex 下的回复做出决断,我是否需要在这个 PR 中对 “Skip optimizer updates for zero-token steps” 问题进行增强/修复?再次,感谢您的辛苦审阅,祝好!

@xcosmosbox
xcosmosbox requested a review from NINGBENZHE August 6, 2026 10:58
@NINGBENZHE

Copy link
Copy Markdown
Member

有冲突也需要解决一下

您好老师,

PR 已完成与最新 main 的冲突合并,冲突发生的原因并不是因为与最新代码发生了对同一处代码的修改,而是两个新的对同一空白位置进行了新代码的增加,并不存在冲突的功能代码。

在对齐最新 main 后,我同时发现 #202 引入的一个测试隔离问题:test_registry_reinforce_plus_plus.py 的 registry_module fixture 在 teardown 中弹出 sys.modules["relax.core.registry"] 后未恢复,导致同一 pytest 进程内的后续测试(如 test_registry_sft.py,以及本 PR 新增的 test_registry_rloo.py)在全量运行时因模块实例不一致而失败。该问题在纯 main 上同样存在,与本 PR 的改动相互独立。

因此我没有将这一修复并入本 PR,而是同步提交了一个独立的 PR #250 ,以避免扩大这个 PR 的改动范围。两者代码相互独立,不构成合入依赖。

烦请您验收现在的代码并对我在 codex 下的回复做出决断,我是否需要在这个 PR 中对 “Skip optimizer updates for zero-token steps” 问题进行增强/修复?再次,感谢您的辛苦审阅,祝好!

非常好的贡献,但是建议本PR聚焦RLOO算法实现优先合入,回退这套 shared zero-token 改动,不必为 RLOO 单独修 normalizer 或加_is_global_zero_token_step。
保留 RLOO 的 advantage、unclipped loss、RLOO 专属参数约束及非空样本的 CP 测试。
删除 PR 中“空/全 mask response 是已支持的 no-signal 正常路径”的代码、测试和文档承诺。
另外可以把 CP=1/CP>1 的 zero-token 语义、optimizer step 语义作为后续独立基础设施问题处理,另起一个新的PR,方便内部做全量算法CE验证,感谢~

@xcosmosbox

Copy link
Copy Markdown
Contributor Author

有冲突也需要解决一下

您好老师,
PR 已完成与最新 main 的冲突合并,冲突发生的原因并不是因为与最新代码发生了对同一处代码的修改,而是两个新的对同一空白位置进行了新代码的增加,并不存在冲突的功能代码。
在对齐最新 main 后,我同时发现 #202 引入的一个测试隔离问题:test_registry_reinforce_plus_plus.py 的 registry_module fixture 在 teardown 中弹出 sys.modules["relax.core.registry"] 后未恢复,导致同一 pytest 进程内的后续测试(如 test_registry_sft.py,以及本 PR 新增的 test_registry_rloo.py)在全量运行时因模块实例不一致而失败。该问题在纯 main 上同样存在,与本 PR 的改动相互独立。
因此我没有将这一修复并入本 PR,而是同步提交了一个独立的 PR #250 ,以避免扩大这个 PR 的改动范围。两者代码相互独立,不构成合入依赖。
烦请您验收现在的代码并对我在 codex 下的回复做出决断,我是否需要在这个 PR 中对 “Skip optimizer updates for zero-token steps” 问题进行增强/修复?再次,感谢您的辛苦审阅,祝好!

非常好的贡献,但是建议本PR聚焦RLOO算法实现优先合入,回退这套 shared zero-token 改动,不必为 RLOO 单独修 normalizer 或加_is_global_zero_token_step。 保留 RLOO 的 advantage、unclipped loss、RLOO 专属参数约束及非空样本的 CP 测试。 删除 PR 中“空/全 mask response 是已支持的 no-signal 正常路径”的代码、测试和文档承诺。 另外可以把 CP=1/CP>1 的 zero-token 语义、optimizer step 语义作为后续独立基础设施问题处理,另起一个新的PR,方便内部做全量算法CE验证,感谢~

好的 NINGBENZHE 老师,谢您的审阅意见。
我已完成全部要求的修改,并已在 revert 后的最终代码上重新完成验证,请审阅合并。

代码部分

  • 按您的意见回退了 shared zero-token 改动:get_cp_local_num_tokens() 恢复历史 per-sample clamp_min(loss_mask.sum(), 1) 计数口径;移除空 response 的切片特殊处理与 no-signal step 的指标归一化逻辑,不再为“空/全 mask response”维护特殊路径。
  • 保留了 RLOO 的 advantage、unclipped loss、RLOO 专属参数约束(--calculate-per-token-loss、--kl-coef=0、--max-staleness 0)及非空样本的 CP 测试。
  • 相关文档已同步回退口径。

验证(revert 后的最终代码上重新执行)

  • 正式双卡 60-rollout A/B 已重跑:RLOO 与 GRPO 各 60/60 steps,两臂在同一个 Ray head 上串行完成(RLOO 60 → 无重启清理 → GRPO 60),pg_clipfrac=0、dropped_group_frac=0,无 OOM/worker crash/非有限值。
  • RLOO 聚焦测试 54 passed;全量 1206 passed, 15 skipped,另有 4 个失败均为测试顺序依赖(单独重跑各自通过),与本次改动无关,相关隔离问题在 fix(test): restore registry module after reinforce++ registry fixture #250 中处理。
  • 性能表已更新为本次复跑数据

再次,感谢您的时间,恳请审阅并合并,祝好!

@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 98a7234 into redai-studio:main Aug 18, 2026
5 checks passed
Men1scus added a commit to Men1scus/Relax that referenced this pull request Aug 24, 2026
`--advantage-estimator` was interpreted independently in six places: role
lookup, reward normalisation, the advantage formula, the policy loss, and two
rounds of argument validation. Adding an algorithm meant finding all of them,
and missing one failed late -- `reinforce_plus_plus` was accepted by argparse
while absent from `ALGOS`, crashing in `controller.register_all_serve`.

`AlgorithmSpec` states those facts once. It holds string identifiers rather
than callables: the advantage formula runs in the `Advantages` Ray Serve
deployment while the policy loss runs in the Megatron worker, and those two
processes import different module subsets, so each resolves the name against
its own table. That also keeps the module free of heavy imports, which is what
lets the registry be tested on a CPU-only runner.

Only fields with a consumer are included. Role topology comes from
`needs_critic`, so PPO keeps its Critic and nothing hard-codes the name;
`process_role` is untouched, since it selects the role *iteration order* and
that is the controller's orchestration surface.

Both advantage call sites now share one handler while keeping their real
differences: the Megatron path passes `padded_total_lengths` (GAE slices CP
shards at padded offsets, and passing nothing there reads the wrong token
positions rather than raising), the Advantages deployment cannot compute it and
passes nothing.

RLOO (redai-studio#205), which landed on main after this branch opened, is migrated in
rather than merged alongside: keeping either side of that conflict was wrong,
since taking this branch drops RLOO and taking main restores the algorithm-name
branches. Its reward stage becomes the `group_leave_one_out` normaliser, its
unclipped objective a `POLICY_LOSS_FNS` entry, and its eleven startup
constraints five capability fields. `requires_on_policy_updates` is one field
for five of those knobs because they have one cause -- an objective with no
importance-ratio correction cannot account for the policy having moved -- and
the spec says so, including that RLOO is currently its only member.

Two duplicate REINFORCE++ name sets in `loss.py` (advantage normalisation at
653, the loss reducer at 813) become `advantage_normalization`. They had to
stay in step because token-global normalisation is only correct together with
the mask-safe reducer, and nothing enforced that. The test that was supposed to
catch them was blind: it banned `args.advantage_estimator in [` while the
implementation wrote `in {`. It is now a regex over every spelling, with its
own test, and reintroducing `in {` turns it red.

No behaviour change is intended: the normalisers reproduce the previous
arithmetic constant for constant, including the 1e-6 group epsilon and the
`--disable-grpo-std-normalization` gate, and RLOO's reward output is compared
against a transcription of main's inline branch rather than against the helper
it shares.

Tests: 1576 passed, 323 skipped. The 2 failures + 2 errors are identical to
main@4899b8f on this machine (no /dev/shm on macOS; one pre-existing
reward_router failure), verified in a detached worktree at that commit.
`pre-commit run --all-files` clean.
Men1scus added a commit to Men1scus/Relax that referenced this pull request Aug 24, 2026
`--advantage-estimator` was interpreted independently in six places: role
lookup, reward normalisation, the advantage formula, the policy loss, and two
rounds of argument validation. Adding an algorithm meant finding all of them,
and missing one failed late -- `reinforce_plus_plus` was accepted by argparse
while absent from `ALGOS`, crashing in `controller.register_all_serve`.

`AlgorithmSpec` states those facts once. It holds string identifiers rather
than callables: the advantage formula runs in the `Advantages` Ray Serve
deployment while the policy loss runs in the Megatron worker, and those two
processes import different module subsets, so each resolves the name against
its own table. That also keeps the module free of heavy imports, which is what
lets the registry be tested on a CPU-only runner.

Only fields with a consumer are included. Role topology comes from
`needs_critic`, so PPO keeps its Critic and nothing hard-codes the name;
`process_role` is untouched, since it selects the role *iteration order* and
that is the controller's orchestration surface.

Both advantage call sites now share one handler while keeping their real
differences: the Megatron path passes `padded_total_lengths` (GAE slices CP
shards at padded offsets, and passing nothing there reads the wrong token
positions rather than raising), the Advantages deployment cannot compute it and
passes nothing.

RLOO (redai-studio#205), which landed on main after this branch opened, is migrated in
rather than merged alongside: keeping either side of that conflict was wrong,
since taking this branch drops RLOO and taking main restores the algorithm-name
branches. Its reward stage becomes the `group_leave_one_out` normaliser, its
unclipped objective a `POLICY_LOSS_FNS` entry, and its eleven startup
constraints six capability fields. `requires_on_policy_updates` is one field
for five of those knobs because they have one cause -- an objective with no
importance-ratio correction cannot account for the policy having moved -- and
the spec says so, including that RLOO is currently its only member.

Two duplicate REINFORCE++ name sets in `loss.py` (advantage normalisation at
main's 691, the loss reducer at 851) become `advantage_normalization`. They had to
stay in step because token-global normalisation is only correct together with
the mask-safe reducer, and nothing enforced that. The test that was supposed to
catch them was blind: it banned `args.advantage_estimator in [` while the
implementation wrote `in {`. It is now a regex over every spelling, with its
own test, and reintroducing `in {` turns it red.

No behaviour change is intended: the normalisers reproduce the previous
arithmetic constant for constant, including the 1e-6 group epsilon and the
`--disable-grpo-std-normalization` gate, and RLOO's reward output is compared
against a transcription of main's inline branch rather than against the helper
it shares.

`apply_custom_config_overrides` re-runs every algorithm validator, not two of
them. `validate_reward_side_kl`, `validate_update_schedule` and
`validate_batch_shape` were split out of `validate_algorithm_args` because
validation has a derivation order, and only two of the four were wired back
into the override path -- so a YAML file could select rloo and then set
`--kl-coef`, `--num-steps-per-rollout 4`, or a `global_batch_size` that breaks
the one-update guarantee, with nothing objecting. `derive_global_batch_size` is
extracted for the same reason: `validate_batch_shape` reads the value that
derivation writes, and re-running the validator without it rejected a
legitimate config (a YAML moving 4 steps to 1 got compared against the batch
size derived from 4). The comment above the calls lists what this still does
*not* cover -- six non-algorithm checks that run before the merge -- because
closing that class means merging the YAML before validation, which is larger
than this change.

Provenance in `test_dispatch_parity_vs_main.py` was wrong and is corrected:
the header named a main SHA that does not exist in the repository, `MAIN_SHA`
held a third, unrelated commit, and the transcribed line numbers pointed at a
July revision with no rloo in it. All of them now name
main@4899b8f3a90489840a736897b4c341d87c6267cf and its actual lines; nothing
between 98a7234 and that commit touched advantages.py, loss.py, utils.py or
ppo_utils.py.

Docs: the estimator table listed every registered algorithm except the one
this branch adds, and the module tree named `numerics.py`, which does not
exist here.

Tests: 1580 passed, 323 skipped. The 2 failures + 2 errors are identical to
main@4899b8f on this machine (no /dev/shm on macOS; one pre-existing
reward_router failure), verified in a detached worktree at that commit.
`pre-commit run --all-files` clean.
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.

[Task 28] 实现 RLOO advantage estimator

3 participants