Skip to content

[Feature] Support incremental routed experts for LMDeploy multi-turn rollouts - #2293

Merged
jayhenry merged 5 commits into
InternLM:mainfrom
RunningLeon:feat/incremental-r3-v3-20261110
Nov 25, 2026
Merged

jayhenry merged 5 commits into
InternLM:mainfrom
RunningLeon:feat/incremental-r3-v3-20261110

Conversation

@RunningLeon

@RunningLeon RunningLeon commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

  1. Preserve historical R3 in ordinary multi-turn rollouts (partial=False). Previously, later full R3 responses could overwrite original routes with re-prefill routes, while the agent retained the original rollout logprobs. Preserving history improves route/logprob consistency for training replay.
  2. Reduce repeated R3 transfer. Request only the new suffix through routed_experts_start_len, then reconstruct complete training routes. This transport optimization is separate from the history-preservation fix.

Changes

  • Reuse routes only for an exact retained token prefix; append new routes without overwriting history. Edited/truncated/missing history falls back to full return.
  • Add LMDeploy offset requests and SessionServer trace-offset handling, including streaming, abort/retry, and image-expanded offsets. SGLang remains disabled.
  • Requires matching LMDeploy offset support; release-version constraints are a follow-up. No Store or weight-update changes.

ProduceBatchResult impact: no schema/reward changes; non-partial responses/logprobs remain per-turn, with accumulation owned by the agent.

RoutedExperts impact: retain historical routes, transfer the suffix, and reconstruct full R3 for training.

Test configuration

Test Configuration
KL/history comparison 8 H200; five-main-layer GLM-5.3 validation model; train EP4/SP8; rollout two TP1/DP4/EP4 groups; MoE/KPool FP8, FP32 head, MTP0; prefix cache/Store on, sharing off, partial=False
Data GSM8K-derived long-context input: 261,056 tokens; 4 turns × 256 generated tokens; 3 × 11 simulated tool tokens (loss mask 0); final length 262,113
Run size KL comparison: 2 steps, 16 trajectories, 64 requests per group. Separate transfer comparison: 5 steps, 40 trajectories, 160 requests per group, Store sharing on
GPU integration Full Qwen3-30B-A3B BF16; 1 H200, TP1/EP1; prefix cache on, chunked prefill 512; partial on/off × 3 turns × 2,048 output tokens; plus SessionServer and abort/replay cases

Results

History preservation

Same fixed baseline combination Mean mismatch_k3_kl
Without this PR 3.8011e-4
Diagnostic history retention, still full-wire return 2.6354e-4
This PR (d1770bf7), no diagnostic retention hook 2.5609e-4 (−32.63%)

All 48 native continuation merges passed elementwise history/suffix checks. This supports the history-preservation fix, not a numerical benefit from wire cropping.

Transfer and regression

  • Transfer-only comparison: both modes retained history; returned route-array rows decreased 74.96%. KL remained approximately 2.58e-4. No end-to-end speedup was measured (rollout 26.09 → 26.33 s).
  • CPU: 63 tests / 18 subtests passed; syntax, whitespace and Ruff checks passed.
  • GPU: 6/6 worker, 4/4 SessionServer stream/non-stream, and 2/2 abort/replay cases passed. Warm-cache paired requests produced identical tokens and exact reconstructed R3.

Limits: KL runs used a truncated model, two steps, non-identical sampled tokens and zero reward/advantage/gradient norm—not convergence or nonzero-update validation. Qwen fixed-length tests used ignore_eos=True for route stress; natural-stop output was checked separately. Broad rollout-logic tests were blocked by missing transformers.models.glm5_next; full pre-commit timed out during environment setup. Full CI, image GPU and multi-node coverage remain pending.

@RunningLeon
RunningLeon marked this pull request as ready for review November 11, 2026 10:56
Comment thread xtuner/v1/rl/rollout/lmdeploy.py Outdated
class LMDeployWorker(RolloutWorker):
"""A Ray actor that runs a text generation server using LMDeploy."""

