Skip to content

feat(rl): implement REINFORCE++ variants with global normalization - #202

Merged
NINGBENZHE merged 13 commits into
redai-studio:mainfrom
zheself:feat/task29-reinforcepp-v9
Aug 6, 2026
Merged

NINGBENZHE merged 13 commits into
redai-studio:mainfrom
zheself:feat/task29-reinforcepp-v9

Conversation

@zheself

@zheself zheself commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Changes

  • Registers both estimator names and validates their mutually exclusive k1/k2
    configuration contracts.
  • Implements masked token KL reward shaping and reverse returns for
    REINFORCE++.
  • Implements an inclusive same-prompt group-mean baseline without group-std
    normalization, followed by global valid-token normalization.
  • Adds a real DP-aware masked population normalizer (ddof=0, variance floor
    1e-8) with coordinated empty-population handling.
  • Uses boolean masking in return, normalization, and reduction paths so masked
    NaN/Inf storage cannot contaminate valid tokens; a fully masked local
    response remains collective-safe.
  • Integrates response-mean PPO and independent k2 loss semantics plus
    algorithm-specific monitoring metrics in the Megatron loss path.
  • Adds independent float64 element-wise references and a real two-process Gloo
    test; covers variable masks, padding, zero reward, zero variance, one token,
    one empty local rank, PPO clipping, and reduced policy/KL losses.
  • Adds one parameterized Qwen3-0.6B recipe for GRPO and both new variants.
  • Adds a design guide and an equal-budget three-seed training/evaluation report
    with path-free CSV evidence, an 18-job SHA256 evidence index, and SVG curves.

CLI compatibility:

  • Existing estimator defaults and GRPO/GSPO/SAPO paths are unchanged.
  • The two new variants intentionally reject fully-async, hybrid, CP > 1,
    per-token global loss reduction, and inconsistent KL settings because those
    modes do not satisfy the documented closed-global-batch contract.
  • The baseline also rejects custom reward/advantage hooks that would bypass its
    frozen inclusive group-mean semantics.

Verification

Environment and source:

  • Experiment source: 5f7cd574372288391bb1c41ca0677422cd31e725
  • PR base after rebase: 0bc99af8dd39de8fd99c588a98b3f3a463bc818c
  • Current report commit: 83dffaf
  • Current submission head: 83dffaf
  • A git range-diff marks all five trained Task 29 commits patch-identical
    before and after the upstream rebase.
  • GPU image: Python 3.12.3, PyTorch 2.11.0+cu129, CUDA 12.9, Ray 2.56.0,
    SGLang 0.5.12.post1; one NVIDIA A40 per formal run.

Focused host tests after rebase:

PYTHONNOUSERSITE=1 PYTHONPATH=$PWD python -m pytest -q \
  tests/core/test_registry_reinforce_plus_plus.py \
  tests/utils/test_arguments_reinforce_plus_plus.py \
  tests/utils/training/test_reinforce_plus_plus.py \
  tests/utils/test_distributed_masked_normalize.py \
  tests/utils/test_reinforce_reward_processing.py \
  tests/backends/megatron/test_reinforce_plus_plus_loss.py \
  tests/backends/megatron/test_fp16_optimizer_config.py \
  tests/utils/training/test_ppo_utils_grpo.py \
  tests/utils/test_arguments_opd_teacher_colocate.py \
  tests/core/test_registry_sft.py

Result: 55 passed, 2 skipped in 20.37s. The host skips require Megatron,
which is not installed in that Conda environment.

After repository formatters modified six Task 29 files, the focused Task 29
selection was rerun and passed: 43 passed, 1 skipped in 45.97s; the skip is
again the unavailable Megatron-dependent upstream FP16 test.

Final pre-review mask/edge-case audit:

62 passed, 2 skipped in 10.65s

This selection adds masked NaN/Inf, fully masked local response, all-zero
reward/KL, safe reduction, and production-dispatch integration coverage. The
two skips are upstream modules requiring a full Megatron installation.

Broader host regression:

NUMBA_CACHE_DIR=/tmp/task29-numba-cache \
PYTHONNOUSERSITE=1 PYTHONPATH=$PWD python -m pytest -q \
  tests/utils tests/core \
  --ignore=tests/utils/test_metrics_service.py \
  --ignore=tests/utils/test_train_metric_utils.py

Historical post-rebase result: 204 passed, 12 skipped, 3 warnings in 18.61s.
After the final audit additions: 209 passed, 12 skipped, 3 warnings in 26.02s.

