Skip to content

fix(opd): keep tail bin under mask, avoid double-summing low_var_kl, and clip 1D advantages - #827

Open
flyingdoubleG wants to merge 1 commit into
redai-studio:mainfrom
flyingdoubleG:fix/opd-kl-tail-low-var-clip
Open

flyingdoubleG wants to merge 1 commit into
redai-studio:mainfrom
flyingdoubleG:fix/opd-kl-tail-low-var-clip

Conversation

@flyingdoubleG

Copy link
Copy Markdown

What

Fix three bugs in relax/utils/opd/opd_utils.py:

  1. compute_opd_kl drops the tail bin when norm_mode="tail" and mask is provided (union top-K path).
  2. compute_opd_kl_topk sums low_var_kl twice on [R, K] inputs, collapsing the [R] per-token vector to a 0-D scalar.
  3. apply_opd_to_advantages ignores --opd-per-token-clip on the 1D sampled-token / EOPD path.

Why

  1. In compute_opd_kl, _add_tail appends the tail probability bin as column K (making s_t/t_t shape [R, K + 1]). When mask ([R, K]) is passed, slicing result[..., :K_orig] discards column K and silently reduces norm_mode="tail" (the default) to norm_mode="trunc":
    • compute_opd_kl_topk(s, t, kl_type="forward_kl", norm_mode="tail", mask=all_true) disagrees with mask=None.
    • For a masked row with valid log-probs s = [-0.5], t = [-0.7], the true tail-completed forward KL is +0.02466 with student gradient +0.2797, whereas dropping the tail bin returned -0.09932 (negative KL) with student gradient -0.4966 (opposite sign).
  2. compute_opd_kl already reduces 2D [R, K] inputs over dim=-1 for kl_type="low_var_kl" (return per_kl.sum(dim=-1) if per_kl.dim() > 1 else per_kl). compute_opd_kl_topk called .sum(dim=-1) a second time, returning a 0-D scalar instead of [R], which causes torch.cat to raise RuntimeError in compute_policy_opd_loss and broadcasts the sequence sum across every token in apply_opd_to_advantages.
  3. apply_opd_to_advantages applied args.opd_per_token_clip in the is_topk branch but omitted it in the 1D student_sampled / EOPD branch right below it.

How

  • In compute_opd_kl:
    • Extend mask with a True column for the tail bin when norm_mode == "tail" instead of slicing result[..., :K_orig], and zero out inactive entries on s_t/t_t before computing exp and log differences so padded -inf positions stay finite.
    • Guard _norm against all-False masked rows (-inf - (-inf)).
  • In compute_opd_kl_topk: return compute_opd_kl(...) directly for low_var_kl without the redundant .sum(dim=-1).
  • In apply_opd_to_advantages: apply torch.clamp(kl_term, max=float(per_token_clip)) on the 1D sampled-token path as well.
  • Added CPU regression tests in tests/cpu/utils/test_opd_kl.py verifying forward values and student gradients against exact tail-completed distributions, low_var_kl [R] output shape and compute_policy_opd_loss integration, 1D opd_per_token_clip, and all-False masked rows.

Testing

  • Verified the 8 new regression cases fail on main and pass with this fix:

    CUDA_VISIBLE_DEVICES="" pytest tests/cpu/utils/test_opd_kl.py tests/cpu/backends/megatron/test_opd_loss_aggregation.py tests/cpu/utils/test_arguments_opd_teacher_colocate.py -v

    Result: 22 passed.

  • Lint and format checks:

    ruff check relax/utils/opd/opd_utils.py tests/cpu/utils/test_opd_kl.py
    ruff format --check relax/utils/opd/opd_utils.py tests/cpu/utils/test_opd_kl.py

    Result: all checks passed, 2 files already formatted.

  • pre-commit run --all-files passes

  • Tests pass (pytest tests/cpu/utils/test_opd_kl.py tests/cpu/backends/megatron/test_opd_loss_aggregation.py tests/cpu/utils/test_arguments_opd_teacher_colocate.py)

  • New tests added (if applicable)

  • Documentation updated (if applicable)

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

@rai-studio-bot

rai-studio-bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for contributing to Relax, @flyingdoubleG! 感谢你为 Relax 做出贡献!

