Skip to content

refactor(opd): use native SGLang image processing - #437

Merged
yuanlehome merged 4 commits into
redai-studio:mainfrom
yuanlehome:refactor/native-image-opd-sglang-v0.5.17
Oct 14, 2026
Merged

yuanlehome merged 4 commits into
redai-studio:mainfrom
yuanlehome:refactor/native-image-opd-sglang-v0.5.17

Conversation

@yuanlehome

@yuanlehome yuanlehome commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What

将图像 OPD / OPSD / MOPD 从 Relax 私有预展开协议迁移到 SGLang v0.5.17 原生图片处理,保留学生实际采样的 response token IDs,并校验教师、学生的 logprob 和 top-k 位置对齐。

删除 opd_preexpanded_raw、RELAX_OPD_PREEXPANDED_PATCH 和对应 runtime monkey patch;同步 Docker、现有训练 recipes、中英文文档及回归测试。

Why

OPD 需要教师对学生实际采样的 token 序列打分。采样 IDs 经 decode / re-tokenize 后可能发生合并或改变,导致 response 长度和打分位置错位。旧实现通过私有图片协议绕过重分词,同时自行维护图像展开、offset 和 M-RoPE,增加了 SGLang 升级成本。

本次使用 v0.5.17 原生处理能力承担图片展开,并在 Relax 侧显式验证 token 与打分契约。

How

  • 请求发送未展开的 prompt IDs、原样 response IDs 和标准图片数据;使用客户端 processor 计算展开长度,并核对服务端返回的完整 prompt_token_ids。
  • OPSD 只重新处理教师 prompt,再拼接原始 response IDs;教师和学生交叉 prefill 分别使用各自的图片。
  • 严格检查 sampled logprob 行数、top-k 形状及 query IDs;图像请求失败或对齐校验失败时抛错。纯文本 OPD 保留原来的部分失败处理策略。
  • 将独立逐位置 top-k 补丁适配到 v0.5.17,覆盖每请求 K、K=1、混合请求和分块处理,并接入两套训练 Dockerfile。
  • 图片编码缓存只保存已完成的结果,避免异步 Future 进入 processor 的 deepcopy / 序列化路径。

**兼容性变化:**该 OPD 路径要求教师与学生使用兼容的 tokenizer、图片 processor 和缩放配置。音频/视频 OPD、按文本恢复 token 的 RadixTreeMiddleware、图像请求的 response EOS ID 替换会明确报错;正常图片输入、EOS 停止和 SGLang 自身的 Radix/KV cache 可用。普通 RL 的音视频处理路径保留。

Testing

本轮 review 修复验证基于 403a22b,环境为 SGLang v0.5.17 / H20:

  • 185 项 OPD、请求校验、分块、教师编排和模型加载回归通过。

  • Qwen3.5-4B 实际 GPU HTTP 回归 11 项通过,覆盖原生图像 rollout / prefill、不同请求 K、混合请求、异常请求,以及 512-token prefill / 128-row logits 分块。

  • 分别移除学生、教师 prefill 调用的期望 query IDs 后,对应的新测试均失败,确认能捕获接线丢失。

  • 保留 scheduler flat top-k 分支,并增加无数据丢失回归;直接删除该分支会丢失 flat 模式的输入 top-k 数据。

  • 本轮未重跑多节点训练集成。

  • pre-commit run --all-files passes

  • Tests pass (pytest tests/) — 完整套件等待当前提交的 PR CI;上述定向回归已通过。

  • 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

Screenshots / Logs

OPD / SGLang regression tests: 71 passed
Related teacher / engine / argument regressions: 114 passed
Native image GPU checks: 11 passed
pre-commit --all-files: passed

Replace the private preexpanded image protocol and runtime monkey patch
with SGLang v0.5.17 native image processing. Preserve sampled response
IDs and validate full expanded prompts, logprob positions and top-k
query IDs before consuming image OPD results.

Adapt the independent per-position top-k patch to v0.5.17, keep teacher
and student images separate in cross-prefills, and make image encoding
caches safe for concurrent processor calls. Update Docker integration,
recipes, bilingual documentation and regression coverage.

Limit this path to compatible image tokenizers/processors. Reject audio,
video, text-reconstructed image routing and response EOS remapping while
preserving the existing text OPD partial-failure behavior.

Validation: 203 CPU tests; 11 GPU tests each through a direct endpoint
and router; two-step MOPD training and checkpoint save; 48 cold-cache
legacy/native pairs with zero logprob difference. Single-concurrency
request latency increases by at most 1.1% in the measured cases.