Post-rebase pinned-container selection: 57 passed, 1 skipped, 30 warnings in 22.65s. The skip is the upstream FP16 module because the standalone container
process cannot import the image's root-owned Megatron checkout; no Task 29
test is skipped in that result. At the experiment commit, the pinned container
also passed 43 Task 29 tests and 14 metrics tests.

GPU stability and equal-budget comparison:

  • 3 algorithms x 3 training seeds x 50 steps: all nine runs retained 50
    rollout records, 50 Actor updates, finite metrics, and iteration 49.
  • 9 final-checkpoint evaluations x 1,024 responses on an identical frozen
    256-prompt subset: all accepted jobs passed summary/TensorBoard/cleanup
    gates.
  • Fixed-subset reward/pass@1, mean ± sample SD across training seeds:
    • GRPO: 0.6077 ± 0.0133
    • REINFORCE++: 0.5866 ± 0.0135
    • REINFORCE++-baseline: 0.6042 ± 0.0215
  • Mean pass@4: GRPO 0.7773, REINFORCE++ 0.7734, baseline 0.7891.
  • All paired reward 95% t-intervals cross zero; no superiority claim is made.
  • train/ppo_kl is documented as old/current policy drift rather than
    reference KL. Across the three REINFORCE++ seeds, the last-10 mean
    rollout/returns - rollout/raw_reward differences are -0.017225,
    -0.018403, and -0.017273, confirming nonzero k1 return shaping; the
    baseline separately reports finite k2 train/kl_loss.
  • Full commands, numerical semantics, per-seed results, incidents, curves, and
    limitations are in
    docs/en/guide/reinforce-plus-plus-training-report.md.
  • Sanitized raw logs, all 18 expanded commands, GPU samples, metrics and an
    internal manifest are published in the
    reproducibility evidence release.
    Archive SHA256:
    0b52d8e8e6a85ff534e16569dd48c9dbef336402a2c80b6aa96b8bf2ffd7834f.

Additional checks:

  • git diff --check: pass.
  • Changed Python modules and the evidence summarizer compile: pass.
  • Recipe bash -n: pass.
  • Eight SVGs parse with rsvg-convert: pass.
  • 450 published training-step rows match the generated evidence export: pass.
  • The 18 accepted-job SHA256 rows match the retained local manifest and job
    IDs: pass.
  • Path/credential scan of the report assets: pass.
  • The published evidence archive was downloaded again from GitHub; its outer
    SHA256, gzip stream, safe tar paths, 72-file internal manifest and repeated
    sensitive-data scan all passed.
  • Ruff check/format, Python compilation, recipe syntax, conflict-marker,
    ASCII-box, CSV/SVG and sensitive-path checks on the final local delta: pass.
  • Current head 83dffaf passed GitHub pre-commit, lint and the Python
    3.10/3.11/3.12 test matrix (five successful checks).
  • npm run docs:build: pass with Node 20.19.5 and VitePress 1.6.4. Generated
    OpenAPI runtime differences were discarded and are not part of this diff.

Risk & Rollback

  • Global population statistics depend on using the intended data-parallel
    process group; the real Gloo tests cover unequal and empty local
    populations, but the first implementation deliberately rejects async and CP
    modes whose ownership/batch boundary is not closed.
  • The two algorithms reject inconsistent configuration instead of silently
    falling back to another KL or reduction convention.
  • The small-model comparison has only three training seeds, one fixed
    evaluation subset/decoding seed, no initial-checkpoint control, and high
    response truncation. It validates stability, not algorithm superiority.
  • Rollback is selecting an existing estimator or reverting these Task 29
    commits. No checkpoint format, Controller/Service path, or existing
    algorithm default changes.

Checklist

  • Diff only contains Task 29 implementation, tests, recipe, design, and
    validation evidence.
  • New and relevant tests pass in the documented host/container scopes.
  • Documentation, parameterized recipe, raw path-free tables, and curves are
    included.
  • No credentials, datasets, checkpoints, internal paths, or private
    machine identifiers are included.
  • pre-commit run --all-files.
  • VitePress documentation build.
  • Current-head CI.
  • Maintainer review after the PR leaves Draft.

@RexFlux

RexFlux commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

整体看下来有几个地方建议再调整一下:

  1. distributed_masked_normalize() 里用了:

if global_count.item() == 0:

这个函数在每个训练 batch 都会走,.item() 会触发 GPU 到 CPU 的同步,和项目规范冲突。建议改成不触发 host sync 的设备端/异步校验,或者把空 global batch 的检查移到训练热路径之外。

  1. 这次新增了两篇英文正式文档,并接入了英文 sidebar,但没有对应的 docs/zh 页面。Relax 文档目前是中英双语结构,建议补齐中文版本和中文 sidebar,保持内容一致。
  2. cp_utils.py 里的 mask-safe reducer 是通用改动,会影响 GRPO、GSPO、SAPO 等现有算法,不只作用于 REINFORCE++,建议简化实现缩小影响范围

