【Task 40】Feat(p3o): add ESS-adaptive policy optimization - #272
Open
DreamEnding wants to merge 31 commits into
Open
【Task 40】Feat(p3o): add ESS-adaptive policy optimization#272DreamEnding wants to merge 31 commits into
DreamEnding wants to merge 31 commits into
Conversation
11 tasks
This was referenced Aug 13, 2026
DreamEnding
marked this pull request as ready for review
August 13, 2026 13:35
DreamEnding
requested review from
Aurelius84,
Yangruipis and
yxyOo
as code owners
August 13, 2026 13:35
There was a problem hiding this comment.
Pull request overview
This PR adds the P3O (ESS-adaptive policy optimization) algorithm to Relax’s RL training stack, including Megatron backend loss integration, optional optimizer-step ESS pre-pass replay, and rollout-side behavior logprob alignment/masking needed to make off-policy correction robust under multimodal token sanitization and rollout staleness.
Changes:
- Introduces P3O math primitives (ESS, adaptive cap, behavior-KL proxy) plus Megatron loss dispatch + metrics for
--advantage-estimator p3o. - Adds a replayable optimizer-step ESS pre-pass (iterator position + RNG preservation) and rollout-policy snapshot/age observability for periodic-sync mismatch scenarios.
- Extends rollout payload handling with a behavior logprob pairing mask (esp. for multimodal token replacement) and adds extensive unit/distributed tests + docs/recipes.
Reviewed changes
Copilot reviewed 60 out of 60 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/utils/training/test_p3o_replay.py | Tests replay guards (iterator offsets + RNG restoration) for step-scoped ESS pre-pass. |
| tests/utils/test_rollout_logprob_mask.py | Tests propagation and loss-mask intersection logic for rollout behavior-logprob pairing masks. |
| tests/utils/test_p3o_registry.py | Validates P3O registry wiring, CLI exposure, and reward normalization parity rules. |
| tests/utils/test_p3o_arguments.py | Tests P3O argument validation/gates (ESS scope, KL mode, incompatibilities). |
| tests/utils/test_multimodal_rollout_stats.py | Verifies rollout summary records include response token IDs + behavior logprob/mask fields. |
| tests/utils/test_arguments_opd_teacher_colocate.py | Ensures P3O and OPD are rejected as mutually exclusive in args validation. |
| tests/examples/algorithms/p3o/test_rollout.py | Tests behavior-only temperature override helper for mismatch experiments. |
| tests/engine/rollout/test_sglang_rollout_diagnostics.py | Adds diagnostics tests for multimodal token sanitization pairing-mask behavior. |
| tests/components/test_p3o_advantages.py | Ensures P3O uses GRPO-style advantage path (shape/value parity). |
| tests/backends/megatron/test_rollout_policy_lag.py | Tests rollout-policy snapshot scheduling helpers. |
| tests/backends/megatron/test_p3o_step.py | Unit-tests stats synchronization + forward-kwargs parity for ESS pre-pass. |
| tests/backends/megatron/test_p3o_partition_invariance.py | Validates objective/grad invariance under logical partitioning. |
| tests/backends/megatron/test_p3o_on_policy.py | Confirms P3O degenerates correctly to on-policy policy-gradient behavior. |
| tests/backends/megatron/test_p3o_observability.py | Tests rollout-policy age metrics + AST checks for observability wiring. |
| tests/backends/megatron/test_p3o_model_step.py | Tests exception safety (dynamic CP group restoration) and guard coverage in train step. |
| tests/backends/megatron/test_p3o_loss.py | Tests P3O loss schema/dispatch + token-normalizer correctness. |
| tests/backends/megatron/test_p3o_distributed.py | Real Gloo tests for synchronized failure + stats/objective invariance. |
| tests/backends/megatron/test_p3o_cp_metadata.py | Fail-fast tests for CP metadata length alignment across consumers. |
| tests/backends/megatron/test_data_vpp.py | Adds tests for shared build_rl_forward_kwargs behavior across text/VL paths. |
| tests/backends/megatron/_megatron_stub.py | Adds import-time Megatron stubs to keep CPU CI tests collectible. |
| scripts/models/qwen3-4B.sh | Makes RoPE base configurable via env var for recipe alignment. |
| relax/utils/utils.py | Adds rollout logprob presence/length checks, pairing-mask handling, and P3O reward normalization rules. |
| relax/utils/types.py | Extends Sample with rollout_log_probs_mask to track token/logprob correspondence. |
| relax/utils/training/train_dump_utils.py | Adds response token IDs and behavior logprob/mask fields to rollout summary dumps. |
| relax/utils/training/ppo_utils.py | Defines shared estimator sets (GRPO-style advantage + group reward normalization). |
| relax/utils/training/p3o_utils.py | Implements P3O math: sufficient stats, step context, proxy/proxy_safe KL, token-level terms. |
| relax/utils/training/p3o_replay.py | Adds replay guards for RNG and iterator positions for step-scoped ESS. |
| relax/utils/training/data_fields.py | Adds rollout_log_probs_mask field when --use-rollout-logprobs is enabled. |
| relax/utils/opd/opd_utils.py | Adds explicit P3O/OPD compatibility validation and enforces it in OPD validation. |
| relax/utils/data/processing_utils.py | Adds multimodal token sanitization that also produces a behavior-logprob pairing mask. |
| relax/utils/arguments.py | Adds P3O CLI args and enforces strict validation after effective-value overrides. |
| relax/engine/rollout/sglang_rollout.py | Adds response token/logprob length validation, sanitization pairing mask, and mask accumulation checks. |
| relax/core/registry.py | Registers p3o as an algorithm mapping to GRPO-equivalent service roles. |
| relax/components/advantages.py | Treats P3O as GRPO-style for advantage/return computation (loss differs later). |
| relax/backends/megatron/rollout_policy_lag.py | Implements periodic snapshot scheduling + policy-age metrics for rollout staleness observability. |
| relax/backends/megatron/p3o_step.py | Implements optimizer-step ESS pre-pass, DP×CP reduce + PP broadcast, and step-context publishing. |
| relax/backends/megatron/model.py | Integrates step-scoped ESS pre-pass + dynamic-CP group restoration guard and logs policy-age metrics. |
| relax/backends/megatron/loss.py | Adds P3O loss path, step/micro-batch ESS resolution, and dispatch guard to avoid OPD hybridization. |
| relax/backends/megatron/data.py | Adds shared build_rl_forward_kwargs and makes DataIterator replayable via snapshot/restore. |
| relax/backends/megatron/cp_utils.py | Adds CP metadata length validation and introduces get_cp_local_valid_mask for exact token alignment. |
| relax/backends/megatron/actor.py | Switches to Relax logger, adds periodic rollout-policy snapshot mechanics, and publishes snapshot version for metrics. |
| examples/algorithms/README.md | Documents P3O in the supported algorithms list and describes activation requirements/constraints. |
| examples/algorithms/p3o/run_p3o_temperature_1p2_a100x4.sh | Adds A100×4 P3O launcher for temperature mismatch (T=1.2). |
| examples/algorithms/p3o/run_p3o_temperature_0p6_a100x4.sh | Adds A100×4 P3O launcher for temperature mismatch (T=0.6). |
| examples/algorithms/p3o/run_p3o_smoke.sh | Adds a scenario selector wrapper for one-rollout smoke runs. |
| examples/algorithms/p3o/run_p3o_periodic_sync_interval_3_a100x4.sh | Adds A100×4 P3O launcher for periodic-sync staleness mismatch. |
| examples/algorithms/p3o/run_p3o_on_policy_a100x4.sh | Adds A100×4 P3O on-policy launcher. |
| examples/algorithms/p3o/run_grpo_temperature_1p2_a100x4.sh | Adds paired GRPO launcher for temperature mismatch (T=1.2). |
| examples/algorithms/p3o/run_grpo_temperature_0p6_a100x4.sh | Adds paired GRPO launcher for temperature mismatch (T=0.6). |
| examples/algorithms/p3o/run_grpo_periodic_sync_interval_3_a100x4.sh | Adds paired GRPO launcher for periodic-sync mismatch. |
| examples/algorithms/p3o/run_grpo_on_policy_a100x4.sh | Adds paired GRPO on-policy launcher. |
| examples/algorithms/p3o/rollout.py | Adds behavior-only temperature override wrapper for controlled mismatch experiments. |
| examples/algorithms/p3o/README.md | Adds English recipe documentation and experiment contract details. |
| examples/algorithms/p3o/README_zh.md | Adds Chinese recipe documentation and experiment contract details. |
| examples/algorithms/p3o/init.py | Adds package marker/docstring for P3O recipe helpers. |
| docs/zh/examples/algorithms.md | Documents P3O CLI/behavior and links to recipes (Chinese). |
| docs/en/examples/algorithms.md | Documents P3O CLI/behavior and links to recipes (English). |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+1594
to
+1601
| if getattr(args, "advantage_estimator", None) == "p3o": | ||
| # P3O's optimizer-step objective is normalized by the exact global count | ||
| # used for ESS. The generic helper preserves a historical clamp-to-one | ||
| # for fully masked samples when CP=1, which would create phantom tokens | ||
| # and make the final loss depend on the CP partition. | ||
| num_tokens = get_cp_local_valid_mask(*token_count_args, **token_count_kwargs).sum() | ||
| else: | ||
| num_tokens = get_cp_local_num_tokens(*token_count_args, **token_count_kwargs) |
| @@ -0,0 +1,3 @@ | |||
| # Copyright (c) 2026 Relax Authors. All Rights Reserved. | |||
|
|
|||
| """P3O P3O example helpers.""" | |||
# 🐛 Bug Fix ## Prevent reuse of terminating reward workers - Create anonymous RewardWorker actors owned by each executor - Avoid reacquiring same-named actors during Ray teardown - Update teardown documentation for the private worker lifecycle
Contributor
Summary解决了什么问题:本次更新逐条回应了上一轮 review 提出的 5 个代码风险点与 S2 数值先决,并完成 P0 集群实验(Step-0 + FP32 对照、分布式边界 smoke)。 新增 7 个提交: Changes
Verification
Risk & Rollback
Checklist
|
# 🐛 Bug Fix ## Keep P3O CPU tests importable without Megatron - Scope Megatron, data-loader, and model-registry stubs to CPU-only P3O tests - Preserve synthetic Gloo coverage by resolving bare test roots without Megatron DDP wrappers - Keep fused cross-entropy setup out of the strict partition worker, where it is covered separately --- # 🎨 Style ## Apply required formatter output - Wrap the oracle-vector helper docstring to the configured docformatter width
# 🐛 Bug Fix ## Ship the Step-0 analysis dependency - Add the oracle analyzer imported by the checked-in revalidation script and its tests - Preserve the existing artifact parsing and token-key semantics used by the audit CLI - Keep the CPU CI collection path self-contained outside local ignored files
# 🐛 Bug Fix ## Model the CPU test topology explicitly - Set the context-parallel size to one for the P3O loss schema test - Avoid treating the generic Megatron import stub as a production runtime value
# 🐛 Bug Fix ## Keep P3O step kwargs tests CPU-safe - Provide the no-op post-process context required by the delayed model import - Restore the temporary model module after each test to avoid cache leakage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Changes
relax/utils/training/p3o_utils.py、relax/backends/megatron/loss.py实现归一化 ESS、自适应 cap、P3O policy loss 与指标;relax/backends/megatron/p3o_step.py实现 replayable no-grad ESS pre-pass;actor.py、rollout_policy_lag.py处理 rollout-policy age 与 step context;relax/backends/megatron/data.py::build_rl_forward_kwargs被训练 pass 和 P3O 统计 pass 共用,统一普通 token、unsplit token、THD VL bridge 和 multimodal kwargs 选择;relax/backends/megatron/cp_utils.py明确动态 CP 合并过程中的长度元数据命名;T=0.6/1.2)、periodic-sync 失配及 P3O/GRPO 对照配方,并补齐中英文算法文档和中文配方 README。--advantage-estimator p3o;P3O 要求--use-rollout-logprobs与--calculate-per-token-loss;--p3o-kl-mode的生产 choices 收敛为proxy与proxy_safe;全词表exact仅保留为纯验证辅助函数,不再是 CLI 模式;--p3o-ess-scope支持micro-batch与step;P3O 与--use-opd互斥;Verification
HEAD
3313cf569407ad3f75ec29174e2c0c4814c4386e。可复制命令:
单元/集成/端到端测试结果:第一组
101 passed, 2 warnings;CP 元数据回归24 passed, 2 warnings;git diff --check通过。PP>1 / CP>1 多节点 GPU 集成 smoke、三 seed 正式实验和 FeynRL 端到端对比未在本地运行。性能 before/after(若适用):不适用;本 PR 的目标是算法正确性和实验能力,尚未产生可比较的 A100×4 性能数据。
日志、曲线、profile 链接:无;A100×4 训练曲线、三 seed 聚合、吞吐与峰值显存将在正式验证矩阵完成后补充。
Risk & Rollback
tests/components/test_p3o_advantages.py需要transfer_queue,tests/engine/rollout/test_sglang_rollout_diagnostics.py需要pybase64,tests/utils/test_p3o_registry.py被当前环境的 scikit-learn/NumPy ABI 不匹配阻断;完整pytest tests/未在当前环境通过。pre-commit run --all-files会被既有 symlink/patch 文件的end-of-file-fixer改动中断,相关无关改动已还原。step作用域依赖可重放前向,相关不确定性特性已由参数校验限制。--advantage-estimator grpo即可不启用 P3O;紧急回退可 revert P3O 提交8f4c368,后续可读性提交c007b8e与文档提交3313cf5可独立回退。Checklist