Warm-cache and independent HF numerical differences remain unresolved.
Multi-node, long-run and checkpoint-reload scenarios were not tested.
@yuanlehome
yuanlehome requested review from a team and a balanced review from Copilot October 13, 2026 12:32
@rai-studio-bot

rai-studio-bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for contributing to Relax, @yuanlehome! 感谢你为 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, SigureMo, NINGBENZHE
CI ✅ 已通过

@rai-studio-bot

rai-studio-bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Nyanpasu 审查看板

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

审查版本: 403a22b

目标分支: main

最终结论已发布(COMMENT,提交 40e315e);其后作者将 main 合入分支(a8b7fed9,diff 与已评审内容一致、冲突解决安全),并在 403a22b 落实评审发现:F1 失效 RELAX_OPD_TOKEN_IDS_LOGPROB_K 链路已全量删除(全树零残留);F3 新增 CPU 回归钉住跨 topk query 顺序校验接线,student/teacher 两侧断线变异本地复验均如期失败(此前该类变异在全部用例中存活);F4 补 patch 侧请求校验与 generate() 原生图像块 CPU 覆盖(patch 侧套件需含 patch 镜像,由 CI unittest.yml 覆盖)。F2 由作者裁决保留:删除会使 flat 模式请求丢失输入 top-k 数据(经 patch 结构核实成立:b64 压缩在 FORCE_LOGPROBS 下无条件运行、按 flat 数据存在性分支),并新增无数据丢失回归,P3 建议按有理由保留撤回。作者 PR 描述记录 H20 修复验证(185 项回归 + 11 项 GPU HTTP 用例,作者运行);完整套件与新头 CI 尚未上报。30 个变更文件在新 inventory(eeaa3936)下重新接收。

审查阶段进度范围与结果
常规审查 ✅ 已完成 已核对全部 29 个文件的 diff 并追踪客户端/patch/测试契约;无已确认的正确性缺陷;2 个简化候选待子任务核实;Copilot 提出的 2 条线程经核实均为 merge-base 已有行为(teacher video/audio key 未接线、编码缓存非 single-flight),非本 PR 引入。
深度审查 ✅ 已完成 两个子任务完成。测试审计:test_opd_native_multimodal 与 test_opd_per_position 经定向变异为 STRONG(MUT-A/B、MUT-1/2 均被精确捕获;patch 测试在 stock sglang 6/6 失败、热应用 patch 后 6/6 通过),GPU opt-in adequate(同 forward oracle、投毒检查、5 组合,仅显式 env 下运行);test_teacher_manager 改进有效。简化核实:S1(RELAX_OPD_TOKEN_IDS_LOGPROB_K 链路死代码)与 S2b(patch scheduler_flat 分支不可达且唯一可达场景有害)确认,S2a(strict_topk _shape 分支)判定保留(前向兼容解码器)。新增核实 2 项测试缺口。

审查发现

待处理
编号 严重性 问题状态规则来源
暂无待处理的记录。
已解决或已取代
编号 严重性 问题状态规则来源
F1 Low severity 清理失效的 RELAX_OPD_TOKEN_IDS_LOGPROB_K 环境变量链路
精简建议(非阻塞)
✅ 已解决 —
F2 Low severity 删除 patch 中不可达的 input_top_logprobs_scheduler_flat 分支
精简建议(非阻塞)
✅ 已解决 —
F3 Medium severity 补 CPU 回归钉住跨 topk query 顺序校验接线 ✅ 已解决 —
F4 Low severity 为 patch 侧请求校验与 generate() 原生图像块补 CPU 覆盖 ✅ 已解决 —
提交范围 · 接收 30 · 建议移出 0 · 待确认 0

接收 30 个文件 · 建议移出 0 个文件 · 待确认 0 个文件。移出与待确认部分暂停深审,不代表审查通过。