@zheself
zheself force-pushed the feat/task29-reinforcepp-v9 branch from 83dffaf to 6d03e71 Compare August 4, 2026 04:32
@zheself

zheself commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

感谢审阅,三个问题均已调整:

  1. distributed_masked_normalize() 已移除训练热路径中的 global_count.item()。空 global mask 改为使用 torch._assert_async 做设备端异步检查,均值和方差使用设备端安全分母计算。另在 PyTorch synchronization debug mode 下完成了 100 次 CUDA 迭代,没有触发 host-synchronization 错误。

  2. 已补齐中文 REINFORCE++ 设计文档和训练/数值验证报告,并接入中文 sidebar、中文算法索引及 example README。中英文页面的标题层级、公式、代码块和图片资源已做结构一致性检查,VitePress 1.6.4 生产构建通过。

  3. relax/backends/megatron/cp_utils.py 已完全恢复为 upstream 实现。非有限 masked-token 防护现在位于 relax/backends/megatron/loss.py 的局部 wrapper 中,并且只为 reinforce_plus_plus 与 reinforce_plus_plus_baseline dispatch;GRPO、GSPO、SAPO 等算法继续使用原有公共 reducer。

验证结果包括:Task 29 定向测试 51 passed、tests/utils + tests/core 224 passed / 12 skipped、完整 Megatron backend 168 passed / 4 skipped,以及真实双进程 Gloo collective。review 后还分别完成了 REINFORCE++ 和 REINFORCE++-baseline 的三步 Qwen3-0.6B/A40 smoke run,两个作业均完成全部 Actor update、有限指标验证、产物检查及 job-scoped Ray 清理检查。

@RexFlux

RexFlux commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

辛苦开下ready to review

@zheself
zheself marked this pull request as ready for review August 4, 2026 14:09
@RexFlux

RexFlux commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator
image 请补充检查下提交的各文档中的图引用是不是有问题呢,例如:https://github.com/zheself/Relax/blob/6d03e711264ccf143d074085c1729088e65ba6f4/docs/en/guide/reinforce-plus-plus-training-report.md

@zheself

zheself commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

感谢指出。问题确认为 GitHub Markdown Preview 与 VitePress public-root 的路径解析差异:原来的 /reinforce-plus-plus/... 可以被 VitePress 按 /Relax/ base 正确改写,但 GitHub 会从站点根目录解析,因此显示为破图。

已在 commit 7bb75f3 中将中英文训练报告的全部 16 个图片引用改为指向 docs/public/reinforce-plus-plus/ 的仓库相对路径。

验证结果:

  • 英文和中文源文件各包含 8 个图片引用,目标集合完全一致;
  • 8 个 SVG 均存在,XML 解析和栅格化检查通过;
  • VitePress 1.6.4 完整生产构建通过,生成的中英文页面均解析出 8 张有效图片;
  • 已实际请求该 commit 的 GitHub 英文、中文 Preview 页面,两页均生成 8 个指向对应 commit 下 docs/public/reinforce-plus-plus/ 的 raw SVG 地址;
  • 8 个远端 SVG 均返回 HTTP 200、image/svg+xml,并再次通过 XML 解析。

@zheself

zheself commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

补充说明:此前评论中引用的文件链接固定在旧提交 6d03e711,该提交确实仍包含修复前的 /reinforce-plus-plus/... 根路径,因此从该历史 permalink 打开仍会看到 404。

当前 PR head 已是 7bb75f3,修复后的文件链接为仓库相对路径 ../../public/reinforce-plus-plus/<file>.svg。当前 branch Preview 和 commit 7bb75f3 Preview 均实际解析为对应 commit 下的 docs/public/reinforce-plus-plus/ raw 地址;8 个 SVG 均返回 HTTP 200、image/svg+xml。请从当前 PR head 或以下最新文件链接检查:

https://github.com/zheself/Relax/blob/7bb75f342bb8a3f08120ed13b30e813f8d3a9339/docs/en/guide/reinforce-plus-plus-training-report.md

@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 5b23011 into redai-studio:main Aug 6, 2026
5 checks passed
@xcosmosbox xcosmosbox mentioned this pull request Aug 6, 2026
11 of 16 tasks
ZiyiTsang pushed a commit to ZiyiTsang/Relax that referenced this pull request Aug 6, 2026
…edai-studio#202)

#### Summary