supports_routed_experts_start_len: bool = True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C1(Critical)开关不可信:能力是无条件常量

基类默认 False、这里无条件 True,但 PR 描述写明需要配套的 LMDeploy 版本(release-version constraint 是后续项)。也就是说这个开关目前不代表能力,而运行期所有长度校验都依赖它。

按「开关即契约」,运行期不降级、长度不符直接报错是对的(不需要再加「返回全量就退化成 legacy」的分支,那是过度防御且会掩盖配置错误)。真正要修的是开关本身,一处、启动期:

# lmdeploy.py
def _engine_supports_routed_experts_start_len(gen_config_cls: type = GenerationConfig) -> bool:
    """能力探测而不是版本号猜测:有该字段才说明这个 lmdeploy 构建支持 offset 语义。"""
    return "routed_experts_start_len" in {f.name for f in fields(gen_config_cls)}


class LMDeployWorker(RolloutWorker):
    def __init__(self, ...):
        super().__init__(...)
        self.supports_routed_experts_start_len = _engine_supports_routed_experts_start_len()

在 worker 里探测一次即可同时覆盖两条路径(SessionServerActor 的这个 flag 本来就由 worker 传入)。探测为 False 而配置又要求 R3 多轮时,应在启动期报错/告警。

失败链参考(用于定严重级别):旧引擎忽略该字段 → merge_incremental_routed_experts / PartialRolloutHandler.postprocess 长度校验失败 → _safe_handle_response raise → RolloutController.generate(无 except)→ AgentLoop.generate_group(asyncio.gather 无 return_exceptions)→ produce_batch(task.result() 无 except)→ manager 的 asyncio.gather,整个 produce window 失败。所以要么启动期拦住,要么按 C2 把错误关在样本内。

Comment thread xtuner/v1/rl/rollout/session_server.py Outdated
and all(node.value.expert_key is not None for node in nodes)
):
# Full responses are shifted by one dummy row below; start at prefix_len - 1.
start_len = sum(len(node.value.token_ids) for node in nodes) - 1

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A1(Warning)R3 行布局约定被复制到 7 处

这条 -1 是「n 个前缀 token ⇒ 已持有 n-1 行」的换算(raw[j] 是 0-based 位置 j 的路由),同样的换算还散落在:session_server.py:497-516(expected_len - start_len / route_base / dummy 行)、utils.py:175-176、utils.py:195-196、utils.py:224、worker.py:1053-1056(partial 分支)、worker.py:1338-1340(total_len)。

建议收敛成「1 条规则函数 + 1 个前缀类」,-1 只出现一次:

# utils.py
def routed_expert_row_count(*, token_count: int, delta_tokens: int = 0, completion_tokens: int = 0) -> int:
    """全量 R3 行数 = token 数 - 1(raw[j] 是 0-based 位置 j 的路由)。"""
    return max(token_count + delta_tokens + completion_tokens - 1, 0)


@dataclass
class RetainedRoutedExpertsPrefix:
    """已持有的 R3 前缀;rows 是唯一真源。token_ids 仅 worker 侧可选,用于校验历史未被编辑。"""
    rows: int = 0
    token_ids: list[int] | None = None

    def __post_init__(self) -> None:
        assert self.token_ids is None or len(self.token_ids) == self.rows

    @classmethod
    def from_token_count(cls, token_count: int) -> "RetainedRoutedExpertsPrefix":
        return cls(rows=routed_expert_row_count(token_count=token_count))

    def split(self, raw, *, delta_tokens: int, completion_tokens: int, start_len: int):
        """把引擎返回的 R3 切成 (delta 行, response 行);不做降级。"""
        if start_len and start_len != self.rows:
            raise ValueError(f"start_len={start_len} != retained rows={self.rows}")
        expected = self.rows + delta_tokens + completion_tokens - start_len
        if len(raw) != expected:
            raise ValueError(f"routed_experts length mismatch: got {len(raw)}, expected {expected}")
        rows = np.concatenate([np.zeros((1, *raw.shape[1:]), dtype=raw.dtype), raw], axis=0)
        base = 1 if start_len else self.rows + 1
        delta = rows[base : base + delta_tokens] if delta_tokens else None
        return delta, rows[base + delta_tokens :]