文件结论仓库维护必要性依据替代去向或方案
relax/backends/sglang/sglang_engine.py
relax/distributed/ray/rollout.py
relax/distributed/ray/teacher_manager.py
relax/engine/rollout/on_policy_distillation.py
relax/engine/rollout/sglang_rollout.py
relax/utils/env.py
relax/utils/opd/opd_main_worker.py
relax/utils/opd/opd_multimodal.py
relax/utils/opd/opd_opsd_worker.py
relax/utils/opd/opd_sglang_patch.py
relax/utils/opd/opd_utils.py
relax/utils/types.py
接收 OPD/OPSD/MOPD 图像路径的核心实现:删除运行时 monkey patch 与客户端预展开编码,改为 SGLang v0.5.17 原生图像处理,并新增展开/折叠坐标与 query ID 校验。生产调用链完整(sglang_rollout.generate → OpdManager.prefill → teacher/student prefill),删除的 opd_sglang_patch.py 与 opd_utils 编码助手无残留引用。 PR 描述 What/How:迁移到 SGLang v0.5.17 原生图片处理,保留学生采样的 response token IDs 并校验教师/学生 logprob 与 top-k 位置对齐;relax/engine/rollout/sglang_rollout.py:392-507、relax/utils/opd/opd_multimodal.py 为新增调用方。 保留 monkey patch 可少改引擎环境,但维护一份 229 行的私有 SGLang 内部复制更脆弱;原生路径+显式校验是更小的长期机制,替代方案不成立。
docker/Dockerfile
docker/Dockerfile.cu13
docker/patch/latest/sglang_per_pos_topk.patch
接收 独立逐位置 top-K patch 适配 v0.5.17(nested per-position 查询、custom_params 携带 K、scheduler 分块切片),跨模型查询(student_topk/union/teacher_topk-adv)必需;两个训练镜像通过 git apply --check 构建期强校验。 PR 描述 How:将独立逐位置 top-k 补丁适配到 v0.5.17,覆盖每请求 K、K=1、混合请求和分块处理,并接入两套训练 Dockerfile;docs/examples 明确 stock SGLang 每位置查询同一组 IDs,跨模型查询需要该 patch;tests/backends/sglang/test_opd_per_position.py 直接针对该 patch 行为。 不 patch 而要求上游 SGLang 支持逐位置查询会阻塞功能;作为外部 artifact 分发会破坏镜像可复现构建,故在仓库内维护并纳入镜像构建。
tests/engine/rollout/test_opd_native_multimodal.py
tests/backends/sglang/test_opd_per_position.py
tests/backends/sglang/test_native_image_opd_gpu.py
tests/distributed/ray/test_teacher_manager.py
tests/test_s3_model_loader.py
tests/backends/sglang/test_opd_request_validation.py
接收 三套互补回归:CPU 层验证折叠/展开坐标、query 顺序、部分失败与缓存可序列化;patch 层验证逐位置 gather、分块续算与 tokenizer_manager 请求校验(K 正整数、prefill-only、按展开 prompt 长度定宽、词表/类型边界、分块切片,经 importorskip 在含 patch 的 CI 镜像内运行);GPU 层为显式 opt-in 的端到端 HTTP 契约检查(含 router)。另两处为被删环境变量的既有测试同步。 PR 描述 What:同步回归测试;Testing 小节:验证基于提交 be50b3f(其后的 40e315e 为测试导入守卫调整);tests/engine/rollout/test_opd_native_multimodal.py:233-257 覆盖全部四种线格式。 仅保留 GPU 测试无法在 CI 常规运行;仅保留 CPU 测试无法发现 patch 与客户端契约漂移,三层各自保护不同边界。
docs/en/examples/on-policy-distillation.md
docs/zh/examples/on-policy-distillation.md
examples/on_policy_distillation/README.md
examples/on_policy_distillation/mopd/run-mopd-qwen3-vl-2b-8xgpu-colocate.sh
examples/on_policy_distillation/mopd/run-mopd-qwen35-35ba3b-16xgpu-colocate.sh
examples/on_policy_distillation/mopd/run-mopd-qwen35-9b-8xgpu-colocate.sh
examples/on_policy_distillation/vision_opd/run-opd-qwen3.5_35ba3b-122ba10b-128xgpu-colocate.sh
examples/on_policy_distillation/vision_opd/run-vision-opd-qwen3.5_9b-35ba3b-8xgpu-2teacher-colocate.sh
examples/on_policy_distillation/vision_opd/run-vision-opd-qwen3.5_9b-35ba3b-8xgpu-colocate.sh
接收 用户可见契约变更:环境变量 RELAX_OPD_PREEXPANDED_PATCH 删除、SGLANG_MM_AVOID_RETOKENIZE 替代、原生图像约束(仅图片、需兼容 processor、不支持 RadixTreeMiddleware/EOS 重映射)。文档与 6 个启动脚本必须同步,否则示例直接失败。 PR 描述 What:同步 Docker、现有训练 recipes、中英文文档及回归测试;兼容性小节列明新报错面;被删环境变量在全部示例脚本中引用,需同步替换。 不为文档/示例改动会让现有用户脚本设置已失效的变量;无更小的替代可同时满足正确性与可用性。
精简审查与验证依据
审查范围进度结论
生产代码 ✅ 已完成 对新增/重写的 OPD 客户端与 docker patch 机制完成必要性审计:3 项裁决(2 remove、1 retain),证据含全仓 grep、git 历史与本机 sglang 0.5.17 源码对照。
测试 ✅ 已完成 对三套新测试族与测试基建完成必要性审计:2 项 retain,均以子任务定向变异实验与本机 stock/patch sglang 双向运行为证据。