- Closes redai-studio#192。
- 新增两个命名明确、实现相互独立的优势估计器:
  `reinforce_plus_plus` 和 `reinforce_plus_plus_baseline`。
- 基于 REINFORCE++ v9 主公式和固定版本的 OpenRLHF 归一化参考,明确并冻结
  return、baseline、mask、分布式归一化、KL 与 reduction 语义,同时记录二者在
  KL 处理上的差异。
- 使用独立的总体统计实现,确保现有 GRPO、GSPO 和 SAPO 行为保持不变。

#### Changes

- Registers both estimator names and validates their mutually exclusive
k1/k2
  configuration contracts.
- Implements masked token KL reward shaping and reverse returns for
  REINFORCE++.
- Implements an inclusive same-prompt group-mean baseline without
group-std
  normalization, followed by global valid-token normalization.
- Adds a real DP-aware masked population normalizer (`ddof=0`, variance
floor
  `1e-8`) with coordinated empty-population handling.
- Uses boolean masking in return, normalization, and reduction paths so
masked
`NaN`/`Inf` storage cannot contaminate valid tokens; a fully masked
local
  response remains collective-safe.
- Integrates response-mean PPO and independent k2 loss semantics plus
  algorithm-specific monitoring metrics in the Megatron loss path.
- Adds independent float64 element-wise references and a real
two-process Gloo
test; covers variable masks, padding, zero reward, zero variance, one
token,
  one empty local rank, PPO clipping, and reduced policy/KL losses.
- Adds one parameterized Qwen3-0.6B recipe for GRPO and both new
variants.
- Adds a design guide and an equal-budget three-seed training/evaluation
report
with path-free CSV evidence, an 18-job SHA256 evidence index, and SVG
curves.

CLI compatibility:

- Existing estimator defaults and GRPO/GSPO/SAPO paths are unchanged.
- The two new variants intentionally reject fully-async, hybrid, CP > 1,
per-token global loss reduction, and inconsistent KL settings because
those
  modes do not satisfy the documented closed-global-batch contract.
- The baseline also rejects custom reward/advantage hooks that would
bypass its
  frozen inclusive group-mean semantics.

#### Verification

Environment and source:

- Experiment source: `5f7cd574372288391bb1c41ca0677422cd31e725`
- PR base after rebase: `0bc99af8dd39de8fd99c588a98b3f3a463bc818c`
- Current report commit: `83dffaf`
- Current submission head: `83dffaf`
- A `git range-diff` marks all five trained Task 29 commits
patch-identical
  before and after the upstream rebase.
- GPU image: Python 3.12.3, PyTorch 2.11.0+cu129, CUDA 12.9, Ray 2.56.0,
  SGLang 0.5.12.post1; one NVIDIA A40 per formal run.

Focused host tests after rebase:

```bash
PYTHONNOUSERSITE=1 PYTHONPATH=$PWD python -m pytest -q \
  tests/core/test_registry_reinforce_plus_plus.py \
  tests/utils/test_arguments_reinforce_plus_plus.py \
  tests/utils/training/test_reinforce_plus_plus.py \
  tests/utils/test_distributed_masked_normalize.py \
  tests/utils/test_reinforce_reward_processing.py \
  tests/backends/megatron/test_reinforce_plus_plus_loss.py \
  tests/backends/megatron/test_fp16_optimizer_config.py \
  tests/utils/training/test_ppo_utils_grpo.py \
  tests/utils/test_arguments_opd_teacher_colocate.py \
  tests/core/test_registry_sft.py
```

Result: `55 passed, 2 skipped in 20.37s`. The host skips require
Megatron,
which is not installed in that Conda environment.

After repository formatters modified six Task 29 files, the focused Task
29
selection was rerun and passed: `43 passed, 1 skipped in 45.97s`; the
skip is
again the unavailable Megatron-dependent upstream FP16 test.

Final pre-review mask/edge-case audit:

```text
62 passed, 2 skipped in 10.65s
```

This selection adds masked `NaN`/`Inf`, fully masked local response,
all-zero
reward/KL, safe reduction, and production-dispatch integration coverage.
The
two skips are upstream modules requiring a full Megatron installation.

Broader host regression:

```bash
NUMBA_CACHE_DIR=/tmp/task29-numba-cache \
PYTHONNOUSERSITE=1 PYTHONPATH=$PWD python -m pytest -q \
  tests/utils tests/core \
  --ignore=tests/utils/test_metrics_service.py \
  --ignore=tests/utils/test_train_metric_utils.py
```

Historical post-rebase result: `204 passed, 12 skipped, 3 warnings in
18.61s`.
After the final audit additions: `209 passed, 12 skipped, 3 warnings in
26.02s`.