7 处落点:

原位置 改为
本处(请求侧) start_len = RetainedRoutedExpertsPrefix.from_token_count(prefix_len).rows
on_response 切分 prefix.split(raw, delta_tokens=delta_len, completion_tokens=len(output_token_ids), start_len=start_len)
utils.py:175-176 start_len != RetainedRoutedExpertsPrefix.from_token_count(prompt_tokens).rows
utils.py:195-196 total = prefix.rows + completion_tokens;history_rows = prefix.rows
utils.py:224 cur[prefix.rows - start_len:]
worker.py:1053-1056 routed_expert_row_count(token_count=len(prompt_ids) + len(response_ids))
worker.py:1338-1340 routed_expert_row_count(token_count=prompt_tokens, completion_tokens=completion_tokens)

两点边界:routed_expert_row_count 保持模块级函数(total_len 等场景没有「前缀」对象,做成类方法只是拿类当命名空间);Path A 的 non-partial 分支不适用这条规则——那里 start_len = len(retained_prefix),在 agent 追加工具 token 后不等于 prompt_tokens - 1,应继续用它自己的前缀状态(见 A2)。

Comment thread xtuner/v1/rl/rollout/worker.py Outdated
# Image placeholders are compressed on the wire; routes use expanded positions.
prompt_ids = rollout_state.extra_fields.get("train_prompt_ids", rollout_state.prompt_ids)
return len(prompt_ids or []) + len(rollout_state.response_ids) - 1
prefix = rollout_state.extra_fields.get("_r3_retained_prefix_ids")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A2(Warning)前缀生命周期应收进一个值对象(R2/R3),并附分叉消除情况

RolloutWorker 对新特性的接触点:1 个类属性 + _get_routed_experts_start_len 定义 + 2 次调用 + 2 处 extra_fields.pop + 新字段名 _r3_retained_prefix_ids + 2 处 if routed_experts_start_len。字段名和分叉落在既有类里,略超 R1。

建议把状态收进纯数据类(规则允许),RolloutWorker 只保留一个字段 + 3 类具名调用:

# utils.py —— 前缀 = 状态 + 切分;行数规则由 routed_expert_row_count 提供(见 A1)
@dataclass
class RetainedRoutedExpertsPrefix:
    rows: int = 0                       # 已持有行数(唯一真源)
    token_ids: list[int] | None = None  # 可选:worker 侧用于校验历史未被编辑

    def __post_init__(self) -> None:
        assert self.token_ids is None or len(self.token_ids) == self.rows

    @classmethod
    def from_request(cls, tokens, response_ids, *, prompt_tokens: int,
                     has_routes: bool, has_image: bool) -> "RetainedRoutedExpertsPrefix":
        # 图像:占位符在 wire 上压缩、路由按展开位置计,两套长度无法互校 -> 显式关闭增量
        if tokens is None or not has_routes or has_image:
            return cls()
        assert len(tokens) == prompt_tokens, "worker token accounting diverges from engine prompt_tokens"
        rows = routed_expert_row_count(token_count=len(tokens) + len(response_ids))
        return cls(rows=rows, token_ids=(tokens + response_ids)[:rows])

    def offset_for(self, tokens) -> int:
        """历史未被编辑时返回 rows,否则 0。"""
        if self.rows == 0 or tokens is None or tokens[: self.rows] != self.token_ids:
            return 0
        return self.rows

调用点(替换现有的 pop / 重算):