生产代码的必要性与替代方案

范围必须保留的契约更简单的方案结论依据与限制
RELAX_OPD_TOKEN_IDS_LOGPROB_K 环境变量链路(sglang_engine.py:632-640 写入+日志、teacher_manager.py:41 转发、env.py:204 声明及 61/112 处引用、test_s3_model_loader.py:114 stub) 旧 patch(dce533b4 行 87)经该环境变量读取逐位置 K(动机注释:Rust router 剥离 payload 字段);本 PR 重写 patch 后 K 改经 sampling_params.custom_params 逐请求携带并在 tokenizer_manager 校验,新 patch 唯一读取的环境变量是 RELAX_FORCE_LOGPROBS_BASE64(仍存活) 删除 4 处残留(写入与转发、声明与文档引用、测试 stub),日志行改为直接打印 args.opd_log_prob_top_k 删除 子任务全仓 grep(relax/、docker/、scripts/、docs/、examples/、tests/ 与本机 /sgl-workspace/sglang)无任何读者;git 历史证明旧 patch 是唯一读者且已被本 PR 替换;该变量从未写入用户文档,残留导出仅触发 validate_env 告警(RELAX_STRICT_ENV=1 下才报错),删除无功能损失。注意:sglang_engine 的相关行不在本次 diff 内,需随下次触及时清理。
strict_topk 的 _shape/_null_prefix/_val_flat 解码分支(opd_main_worker.py:135-149) 对应 sglang v0.5.17 原生 return_flat_raw_top_logprobs 线格式;relax 从不设置该请求旗标(io_struct.py:219 默认 False,全仓 0 命中),生产解码实际走 _val_b64 分支 删除该分支,仅保留 b64 与 legacy 解码 保留 生产不可达已核实,但它是被单元测试覆盖(构造合成 meta)的前向兼容解码器:sglang v0.5.17 原生支持该展平格式(调度端展平避免逐位置 Python 列表),日后启用是合理的性能路径;分支含严格校验(shape/dtype/null-prefix/query 等值),保留成本约 15 行,删除会损失现成解码器。
patch 的 input_top_logprobs_scheduler_flat 发射分支(docker/patch/latest/sglang_per_pos_topk.patch 行 176-181) 仅当请求带 return_flat_raw_top_logprobs 且引擎进程设 RELAX_FORCE_LOGPROBS_BASE64=1 时可达;该分支置于 add_logprob_to_meta_info 顶部,会抢先于 sglang 原生 flat 字段构建、改发 relax b64 格式 从 patch 中删除该分支 保留 relax 构造的请求从不携带该旗标(全仓 0 命中),原判不可达且唯一可达场景有害、无单元测试。作者于 PR 描述裁决保留:删除该分支会使 flat 模式请求落入缺失的 nested 路径、丢失输入 top-k 数据;经 patch 结构核实成立(b64 压缩在 RELAX_FORCE_LOGPROBS_BASE64 下无条件运行、按 flat 数据存在性分支),并新增无数据丢失回归 test_compact_logprobs_preserve_scheduler_flat_topk。P3 非阻塞建议按有理由保留撤回;该分支实际服务外部 flat 客户端,relax 自身不用。

测试的必要性与替代方案