Post-rebase pinned-container selection: `57 passed, 1 skipped, 30
warnings in
22.65s`. The skip is the upstream FP16 module because the standalone
container
process cannot import the image's root-owned Megatron checkout; no Task
29
test is skipped in that result. At the experiment commit, the pinned
container
also passed 43 Task 29 tests and 14 metrics tests.

GPU stability and equal-budget comparison:

- 3 algorithms x 3 training seeds x 50 steps: all nine runs retained 50
  rollout records, 50 Actor updates, finite metrics, and iteration 49.
- 9 final-checkpoint evaluations x 1,024 responses on an identical
frozen
256-prompt subset: all accepted jobs passed summary/TensorBoard/cleanup
  gates.
- Fixed-subset reward/pass@1, mean ± sample SD across training seeds:
  - GRPO: `0.6077 ± 0.0133`
  - REINFORCE++: `0.5866 ± 0.0135`
  - REINFORCE++-baseline: `0.6042 ± 0.0215`
- Mean pass@4: GRPO `0.7773`, REINFORCE++ `0.7734`, baseline `0.7891`.
- All paired reward 95% t-intervals cross zero; no superiority claim is
made.
- `train/ppo_kl` is documented as old/current policy drift rather than
  reference KL. Across the three REINFORCE++ seeds, the last-10 mean
  `rollout/returns - rollout/raw_reward` differences are `-0.017225`,
`-0.018403`, and `-0.017273`, confirming nonzero k1 return shaping; the
  baseline separately reports finite k2 `train/kl_loss`.
- Full commands, numerical semantics, per-seed results, incidents,
curves, and
  limitations are in
  `docs/en/guide/reinforce-plus-plus-training-report.md`.
- Sanitized raw logs, all 18 expanded commands, GPU samples, metrics and
an
  internal manifest are published in the
[reproducibility evidence
release](https://github.com/zheself/Relax/releases/tag/task29-reinforcepp-evidence-c72caf1).
  Archive SHA256:
  `0b52d8e8e6a85ff534e16569dd48c9dbef336402a2c80b6aa96b8bf2ffd7834f`.

Additional checks:

- `git diff --check`: pass.
- Changed Python modules and the evidence summarizer compile: pass.
- Recipe `bash -n`: pass.
- Eight SVGs parse with `rsvg-convert`: pass.
- 450 published training-step rows match the generated evidence export:
pass.
- The 18 accepted-job SHA256 rows match the retained local manifest and
job
  IDs: pass.
- Path/credential scan of the report assets: pass.
- The published evidence archive was downloaded again from GitHub; its
outer
SHA256, gzip stream, safe tar paths, 72-file internal manifest and
repeated
  sensitive-data scan all passed.
- Ruff check/format, Python compilation, recipe syntax, conflict-marker,
ASCII-box, CSV/SVG and sensitive-path checks on the final local delta:
pass.
- Current head `83dffaf` passed GitHub pre-commit, lint and the Python
  3.10/3.11/3.12 test matrix (five successful checks).
- `npm run docs:build`: pass with Node 20.19.5 and VitePress 1.6.4.
Generated
OpenAPI runtime differences were discarded and are not part of this
diff.

#### Risk & Rollback

- Global population statistics depend on using the intended
data-parallel
  process group; the real Gloo tests cover unequal and empty local
populations, but the first implementation deliberately rejects async and
CP
  modes whose ownership/batch boundary is not closed.
- The two algorithms reject inconsistent configuration instead of
silently
  falling back to another KL or reduction convention.
- The small-model comparison has only three training seeds, one fixed
evaluation subset/decoding seed, no initial-checkpoint control, and high
response truncation. It validates stability, not algorithm superiority.
- Rollback is selecting an existing estimator or reverting these Task 29
  commits. No checkpoint format, Controller/Service path, or existing
  algorithm default changes.

#### Checklist

- [x] Diff only contains Task 29 implementation, tests, recipe, design,
and
  validation evidence.
- [x] New and relevant tests pass in the documented host/container
scopes.
- [x] Documentation, parameterized recipe, raw path-free tables, and
curves are
  included.
- [x] No credentials, datasets, checkpoints, internal paths, or private
  machine identifiers are included.
- [x] `pre-commit run --all-files`.
- [x] VitePress documentation build.
- [x] Current-head CI.
- [ ] Maintainer review after the PR leaves Draft.

---------

Co-authored-by: 郑宝炜 <[email protected]>
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 29 Proposal] REINFORCE++ / REINFORCE++-baseline: v9 semantics, numerical parity, and distributed normalization

4 participants