# 1) 发请求前
start_len = self._r3_prefix.offset_for(rollout_state.tokens)
# 2) 收到响应后
self._r3_prefix = RetainedRoutedExpertsPrefix.from_request(
    rollout_state.tokens, response_ids,
    prompt_tokens=meta["prompt_tokens"],
    has_routes=routed_experts is not None,
    has_image="image_data" in rollout_state.extra_fields,
)
# 3) 重试 / ABORTED 重跑 / FAILED 的 finally:失效
self._r3_prefix = RetainedRoutedExpertsPrefix()

A2 附:R3 分叉消除情况(4 → 2)

分叉 处理 结果
on_response 的 route_base = 0 / prefix_len prefix.split() 内部处理 ✅ 消除
on_response 全量模式补 dummy prefix.split() 内部处理 ✅ 消除
_safe_handle_response 的 elif start_len: merge / else: 直接赋值 merge 增加 start_len == 0 直通 ✅ 消除
_safe_handle_response 空 abort 丢弃历史 abort 策略,不属于前缀 ❌ 保留(可删冗余的 Status.ABORTED)

merge 直通(注意条件必须挂在实际发出的 start_len 上,不能用 self.rows——历史被编辑时 offset_for() 返回 0、引擎按全量返回):

async def merge_incremental_routed_experts(history, current, *, start_len: int, total_len: int):
    if start_len == 0:
        # legacy:本轮全量传输,没有增量可拼;旧历史不再复用,顺手释放
        if isinstance(history, RayObjectRef):
            free_object_refs([history])
        return current
    ...

_safe_handle_response 的 non-partial 分支可简化为:

if routed_experts_start_len and not response_ids:
    self._drop_routed_experts(rollout_state, routed_experts)   # 本轮零产出,历史作废
    routed_experts = None
else:
    routed_experts = await merge_incremental_routed_experts(
        rollout_state.routed_experts, routed_experts,
        start_len=routed_experts_start_len,
        total_len=routed_expert_row_count(token_count=meta["prompt_tokens"],
                                          completion_tokens=meta["completion_tokens"]),
    )

顺带:rollout_status == Status.ABORTED 是冗余条件。update_status_from_finish_reason 只返回 COMPLETED/ABORTED/FAILED;COMPLETED 若 empty response_ids 会提前判 FAILED,FAILED 已 early return,所以 not response_ids 已蕴含 ABORTED。

Comment thread xtuner/v1/rl/rollout/worker.py Outdated
routed_experts_start_len=routed_experts_start_len,
)
else:
if routed_experts_start_len and rollout_status == Status.ABORTED and not response_ids:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

B1(Warning)non-partial 后处理应下沉成一步

_safe_handle_response 已近 200 行、多分支 early return;这里又插入了「取 offset → 空 abort 丢弃 → 合并 → 重算标记 → 赋值 5 个字段」。建议让上层只表达意图,细节下沉到私有方法(它能隐藏一条真实规则,值得保留):

if self.enable_partial_rollout:
    rollout_state = await self.partial_rollout_handler.postprocess(...)
else:
    rollout_state = await self._postprocess_full_rollout(
        rollout_state,
        response=response,
        response_ids=response_ids,
        logprobs=logprobs,
        routed_experts=routed_experts,
        finish_reason=finish_reason,
        status=rollout_status,
        meta=response["meta_info"],
        routed_experts_start_len=routed_experts_start_len,
    )