范围必须保留的契约更简单的方案结论依据与限制
三套互补测试族(CPU 406 行 / patch 60 行 / GPU opt-in 227 行) CPU 保护折叠/展开坐标、query 顺序与部分失败语义;patch 层保护逐位置 gather 与分块续算;GPU opt-in 保护真实端到端契约(含 router) 合并或删减某一层 保留 测试审计子任务定向变异验证:CPU 层 MUT-A(掩盖失败)/MUT-B(弱化 retokenization 校验)、patch 层 MUT-1(分块续算偏移)/MUT-2(末行哑查询)均被精确捕获;patch 测试在本机 stock sglang 6/6 失败、热应用 docker patch 后 6/6 通过,证明 importorskip 不会掩盖 patch 缺失(patch 缺失时表现为失败而非静默跳过);CI unittest.yml 哈希键含 docker/patch/**,patch 变更即重建镜像。
test_opd_native_multimodal 的 sys.modules stub fixture 与 monkeypatch(GenerateState/_post_logprob/_assemble_transfer) 在 CPU 层隔离推理栈依赖,专验客户端校验与装配逻辑 以真实 sglang_rollout 模块替换 stub 保留 集成面由 GPU opt-in 测试与安装推理栈的 CI(unittest.yml)覆盖;head 40e315e 已将两个直接导入 sglang_rollout 的测试改为 pytest.importorskip(..., exc_type=ModuleNotFoundError),无推理栈时显式跳过而非失败,与既有约定一致。
Powered by Nyanpasu with glm-5.3-flash max, please check the suggestions carefully.

Copilot AI 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.

🟡 Changes recommended

Teacher audio/video options remain silently ignored, and concurrent prefills duplicate image encoding work.

2 open findings
What changed in this PR

Refactors multimodal OPD to use native SGLang v0.5.17 image processing with stricter token/logprob validation.

Changes:

  • Replaces the pre-expanded image protocol with native image requests.
  • Adds per-position top-k support and regression coverage.
  • Updates Docker images, recipes, and bilingual documentation.
File Description
tests/​test_s3_model_loader.py Removes obsolete environment stub.
tests/​engine/​rollout/​test_opd_native_multimodal.py Tests native multimodal OPD behavior.
tests/​distributed/​ray/​test_teacher_manager.py Tests native SGLang environment setup.
tests/​backends/​sglang/​test_opd_per_position.py Tests per-position logprob gathering.
tests/​backends/​sglang/​test_native_image_opd_gpu.py Adds opt-in GPU endpoint tests.
relax/​utils/​types.py Tracks collapsed teacher tokens.
relax/​utils/​opd/​opd_utils.py Removes pre-expanded image helpers.
relax/​utils/​opd/​opd_sglang_patch.py Removes the runtime monkey patch.
relax/​utils/​opd/​opd_opsd_worker.py Builds native teacher inputs.
relax/​utils/​opd/​opd_multimodal.py Adds image validation and encoding.
relax/​utils/​opd/​opd_main_worker.py Strengthens logprob response validation.
relax/​utils/​env.py Removes the obsolete patch flag.
relax/​engine/​rollout/​sglang_rollout.py Validates native image rollouts.
relax/​engine/​rollout/​on_policy_distillation.py Integrates native image prefills.
relax/​distributed/​ray/​teacher_manager.py Configures managed teachers.
relax/​distributed/​ray/​rollout.py Configures student engines.
relax/​backends/​sglang/​sglang_engine.py Removes runtime patch installation.
examples/​on_policy_distillation/​vision_opd/​run-vision-opd-qwen3.5_9b-35ba3b-8xgpu-colocate.sh Updates image-processing environment.
examples/​on_policy_distillation/​vision_opd/​run-vision-opd-qwen3.5_9b-35ba3b-8xgpu-2teacher-colocate.sh Updates image-processing environment.
examples/​on_policy_distillation/​vision_opd/​run-opd-qwen3.5_35ba3b-122ba10b-128xgpu-colocate.sh Updates image-processing environment.
examples/​on_policy_distillation/​README.md Documents native image OPD.
examples/​on_policy_distillation/​mopd/​run-mopd-qwen35-9b-8xgpu-colocate.sh Updates propagated environment.
examples/​on_policy_distillation/​mopd/​run-mopd-qwen35-35ba3b-16xgpu-colocate.sh Updates propagated environment.
examples/​on_policy_distillation/​mopd/​run-mopd-qwen3-vl-2b-8xgpu-colocate.sh Updates propagated environment.
docs/​zh/​examples/​on-policy-distillation.md Documents native image requests in Chinese.
docs/​en/​examples/​on-policy-distillation.md Documents native image requests in English.
docker/​patch/​latest/​sglang_per_pos_topk.patch Adapts per-position top-k for v0.5.17.
docker/​Dockerfile.cu13 Applies the top-k patch.
docker/​Dockerfile Applies the top-k patch.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +13 to +14
if media.get("videos") or media.get("audio"):
raise ValueError("Native SGLang OPD supports images only; audio/video inputs are unsupported.")

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.

核实结论:所描述的绕过路径不成立,且相关接线在合并基线前就已如此,非本 PR 引入。

  • --opd-teacher-video-key / --opd-teacher-audio-key 在合并基线 dce533b 即已存在(relax/utils/opd/opd_utils.py:706/712),本 PR 未改动其定义。
  • relax/engine/rollout/data_source.py:65-68 只把 --opd-teacher-image-key 组装进 teacher_multimodal_keys,video/audio key 没有任何消费方——该行为在 dce533b 与当前 head 完全一致(同文件同位置)。
  • 因此 sample.teacher_multimodal_inputs 在构造上只能携带 images,image_inputs() 的音频/视频拒绝覆盖了可达输入面;新守卫没有漏掉本可进入 teacher 侧的路径。

未接线的 video/audio 旗标本身属于既有问题(在未改动的 data_source.py 一侧),适合另开 issue 清理,不应作为本 PR 的缺陷。

Comment on lines +80 to +85
cached = multimodal_inputs.get(key)
if cached is None:
from relax.utils.data.processing_utils import async_encode_image_for_rollout_engine

cached = await asyncio.gather(*(async_encode_image_for_rollout_engine(img) for img in images))
multimodal_inputs[key] = cached

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.

核实结论:行为属实但无正确性影响,且与合并基线行为一致,属作者已文档化的取舍。

  • 合并基线的 relax/utils/opd/opd_utils.py:931-945(_encode_images_b64)就是同样的 check-then-encode 模式(先查缓存、await 编码、再写回),本 PR 未引入新的并发窗口。
  • 影响面有界:重复编码只发生在同一次 prefill 的 asyncio.gather 内、共享同一 media dict 的样本之间,结果是重复的 base64 编码(浪费 CPU/内存),两次写入内容相同,无数据竞争(asyncio 协作式调度,无中断写)。
  • 代码注释(opd_multimodal.py:77-78)说明了为何只缓存已完成字符串:样本可能在编码期间被复制或 pickle 传输,Future 不可序列化。改用 single-flight Future 会破坏该约束;要消除重复需引入进程级按 dict 键控的锁,收益有限。

不构成本 PR 的缺陷;如需优化建议另立 issue。

Use test-local pytest.importorskip for the two regressions that import
the SGLang rollout module. CPU-only CI skips their four parametrized cases
when the inference stack is unavailable and keeps running the other OPD
tests. Full inference environments continue to execute the real code.

Validation: 43 related CPU tests pass and four inference cases skip
without SGLang installed;
pre-commit run --all-files passes.

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

审查结论:无阻塞问题,4 条非阻塞建议

已核对全部 29 个变更文件(12 个 relax 生产文件、3 个 docker/patch 文件、5 个测试文件、9 个文档/示例)。客户端与 SGLang v0.5.17 的图像/打分契约——折叠/展开 prompt 坐标、R+1 input logprobs、(R+1)*K 逐位置查询校验、prompt_token_ids/output_ids 响应字段、部分失败升级语义——已对照本机 sglang 0.5.17 源码逐项核实,未发现正确性缺陷。作者声明的 GPU/router 验证基于提交 be50b3f,其后唯一新增提交 40e315e 仅调整 2 行测试导入守卫(生产代码逐字节不变),当前 CI 全绿。深度阶段的定向变异测试审计与必要性审计结论见看板。

以下 4 条 inline 建议为非阻塞:2 条简化建议(失效的环境变量链路、patch 内不可达分支),2 条测试缺口(跨 topk query 顺序校验接线未被测试钉住、patch 侧校验与 generate() 原生图像块缺 CPU 覆盖)。

看板(发现索引、证据与范围): #437 (comment)

Powered by Nyanpasu with glm-5.3-flash max, please check the suggestions carefully.

+ self.token_ids_logprobs = []
+ for i, req in enumerate(reqs):
+ ids = req.logprob.token_ids_logprob
+ opd_k = (req.sampling_params.custom_params or {}).get("relax_opd_token_ids_logprob_k")

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 · 清理失效的 RELAX_OPD_TOKEN_IDS_LOGPROB_K 环境变量链路

本 PR 把 patch 的 K 传输改为逐请求 sampling_params.custom_params(本行),而旧 patch(dce533b4 第 87 行)是环境变量 RELAX_OPD_TOKEN_IDS_LOGPROB_K 的唯一读者——重写后整条链路失效但仍残留 4 处:

  • relax/backends/sglang/sglang_engine.py:632-640:写入变量并打印 "(topk enabled)" 日志,误导运维以为 patch 会消费它;
  • relax/distributed/ray/teacher_manager.py:41:向 teacher 引擎转发(默认 "0",与实际 opd_log_prob_top_k 不一致);
  • relax/utils/env.py:204:声明及 61/112 处文档引用;
  • tests/test_s3_model_loader.py:114:stub 属性。

全仓 grep(relax/、docker/、scripts/、docs/、examples/、tests/ 及 sglang 0.5.17 源码)确认无任何读者,该变量也从未写入用户文档。建议删除这 4 处,日志行直接打印 args.opd_log_prob_top_k;新 patch 唯一仍需的环境变量 RELAX_FORCE_LOGPROBS_BASE64(第 146 行)保持不变。残留导出仅触发 validate_env 告警(RELAX_STRICT_ENV=1 下才报错),删除无兼容风险。注:sglang_engine 的相关行不在本次 diff 内,可随下次触碰清理。

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.

已在 403a22b 复核:sglang_engine.py 的写入与日志、teacher_manager.py 的转发、env.py 的声明及两处文档引用、test_s3_model_loader.py 的 stub 均已删除,全树(relax/tests/scripts/examples/docker/docs)grep 零残留;日志改为直接打印 opd_log_prob_top_k。该发现已解决。

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.

done

+ meta_info[f"{prefix}_idx_b64"] = encode(getattr(state, f"{prefix}_idx"), "int32")
+ if top_k > 0:
+ prefix = f"{side}_top_logprobs"
+ if side == "input" and state.input_top_logprobs_scheduler_flat is not None:

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 · 删除 patch 中不可达的 input_top_logprobs_scheduler_flat 分支

该分支(本文件 176-181 行)仅在请求携带 return_flat_raw_top_logprobs 且引擎进程设 RELAX_FORCE_LOGPROBS_BASE64=1 时可达。relax 构造的请求从不携带该旗标(sglang io_struct.py:219 默认 False,全仓 0 处设置),唯一理论触发方是外部直连客户端——而此时该分支位于 add_logprob_to_meta_info 顶部,会抢先于 sglang 原生 flat 字段构建、改发 relax 的 _val_b64 格式,原生 flat 客户端无法解析。也就是说:生产不可达,可达场景有害,且无任何单元测试。建议删除该分支以缩小 patch 面积。(对照保留项:strict_topk 的 _shape 解码分支是测试覆盖的前向兼容解码器,建议保留。)

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.

作者在 PR 描述中裁决保留该分支:直接删除会使 flat 模式(return_flat_raw_top_logprobs)请求落入缺失的 nested 路径、丢失输入 top-k 数据,并新增无数据丢失回归 test_compact_logprobs_preserve_scheduler_flat_topk。核实该论断与 patch 结构一致(b64 压缩在 RELAX_FORCE_LOGPROBS_BASE64 下无条件运行,按 flat 数据存在性分支)。作为 P3 非阻塞建议,按有理由保留撤回该发现。补充一点供后续参考:该分支实际服务外部 flat 客户端(relax 自身不携带该旗标),此类客户端收到的将是 relax b64 格式而非原生 flat 字段,若将来有外部消费者接入,可在 patch 注释中说明该行为。

LogprobResponse({"meta_info": {"input_top_logprobs": rows}}).strict_topk("input_top_logprobs", 2, 2)


def test_strict_cross_topk_rejects_shifted_query_ids():

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 · 补 CPU 回归钉住跨 topk query 顺序校验接线

生产接线存在且正确:_teacher_prefill(on_policy_distillation.py:483-488)与 _student_prefill(:534-536)都把期望 query IDs 传入 strict_topk,服务器返回值若不在查询位置上会拒绝——这是跨模型 OPD 打分正确性的核心保证。但该接线未被任何测试钉住:定向变异实验(去掉 _student_prefill 的 strict_topk 第 4 个参数)在全部 28 个 CPU 测试下存活,因为现有 CPU 桩响应的行序恰好与查询序一致;GPU opt-in 测试是自己手工核对返回值,同样无法发现接线丢失。建议在本文件补充一个 CPU 用例:构造 input_token_ids_logprobs 行序与查询序不一致的响应,断言 _student_prefill/_teacher_prefill 抛 ValueError。

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.

已在 403a22b 复核:test_native_cross_prefill_rejects_reordered_query_ids 覆盖 student/teacher 两侧及行序、列序两种错位,并断言失败后不残留部分赋值。定向变异复验:基线 6 用例通过;断开 _student_prefill 传入 expected_query_ids 后 student 侧 2 用例如期失败,还原后恢复——此前该变异在全部 28 个用例中存活,现被精确捕获,接线已钉住。

+ opd_k = (sampling_params.custom_params or {}).get("relax_opd_token_ids_logprob_k")
+ if opd_k is not None:
+ if isinstance(opd_k, bool) or not isinstance(opd_k, int) or opd_k <= 0:
+ raise ValueError("relax_opd_token_ids_logprob_k must be a positive integer")

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 · 为 patch 侧请求校验与 generate() 原生图像块补 CPU 覆盖

两块新校验逻辑目前只有 opt-in GPU 覆盖或完全没有测试:

  • 本 patch 的 tokenizer_manager 请求校验(本行起的 K 正整数、prefill-only、vocab 边界、(len(input_ids)-logprob_start_len)*K 尺寸)与 schedule_batch 的 prefill 分块切片没有 CPU 测试——GPU 文件只覆盖 400 拒绝分支;CI 镜像虽含 patch(unittest.yml 哈希键含 docker/patch/**),但这两块只在显式设置 env 的 GPU 测试中执行。
  • sglang_rollout.generate 的原生图像块(请求校验、return_prompt_token_ids、响应后 validate_prompt_token_ids、媒体 token 替换拒绝)无任何测试:CPU 唯一的 generate() 调用先命中 RadixTreeMiddleware 拒绝即返回,GPU e2e 手工构造 payload 绕过了它。

建议为 tokenizer_manager 校验补 CPU 用例,并用现有 stub fixture 补一个 generate() 级别用例。

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.

已在 403a22b 复核:test_opd_request_validation.py 覆盖 tokenizer_manager 侧 K 正整数、prefill-only 条件、按展开 prompt 长度定宽、词表/类型边界与 schedule_batch 分块切片;test_opd_native_multimodal.py 新增 generate() 原生图像块用例(折叠 IDs、return_prompt_token_ids、缺失/变更 prompt_ids、采样 media token 拒绝及失败态清理)。说明一点:patch 侧套件依赖含 patch 的镜像,stock sglang 下会失败而非跳过,与既有 test_opd_per_position.py 同一模式,由 unittest.yml 覆盖(新头 CI 结果尚未上报);客户端侧用例本地复验 6 用例通过。

Merge the rollout utility extraction and managed PD changes from main into
the native image OPD branch. Preserve the compute_mopd_metrics compatibility
re-export without restoring the obsolete opd_opsd_worker import.

Validation: all pre-commit hooks pass; targeted regression tests report
160 passed and 49 skipped because inference runtime dependencies are absent.
Multi-node GPU integration tests were not run on this local CPU environment.
@yuanlehome
yuanlehome force-pushed the refactor/native-image-opd-sglang-v0.5.17 branch from a8b7fed to 40e315e Compare October 14, 2026 04:16
Cover query ordering at both cross-top-k prefill callers, native rollout
request and response guards, and SGLang request validation and prefill
chunk slicing. Preserve compact transport of scheduler-side flat top-k
values with a regression test.

Remove the obsolete global top-k environment setting now that each
request carries its own query width.

Validation: pre-commit --all-files; 185 targeted regression tests and 11
native image GPU checks on H20 with Qwen3.5-4B and SGLang v0.5.17.
Removing expected query IDs at either prefill caller fails the new tests.
@yuanlehome
yuanlehome merged commit 108d8c3 into redai-studio:main Oct 14, 2026
22 checks passed
leelingrui added a commit to leelingrui/Relax that referenced this pull request Oct 17, 2026
…rence

Resolve conflicts with upstream redai-studio#433 (managed PD), redai-studio#437 (native image OPD),
redai-studio#439 (rollout utility extraction), redai-studio#361 (multinode scale-out) and the
placement factory relocation, porting their intent onto InferenceManager.

- Managed static PD: start_servers defers the Router until P/D engines are
  ready and seeds it with them; replacements still join after weight sync.
- Recovery broadcasts rank-0 failures before weight sync; pool monitors stop
  within one shared 5s budget; Controller bounds shutdown_all to 35s.
- Teacher engines get SGLANG_MM_AVOID_RETOKENIZE in config_adapters; the
  removed RELAX_OPD_PREEXPANDED_PATCH reference is dropped.
- Drop RolloutManager/TeacherManager-only code and tests; adapt new upstream
  tests to EngineGroupSpec/InferenceModelSpec and the inference manager.
leelingrui added a commit to leelingrui/Relax that referenced this pull request Oct 19, 2026
…rence

Resolve conflicts with upstream redai-studio#433 (managed PD), redai-studio#437 (native image OPD),
redai-studio#439 (rollout utility extraction), redai-studio#361 (multinode scale-out) and the
placement factory relocation, porting their intent onto InferenceManager.

- Managed static PD: start_servers defers the Router until P/D engines are
  ready and seeds it with them; replacements still join after weight sync.
- Recovery broadcasts rank-0 failures before weight sync; pool monitors stop
  within one shared 5s budget; Controller bounds shutdown_all to 35s.
- Teacher engines get SGLANG_MM_AVOID_RETOKENIZE in config_adapters; the
  removed RELAX_OPD_PREEXPANDED_PATCH reference is dropped.
- Drop RolloutManager/TeacherManager-only code and tests; adapt new upstream
  tests to EngineGroupSpec/InferenceModelSpec and the inference manager.
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.

4 participants