📚 Contribution guide / 贡献指南

Describe the problem, your changes, and how you validated them. Keep each PR focused and run pre-commit run --all-files before submitting.

请说明问题、改动和验证方式,保持 PR 聚焦,并在提交前运行 pre-commit run --all-files。

English contribution guide · 中文贡献指南

🛠️ CI commands / CI 指令
Command / 指令 Usage / 用途
/rerun Retry failed CI / 重跑失败的 CI
/rerun <target> Rerun a workflow or check / 重跑指定 workflow 或检查
/cancel <workflow> Cancel an entire workflow / 取消整个 workflow
/help Show commands and targets / 查看指令和 target
/review Request a code review / 请求代码 review

Put one command on the first line of a new PR comment. Rerun/cancel require PR authorship or repository write access.

在新 PR 评论的首行写一条指令。PR 作者或有仓库写权限的贡献者可以重跑、取消 CI。

CI usage and targets · CI 用法与 target

🔎 Merge requirements / 合入条件

GitHub:⏳ 合入条件未满足

Requirement / 条件 Status / 状态
审批人数 ⏳ 0/1 · 至少 1 位有仓库 write 或更高权限的人 Approve
团队审批(relax-block-reviewers) ⏳ 0/1 · 可联系:Aurelius84, Yangruipis, RexFlux, yuanlehome, SigureMo, NINGBENZHE, Lemon-412
CI ❌ 未通过

@rai-studio-bot

rai-studio-bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Nyanpasu 审查看板

审查状态: 💬 已完成 · 有补充意见

审查版本: c01c972

目标分支: main

四个定向 CPU 用例在本提交全部通过,其中三个在基线复现了目标缺陷。建议补上 norm 模式部分填充行的梯度回归覆盖。GPU 训练未验证。

审查阶段进度范围与结果
常规审查 ✅ 已完成 已核对 union tail、low_var_kl 逐 token 输出及 sampled-token 裁剪的实际调用路径。
深度审查 ✅ 已完成 已核对部分填充行的梯度复现、共享裁剪路径和测试的独立期望。

CI 异常

检查版本: c01c972 · 已分析

失败检查原因与现状证据建议下一步
Pre-commit Checks `` `docformatter` `` 自动改写了 `` `tests/cpu/utils/test_opd_kl.py` `` 中两条超长 docstring,导致 Pre-commit Checks 失败。 第 2 次运行在 `` `Run prek` `` 步骤报告 `` `files were modified by this hook` ``。日志中的 diff 显示两条 docstring 按 79 列折行。 运行 `` `prek run --all-files` ``,提交生成的格式修改,并检查新提交的 Pre-commit Checks。

审查发现

待处理
编号 严重性 问题状态规则来源
F1 Medium severity 用部分填充行验证 norm 模式的反向传播 🚧 未解决 AGENTS.md · 测试准入与有效性
F2 Low severity [experimental · TST003] 让无填充行也走独立的 tail 参考 🚧 未解决 Relax 测试质量准则 · TQ03
F3 Low severity 去掉正向和反向 KL 的重复 padding 清零
精简建议(非阻塞)
🚧 未解决 —
已解决或已取代
编号 严重性 问题状态规则来源
暂无已解决或已取代的记录。

改进建议(非阻塞)

精简

💡 生产代码 · 1 条建议

正向和反向 KL 的 padding 项在求和前已是精确零,可省去重复遮罩。

范围建议保留的行为与验证依据
compute_opd_kl 的 alpha=0/1 分支 删除
保留运算前的掩码,两个端点直接对逐项 KL 求和。
padding 对 KL 值及输入梯度的贡献为零,tail 项仍有效。
运算前 where 将两个 padding 输入都置零,端点逐项表达式为 exp(0) × (0 − 0),where 也屏蔽这些位置的输入梯度。依据表达式核对,未测 GPU 性能。
Powered by Nyanpasu with gpt-6.2-sol high, please check the suggestions carefully.

@rai-studio-bot rai-studio-bot 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.

审查结论

定向 CPU 对照验证了三项 OPD 修复。建议补上 norm 模式部分填充行的梯度回归覆盖。此次验证未覆盖 GPU 训练。审查看板