async def _postprocess_full_rollout(
    self, rollout_state: RolloutState, *, response: str, response_ids: list[int],
    logprobs: list[float], routed_experts, finish_reason: str, status: Status,
    meta: dict, routed_experts_start_len: int,
) -> RolloutState:
    """Non-partial postprocess:response 每轮覆盖写,R3 按 retained prefix 增量合并。"""
    if routed_experts_start_len and not response_ids:
        self._drop_routed_experts(rollout_state, routed_experts)   # 本轮零产出,历史作废
        routed_experts = None
    else:
        # start_len == 0 时 merge 直通返回 current(legacy 全量),这里不需要再分叉
        routed_experts = await merge_incremental_routed_experts(
            rollout_state.routed_experts, routed_experts,
            start_len=routed_experts_start_len,
            total_len=routed_expert_row_count(token_count=meta["prompt_tokens"],
                                              completion_tokens=meta["completion_tokens"]),
        )
    self._r3_prefix = RetainedRoutedExpertsPrefix.from_request(
        rollout_state.tokens, response_ids,
        prompt_tokens=meta["prompt_tokens"],
        has_routes=routed_experts is not None,
        has_image="image_data" in rollout_state.extra_fields,
    )
    rollout_state.response = response
    rollout_state.response_ids = response_ids
    rollout_state.logprobs = logprobs
    rollout_state.routed_experts = routed_experts
    rollout_state.finish_reason = finish_reason
    rollout_state.status = status
    return rollout_state

