Repository navigation
refactor(opd): use native SGLang image processing - #437
yuanlehome merged 4 commits into
Conversation
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.
|
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 请说明问题、改动和验证方式,保持 PR 聚焦,并在提交前运行 🛠️ CI commands / CI 指令
Put one command on the first line of a new PR comment. Rerun/cancel require PR authorship or repository write access. 在新 PR 评论的首行写一条指令。PR 作者或有仓库写权限的贡献者可以重跑、取消 CI。 🔎 Merge requirements / 合入条件GitHub:⏳ 合入条件未满足
|
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)下重新接收。
审查发现待处理
已解决或已取代
提交范围 · 接收 30 · 建议移出 0 · 待确认 0接收 30 个文件 · 建议移出 0 个文件 · 待确认 0 个文件。移出与待确认部分暂停深审,不代表审查通过。
精简审查与验证依据
生产代码的必要性与替代方案
测试的必要性与替代方案
Powered by Nyanpasu with glm-5.3-flash max, please check the suggestions carefully.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
🟡 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.
| if media.get("videos") or media.get("audio"): | ||
| raise ValueError("Native SGLang OPD supports images only; audio/video inputs are unsupported.") |
There was a problem hiding this comment.
核实结论:所描述的绕过路径不成立,且相关接线在合并基线前就已如此,非本 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 的缺陷。
| 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 |
There was a problem hiding this comment.
核实结论:行为属实但无正确性影响,且与合并基线行为一致,属作者已文档化的取舍。
- 合并基线的
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
left a comment
There was a problem hiding this comment.
审查结论:无阻塞问题,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)
| + 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") |
There was a problem hiding this comment.
本 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 内,可随下次触碰清理。
There was a problem hiding this comment.
已在 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。该发现已解决。
| + 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: |
There was a problem hiding this comment.
该分支(本文件 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 解码分支是测试覆盖的前向兼容解码器,建议保留。)
There was a problem hiding this comment.
作者在 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(): |
There was a problem hiding this comment.
生产接线存在且正确:_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。
There was a problem hiding this comment.
已在 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") |
There was a problem hiding this comment.
两块新校验逻辑目前只有 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() 级别用例。
There was a problem hiding this comment.
已在 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.
a8b7fed to
40e315e
Compare
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.
…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.
…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.


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_token_ids。**兼容性变化:**该 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-filespassesTests pass (
pytest tests/) — 完整套件等待当前提交的 PR CI;上述定向回归已通过。New tests added (if applicable)
Documentation updated (if applicable)
Type of Change
Screenshots / Logs