Powered by Nyanpasu with gpt-6.2-sol high, please check the suggestions carefully.

def test_opd_kl_masked_all_false_row_stays_finite() -> None:
s = torch.tensor([[-1.0, -2.0], [-1.0, -2.0]], dtype=torch.float32, requires_grad=True)
t = torch.tensor([[-1.2, -1.8], [-1.2, -1.8]], dtype=torch.float32)
mask = torch.tensor([[True, True], [False, False]])

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.

Medium severity P2 · 用部分填充行验证 norm 模式的反向传播

当前两行分别全有效、全遮罩,这个用例在基线 97ccd1d4 上也通过。常规 union 批次会有部分填充行。在 PyTorch 2.11 CPU 上,用 [True, True, False] 的行计算 norm 模式 JSD,基线和本提交的前向值一致,但基线两个有效位置的梯度都是 NaN,本提交梯度有限。

建议把第一行改成两个有效位置加一个 padding,保留第二行的全遮罩断言。这样现有的梯度有限性检查就能捕获真实的归一化回归。测试准则

Powered by Nyanpasu with gpt-6.2-sol high, please check the suggestions carefully.


unmasked = compute_opd_kl_topk(s, t, kl_type=kl_type, jsd_alpha=0.5, norm_mode="tail", mask=None)
masked = compute_opd_kl_topk(s, t, kl_type=kl_type, jsd_alpha=0.5, norm_mode="tail", mask=all_true)
torch.testing.assert_close(masked, unmasked, atol=1e-6, rtol=1e-6)

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.

Low severity P3 · [experimental · TST003] 让无填充行也走独立的 tail 参考

这里的等价性检查能发现 mask 改变结果,但如果实现只在有 padding 的行保留 tail,两边都会漏算 tail,仍会相等。上面的独立参考目前只检查有 padding 的行。

可以保留这里的等价性断言,并将独立参考用例的第一行 mask 改为全 True,第二行继续覆盖 padding。这样两类输入都能直接和 tail 完整分布核对,无需再增加用例。测试质量准则

Powered by Nyanpasu with gpt-6.2-sol high, please check the suggestions carefully.

Comment on lines 1204 to 1213
if jsd_alpha == 0.0:
result = s_t.exp() * (s_t - t_t)
if mask is not None:
result = result[..., :K_orig].masked_fill(~mask, 0.0)
if eff_mask is not None:
result = result.masked_fill(~eff_mask, 0.0)
return result.sum(dim=-1)
if jsd_alpha == 1.0:
result = t_t.exp() * (t_t - s_t)
if mask is not None:
result = result[..., :K_orig].masked_fill(~mask, 0.0)
if eff_mask is not None:
result = result.masked_fill(~eff_mask, 0.0)
return result.sum(dim=-1)

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.

Low severity P3 · 去掉正向和反向 KL 的重复 padding 清零

进入这两个分支前,padding 上的 s_t 和 t_t 都已由 torch.where 置零。两个 KL 端点在这里的 padding 项恒为 exp(0) * (0 - 0) = 0,前面的 where 已挡住这些位置的输入梯度。可以直接求和,省去每个端点的整张量遮罩。中间权重的 JSD 继续显式清零,避免混合概率计算的舍入残差。

Suggested change
if jsd_alpha == 0.0:
result = s_t.exp() * (s_t - t_t)
if mask is not None:
result = result[..., :K_orig].masked_fill(~mask, 0.0)
if eff_mask is not None:
result = result.masked_fill(~eff_mask, 0.0)
return result.sum(dim=-1)
if jsd_alpha == 1.0:
result = t_t.exp() * (t_t - s_t)
if mask is not None:
result = result[..., :K_orig].masked_fill(~mask, 0.0)
if eff_mask is not None:
result = result.masked_fill(~eff_mask, 0.0)
return result.sum(dim=-1)
if jsd_alpha == 0.0:
return (s_t.exp() * (s_t - t_t)).sum(dim=-1)
if jsd_alpha == 1.0:
return (t_t.exp() * (t_t - s_t)).sum(dim=-1)
Powered by Nyanpasu with gpt-6.2-sol high, please check the suggestions carefully.

This branch has not been deployed

No deployments
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