Comment thread xtuner/v1/rl/rollout/session_server.py Resolved
Comment thread xtuner/v1/rl/rollout/worker.py Outdated
free_object_refs([routed_experts])
routed_experts = None
elif routed_experts_start_len:
routed_experts = await merge_incremental_routed_experts(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C2(Warning)「报错」要收敛在样本级,不要让异常穿过三层 gather

这里(以及 partial 侧的长度校验)失败会 raise ValueError → _safe_handle_response 包成 RuntimeError → worker.generate(无 except)→ RolloutController.generate(无 except)→ AgentLoop.generate_group(asyncio.gather 无 return_exceptions)→ produce_batch(task.result() 无 except)→ manager 的 asyncio.gather:一个坏样本打死整个 produce window。

这与仓库既有约定不一致:canonicalize_train_fields(agent_loop.py:341)对单样本异常是「记 error、置 Status.FAILED、继续」,注释写明 "so the producer can discard its group without aborting the produce window"。

建议对齐——仍然是直接报错、仍然不改数据,只是把错误关在样本内:

# worker.py: _safe_handle_response 的 except 分支
except (ValueError, AssertionError) as e:
    self.logger.error(f"Incremental R3 rejected for rollout {uid}: {e}")
    rollout_state.status = Status.FAILED
    rollout_state.error_msg = str(e)
    return rollout_state          # 交给 replay buffer 记账 / 重试 / 过期

Comment thread xtuner/v1/rl/rollout/worker.py Outdated
else:
if routed_experts_start_len and rollout_status == Status.ABORTED and not response_ids:
# Non-partial replay restarts the request; no suffix is required after an empty abort.
if isinstance(routed_experts, ray.ObjectRef):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

W3(Warning)空 abort 分支丢弃历史 ref 但没有 free_object_refs

这里只释放了「本次响应」的 ref,随后 rollout_state.routed_experts = routed_experts(None)会把上一轮保留的历史 ref 静默覆盖。大数组只能等 Ray 引用计数 + GC 回收,与 reset_response / merge_incremental_routed_experts 都显式 free_object_refs 的约定不一致。

建议显式释放(或抽一个 _drop_routed_experts(state, current),让「丢弃历史」这一个动作同时负责两条 ref):

if routed_experts_start_len and not response_ids:
    _free_if_ref(routed_experts)                    # 本次响应
    _free_if_ref(rollout_state.routed_experts)      # 上一轮保留的历史
    routed_experts = None

另外,当前 test_empty_abort_restarts_without_incremental_history 里历史是裸 np.ndarray,所以只断言到「本次响应被释放」;建议把历史也换成 _ObjectRef 并把断言提到 2 次。

Comment thread xtuner/v1/rl/rollout/utils.py Resolved
}
worker_req["input_ids"] = input_ids
# Client-provided crops cannot authorize dropping training history.
worker_req.pop("routed_experts_start_len", None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

W6(Nit)evaluate 路径没有剥离客户端传入的 offset

on_request 在 trace_enabled=False 时提前 return,既不判断开关也不 pop,客户端自己传的 routed_experts_start_len 会被原样转发给 LMDeploy。trace 路径的注释写着「Client-provided crops cannot authorize dropping training history」,但 evaluate 路径没有同样的剥离:虽然 evaluate 不消费 R3,但让客户端能控制引擎的裁剪行为没有意义,旧引擎也可能因未知字段 400。

# evaluate 分支的过滤集合加一项
worker_req = {k: v for k, v in req_body.items()
              if k not in _SESSION_SERVER_ONLY_KEYS | {"routed_experts_start_len"}}

Comment thread xtuner/v1/rl/rollout/utils.py Outdated
routed_experts_start_len: int = 0,
) -> RolloutState:
"""Postprocess a partial rollout using the default semantics."""
if routed_experts_start_len and (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

W7(Nit)这个守卫把两种失败原因混在一句消息里

「历史缺失」与「offset 和引擎 prompt_tokens 对不上」是两类问题,排查时无法区分是 worker 记错账还是引擎上报的 prompt_tokens 有问题。按失败原因拆开:

if routed_experts_start_len:
    if rollout_state.routed_experts is None:
        raise ValueError("Incremental R3 requires a retained history, "
                         "but rollout_state.routed_experts is None")
    if routed_experts_start_len != prompt_tokens - 1:
        raise ValueError(
            "Incremental R3 offset does not match the engine prompt length: "
            f"start_len={routed_experts_start_len}, prompt_tokens={prompt_tokens}"
        )

Comment thread xtuner/v1/rl/rollout/worker.py Outdated
and self.enable_return_routed_experts
and rollout_state.sample_params.return_routed_experts
and rollout_state.sample_params.return_token_ids
and not rollout_state.extra_fields.get("disable_routed_experts", False)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

W8(合并项)过度防御 / 重复校验清单

按「同一判断只定义一次、复合守卫按失败原因拆分、恒真条件删除」逐项过:

# 位置 现状 处理
1 本行 disable_routed_experts 全仓库无写入方(sglang.py:193 也只读),永远不成立 删掉,或补上唯一写入点
2 session_server.py:388 getattr(self, "supports...", False);__init__ 必然赋值,且让使用点在引用检索里隐身 类属性默认值 + 普通属性访问
3 worker.py:1344-1347 一个长度判断同时承担「图像压缩(预期)」与「记账 bug(非预期)」 按 image_data 显式分支,其余 assert
4 utils.py:201-204 / 216-223 同一个长度判断写两遍 合成一处
5 session_server.py:513 assert route_base + delta_len + len(out) == len(raw) 与 expected_len 恒等 删掉
# 第 1 项:删掉这个条件(若要保留单样本开关,就在 agent loop 侧补唯一写入点)
if (
    self.supports_routed_experts_start_len
    and self.enable_return_routed_experts
    and rollout_state.sample_params.return_routed_experts
    and rollout_state.sample_params.return_token_ids
    and rollout_state.routed_experts is not None
):
    ...

# 第 2、5 项:session_server.py
class SessionServer:
    supports_routed_experts_start_len: bool = False          # 替代 getattr,可被 find-references 找到

- assert route_base + delta_len + len(output_token_ids) == len(raw_routed_expert)   # 恒真,删除

# 第 3 项:图像与记账 bug 分开(可收进 A2 的 RetainedRoutedExpertsPrefix.from_request)
if "image_data" in rollout_state.extra_fields:
    self._r3_prefix = RetainedRoutedExpertsPrefix()          # 显式关闭增量
else:
    assert len(rollout_state.tokens) == prompt_tokens, (
        f"worker token accounting diverges from engine prompt_tokens: "
        f"{len(rollout_state.tokens)} vs {prompt_tokens}"
    )
    self._r3_prefix = RetainedRoutedExpertsPrefix.from_request(...)

# 第 4 项:删除 utils.py:201-204,只保留 216-223 那一处即可

Comment thread xtuner/v1/rl/rollout/session_server.py Resolved
Comment thread xtuner/v1/rl/rollout/worker.py Outdated
Comment on lines +1344 to +1347
if routed_experts is not None and rollout_state.tokens is not None:
prefix = (rollout_state.tokens + response_ids)[:-1]
if len(prefix) == response["meta_info"]["prompt_tokens"] + len(response_ids) - 1:
rollout_state.extra_fields["_r3_retained_prefix_ids"] = prefix

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的 len(prefix) == prompt_tokens + len(response_ids) - 1 等价于 len(tokens) == prompt_tokens,但它同时承担了两件事

1. 「图像压缩」具体指什么

VLM 样本在数据侧就有两个 token 口径:

口径 来源 用途
展开(一张图 N 个连续 img_context_token) qwen3_vl_tokenize_fn.py:107 extra_info["train_prompt_ids"] = data["input_ids"] 训练拼 input_ids
压缩(一张图 1 个占位符) 同文件 :17-27 remove_consecutive_img_context_tokens → RolloutState.prompt_ids wire 上的 payload["input_ids"]

图片本体走 extra_fields["image_data"](lmdeploy.py:244-246),引擎按 image_grid_thw 把占位符重新展开成 N 个 visual token 再 forward —— 作者在 worker.py:1054 的注释「Image placeholders are compressed on the wire; routes use expanded positions」就是这个意思。所以有图时 len(tokens)(压缩)< prompt_tokens(展开),差值 = Σ(N_i − 1)。量级示例:448×448、patch14 + merge2 的一张图展开成 256 个 visual token(256:1)。

2. 这一行实际在做的事

  • 无图:两边相等 → 记录可复用前缀,下一轮走增量;
  • 有图:不等 → 不记录 → 下一轮 offset_for() 返回 0,退回全量传输(正确,但没有任何日志);
  • token 记账真出 bug:同样不等 → 同样退回全量、同样没有日志。

后两种情形在这里无法区分,所以建议按原因拆开(W8 第 3 项):

if routed_experts is not None and rollout_state.tokens is not None:
    if "image_data" in rollout_state.extra_fields:
        self._r3_prefix = RetainedRoutedExpertsPrefix()        # 图像:显式关闭增量
    else:
        assert len(rollout_state.tokens) == prompt_tokens, (
            f"worker token accounting diverges from engine prompt_tokens: "
            f"{len(rollout_state.tokens)} vs {prompt_tokens}"
        )
        self._r3_prefix = RetainedRoutedExpertsPrefix.from_request(...)

3. 为什么 non-partial 增量不支持多模(而 partial 支持)

  • R3 的行是展开位置的(一个 visual token 一行),而 _r3_retained_prefix_ids 存的是压缩 token;把压缩长度当 start_len 会让 merge_incremental_routed_experts 的长度校验失配,更糟的是「凑巧相等」时路由整体错位一格、静默污染训练数据。
  • 要支持就得把「前 K 个压缩 token」映射成「前 M 个展开位置」,需要这段前缀涉及的所有图片的 image_grid_thw;而 train_prompt_ids 只描述初始 prompt,不覆盖多轮累加后的 tokens(含工具 token,甚至可能追加新图)。
  • partial 分支能支持,是因为它用 train_prompt_ids(展开)算 offset,并由 PartialRolloutHandler.postprocess 的 start_len == prompt_tokens - 1 兜底(覆盖见 test_offset_uses_expanded_training_prompt)。

结论:这里的退化是有意的,但应该写成显式的 image_data 分支 + 其余情形 assert,否则「图像」和「记账 bug」会永久混在一起。

@jayhenry
jayhenry merged commit 815158f into InternLM:main Nov 25, 2026
7 of 8 checks passed
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