Continuous Token Support for Multi-Turn AgentLoop Rollout
Feature request
Continuous Token Support for Multi-Turn AgentLoop Rollout
This issue tracks a stacked PR series that adds Continuous Token support to verl's multi-turn AgentLoop rollout.
Motivation
Agentic Multi-turn Continuous Token Design Notes
TL;DR
The basic idea of token-in-token-out (TITO) is that the training side should use the token ids that were actually produced and observed on the inference side, instead of retokenizing after the fact. verl already has the most basic token-in-token-out idea today: it preserves the accumulated token ids from previous turns and aligns the loss mask correctly. However, agentic multi-turn rollout involves concatenating tokens across multiple turns. The chat templates of many open-source models are not simply append-only; if incremental token ids are extracted carelessly and boundaries are not merged rigorously, the resulting multi-turn prompt can be wrong. If we only needed to handle a specific model tokenizer, we could ensure correctness with a model-specific method. But we want a design that generalizes across different tokenizers while minimizing model-specific hardcoding. A generalizable multi-turn TITO design has four common pitfalls:
- Multi-turn continuous tokens must not retokenize the current full messages. They must preserve the real token ids accumulated from previous turns.
- Incremental non-assistant token ids must be extracted from an appropriate synthetic context, not by simply encoding incremental messages.
- When incremental ids are merged back into old token ids, some models require explicit boundary handling.
- After constructing the full trajectory, a comparator is needed to check structural errors. Differences between assistant content and the canonical render of the full chat template can be tolerated, but deviations in special-token boundaries cannot. [WIP]
Among these, item 1 is the core TITO invariant and should be fixed at the trajectory/session layer. Items 2 and 3 are model-related implementation details that can be overridden through model-specific strategies. Item 4 is the final structural validation mechanism.
This note discusses the four points above, how they are currently implemented in verl, and how a ContinuousTokenBuilder abstraction can implement correct multi-turn TITO through a "core invariant pipeline + model-specialized methods" design.
1. Issues to Watch For in Multi-turn Continuous Tokens
1. Full messages must not be retokenized
In a multi-turn rollout, the previous turn observed by the model is:
prompt_token_ids + model_output_token_ids
When continuing generation in the next turn, we should directly reuse this real sequence of token ids. If we instead run full_messages through apply_chat_template + encode again, two classes of problems can occur.
- BPE boundary changes. During inference, the model may have generated two tokens in two steps:
output_ids = [A, B]
decode([A, B]) = " international"
But if the string " international" is placed back into a message and re-encoded, BPE may merge it into one token:
encode(" international") = [C]
Then the token sequence on the training side is no longer the real token sequence produced on the inference side.
- Position-dependent rendering in chat templates. Some templates insert or remove tokens depending on whether an assistant message is a historical message, whether it contains
</think>, or whether it appears after the last user message. Rendering full messages again can change prompt tokens that truly existed at inference time.
Counterexample: DeepSeek-R1-Distill-Qwen-1.5B {folded="true"}
The Turn 0 generation prompt for DeepSeek-R1-Distill-Qwen-1.5B is:
<|Assistant|><think>\n
The corresponding token suffix is:
[151645, 151648, 198]
# 151645 = <|Assistant|>
# 151648 = <think>
# 198 = "\n"
The output ids actually generated by the model are:
output_text = "I should add one and one.\n</think>\n1+1 = 2"
output_ids = [40, 1265, 912, 825, 323, 825, 624, 151649, 198, 16, 10, 16, 284, 220, 17]
The real history is:
<|Assistant|><think>
I should add one and one.
</think>
1+1 = 2
If padding is used to apply the chat template again, DeepSeek's historical assistant branch will remove <think>\n because it determines that "000000000000000" does not contain thinking, so its chat template removes the newline in the generation prompt. The padded render becomes:
<|Assistant|>000000000000000<|end▁of▁sentence|><|User|>...
Or, if we restore according to the original output start index, we get something like:
<|Assistant|>00I should add one and one.
</think>
1+1 = 2...
Because the padded sequence is missing the two prompt tokens <think>\n that really existed at inference time, subsequent positions are no longer isomorphic. This is not a BPE issue; it is caused by completed-message templating eating generation-prompt tokens.
Counterexample: GLM4.7 {folded="true"}
GLM4.7's default generation prompt is:
<|assistant|><think>
But if the historical assistant-message branch has no reasoning_content, or if the padding content does not contain </think>, it renders:
<|assistant|></think>{content}
So if an old assistant message is replaced with padding, the marker before the padding span changes from the real runtime value:
<|assistant|><think>
to:
<|assistant|></think>
This token appears before the padding span, so restoring the padding cannot cover it.
Conclusion
We must preserve the real token ids accumulated from previous turns:
accumulated_token_ids = previous_prompt_ids + previous_completion_ids
The next turn may only append new incremental token ids; it must not re-encode the entire full_messages. On this point, verl's current logic is correct: it preserves the old trajectory buffer, and the next turn appends incremental ids to response_ids. For example, after a prefix hit in the gateway, it copies the active buffer and appends incremental ids; see verl/verl/agent/gateway/gateway.py:524-545. The remaining problems are the next two questions: how incremental token ids are extracted, and how they are merged into old token ids.
2. How to obtain incremental token ids
Message-level incrementality is easy to compute:
incremental_messages = new_messages[len(old_messages):]
The hard part is encoding these incremental messages into "clean token ids that should be appended after the old token ids." If we directly do:
encode(apply_chat_template(incremental_messages, add_generation_prompt=True))
many templates will generate an extra system prompt, tool schema, role prelude, and so on. These contents already appeared in the initial prompt or old token ids, and should not be concatenated into the trajectory again.
verl's current approach
verl has already noticed this problem, so _encode_incremental separately encodes incremental messages and then removes self._system_prompt:
ids = apply_chat_template(incremental_messages, add_generation_prompt=True)
return ids[len(self._system_prompt):]
Source locations:
verl/verl/agent/gateway/gateway.py:412-454- The traditional ToolAgentLoop has the same
remove_system_prompt=True; seeverl/verl/experimental/agent_loop/agent_loop.py:243-309
But this method has two problems.
Problem 1: extracting the system prompt length is unreliable
Two bad cases: https://github.com/verl-project/verl/issues/6500 https://github.com/verl-project/verl/issues/6501
verl extracts the system prompt in verl/verl/utils/chat_template.py:13-32:
token1 = apply_chat_template([user_empty], add_generation_prompt=False)
token2 = apply_chat_template([user_empty, user_empty], add_generation_prompt=False)
system_prompt = token1[:-(len(token2) - len(token1))]
This method assumes the second user only appends a fixed-length suffix, so len(token2) - len(token1) is the length of the first user turn.
However, the turn delimiter, EOS, or thinking marker of some tokenizers can change depending on message position. For example, one message may render differently when it is the "last message" versus when it is a "historical message"; in that case, len(token2) - len(token1) is no longer a stable user-turn length. The extracted system_prompt length can therefore be wrong, and the start point of subsequent incremental ids will also be wrong. We therefore lean toward extracting clean incremental tokens by constructing anchor messages. But arbitrary anchor-message construction can trigger problem B.
Problem 2: tool responses usually depend on the preceding assistant tool call
A tool response is not ordinary user text. Many chat templates need to see:
{"role": "assistant", "tool_calls": [...]}
{"role": "tool", "content": "..."}
before they can render the tool-response boundary correctly. Applying the chat template only to a tool message, or only using an anchor system message, can easily fail outright or produce the wrong boundary. For example, some templates decide how to render a tool response based on the preceding assistant tool call. Therefore, anchor messages must also be constructed in a specific way, and different models must be allowed to override this method.
Counterexample 1: MiniMax
Without a dummy assistant, the chat template directly raises an error.
Counterexample 2: Nemotron
Without a dummy assistant, <|im_start|>user is omitted.
Counterexample 3: Llama-3.1-8B-Instruct
If, in order to extract incremental ids for a tool response, we construct only a dummy system:
base_messages = [
{"role": "system", "content": "dummy system"},
]
appended_messages = [
{
"role": "tool",
"tool_call_id": "call12345",
"name": "get_weather",
"content": '{"temperature":"20C"}',
}
]
text_without = tokenizer.apply_chat_template(
base_messages,
tools=tools,
tokenize=False,
add_generation_prompt=False,
)
this tokenizer will directly raise:
TemplateError: Cannot put tools in the first user message when there's no first user message!
The reason is that when this template sees tools, it tries to place the tool schema into the first user message. But the synthetic context contains only system, with no user and no preceding assistant tool call, so this context is illegal for the template. If we construct a dummy assistant:
base_messages = [
{"role": "system", "content": "dummy system"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call12345",
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"city": "SF"},
},
}
],
},
]
full_messages = base_messages + appended_messages
then rendering works normally, and suffix diff can extract a clean tool result:
<|start_header_id|>ipython<|end_header_id|>
"{\"temperature\":\"20C\"}"<|eot_id|>
This example shows that the dummy assistant is not "just any assistant used for padding." Its purpose is to restore the real preceding state of the rollout inside the synthetic context: the assistant has just initiated the corresponding tool call, and now it is the tool response's turn. There is also a small detail here: when constructing the synthetic context for a tool response, do not casually add a dummy user. For example, Qwen3 decides whether to insert or clean up <think>...</think> based on whether the assistant is after the last real user and whether the assistant is the last message. If the base is written as [_DUMMY_SYSTEM, _DUMMY_USER, dummy_assistant], the dummy assistant in text_without may get an empty thinking block inserted because it is after the last user. But after text_with = base + tool_response, the assistant is no longer the last message, so the thinking block is removed, causing text_with.startswith(text_without) to fail. The key design point is: we do not require the chat template of the complete conversation to be append-only. We only require append-only behavior in the synthetic context, so we can stably extract the suffix for the current role.
3. How to correctly merge incremental ids back into accumulated ids
After obtaining incremental token ids, verl's current approach is simply:
accumulated_ids + incremental_ids
This is not rigorous, because a model's stop token and the next-turn boundary in the chat template often do not correspond one-to-one.
Counterexample 1: Qwen3: generation stops at <|im_end|>, while the template needs <|im_end|>\n {folded="true"}
Each message in the Qwen3 chat template usually ends with:
<|im_end|>\n
But during generation, the model stops at:
<|im_end|>
It does not generate the following \n. If the next turn directly appends incremental ids, the newline is missing.
Counterexample 2: GLM4.7: the stop token and the next message BOS are shared
In GLM4.7, <|user|> and <|observation|> can be both an assistant stop token and the start token of the next message. For example, when a tool call succeeds:
runtime prefix ends with: <|observation|>
incremental tool response starts with: <|observation|><tool_response>...
If we concatenate directly:
...<|observation|><|observation|><tool_response>...
we get a duplicated <|observation|>. If the tool call fails, or if no tool path is taken, the model may already have stopped at:
<|observation|>
but the next environment turn appends a user retry:
<|user|>tool call fails, please retry
Direct concatenation becomes:
...<|observation|><|user|>tool call fails...
The semantics are also wrong, because <|observation|> is the stop/boundary generated by the model in expectation of a tool result, but the real next turn is not an observation. Note that experience suggests special-token errors are semantic errors and are more serious than Qwen3's missing newline issue; they may carry a significant risk of training collapse.
Conclusion
Combining the three points above, we need a ContinuousTokenBuilder abstraction:
class ContinuousTokenBuilder:
def encode_environment_delta(...):
...
def merge(prev_messages, next_messages, runtime_token_ids, tools=None):
delta = self.encode_environment_delta(...)
return [*runtime_token_ids, *delta]
Different models can customize incremental extraction and boundary merging by inheriting from ContinuousTokenBuilder and overriding instance methods. For some commonly used models, we can provide correct model-specific continuous token builders for users to use directly.
4. A comparator is needed after trajectory construction
After the full trajectory is assembled, we need to check:
whether non-assistant content is correct
whether special token counts and types are correct
whether message boundaries are correct
But we cannot simply require:
accumulated_ids == encode(apply_chat_template(full_messages))
because the canonical render of the full template may modify historical assistant content. For example, Qwen3 / DeepSeek / GLM may clear thinking from previous turns:
runtime actual:
<think>
previous reasoning
</think>
final answer
canonical full render:
final answer
This difference should be allowed, because TITO's goal is to preserve the real runtime token prefix, not to canonicalize historical assistant messages after the fact. The comparison logic should be:
- First split segments by special tokens.
- If the number of segments or the special/content pattern differs, report
special_token_count. - If special-token types differ, report
special_token_type. - If ordinary content differs, classify it as
assistant_textornon_assistant_textdepending on whether it belongs to an assistant segment.assistant_textis a soft mismatch: assistant mistakes are allowed, and runtime assistant tokens may differ from the canonical template. Hard mismatches are:
special_token_count
special_token_type
non_assistant_text
These indicate that role boundaries, tool responses, user/system/environment content, or other structural elements were broken by TITO concatenation. verl currently does not have such a comparator.
2. Correct Approach and Design
Data structure
# One RolloutTokenState corresponds to one sample trajectory in an agentic rollout.
class RolloutTokenState:
rendered_messages: list[dict]
runtime_token_ids: list[int]
records: list[RequestResponseRecord]
Continuous token builder abstraction
class ContinuousTokenBuilder:
append_only_roles = {"tool"}
def render_chat(self, messages, *, add_generation_prompt, tools=None, tokenize=False):
return tokenizer.apply_chat_template(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
tokenize=tokenize,
**chat_template_kwargs,
)
def encode_render_delta(self, anchor_messages, delta_messages, *, tools=None, add_generation_prompt=False):
before = self.render_chat(anchor_messages, add_generation_prompt=False, tools=tools)
after = self.render_chat(
anchor_messages + delta_messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
)
if not after.startswith(before):
raise ValueError("synthetic context is not append-only for this segment")
return encode(after[len(before):])
def encode_tool_observations(self, tool_messages, tools=None):
assistant_stub = make_tool_call_stub(tool_messages)
return self.encode_render_delta(
[SYNTHETIC_SYSTEM, assistant_stub],
tool_messages,
tools=tools,
)
def encode_plain_turn(self, message, tools=None):
return self.encode_render_delta(
[SYNTHETIC_SYSTEM],
[message],
tools=tools,
)
def encode_environment_delta(self, prev_messages, next_messages, tools=None):
require_message_prefix(prev_messages, next_messages, append_only_roles=self.append_only_roles)
new_tail = next_messages[len(prev_messages):]
pieces = []
for role, segment in group_consecutive_roles(new_tail):
if role == "tool":
pieces.extend(self.encode_tool_observations(segment, tools=tools))
elif role in {"user", "system"}:
pieces.extend(self.encode_plain_turn(segment[0], tools=tools))
pieces.extend(self.encode_render_delta(
next_messages,
[],
tools=tools,
add_generation_prompt=True,
))
return pieces
def merge(self, prev_messages, next_messages, runtime_token_ids, tools=None):
delta = self.encode_environment_delta(prev_messages, next_messages, tools=tools)
return [*runtime_token_ids, *delta]
Model-specific merge
class Qwen3ContinuousTokenBuilder(ContinuousTokenBuilder):
def merge(...):
delta = self.encode_environment_delta(...)
prefix = list(runtime_token_ids)
if prefix and prefix[-1] == im_end_id:
prefix.append(newline_id)
return [*prefix, *delta]
class GLM47ContinuousTokenBuilder(ContinuousTokenBuilder):
def merge(...):
delta = self.encode_environment_delta(...)
prefix = list(runtime_token_ids)
if prefix and prefix[-1] in {user_id, observation_id}:
prefix = prefix[:-1]
return [*prefix, *delta]
Runtime path
def build_prompt_tokens(request_messages, tools):
if state.runtime_token_ids is None:
return continuous_builder.render_chat(
request_messages,
tools=tools,
add_generation_prompt=True,
tokenize=True,
)
return continuous_builder.merge(
prev_messages=state.rendered_messages,
next_messages=request_messages,
runtime_token_ids=state.runtime_token_ids,
tools=tools,
)
def update_after_generation(request_messages, prompt_token_ids, completion_token_ids, assistant_message):
# This stores the real runtime token stream, not the canonical full render.
state.runtime_token_ids = prompt_token_ids + completion_token_ids
state.rendered_messages = request_messages + [assistant_message]
Finalize / debug comparator
def inspect_runtime_render_gap(state):
canonical_ids = continuous_builder.render_chat(
state.rendered_messages,
add_generation_prompt=False,
tokenize=True,
)
return token_sequence_checker.compare(
expected_ids=canonical_ids,
actual_ids=state.runtime_token_ids,
)
The comparator treats only the following categories as hard errors:
special_token_count
special_token_type
non_assistant_text
assistant_text is only recorded as a metric and is not treated as a hard error. The reason is that assistant content comes from the model's real output. It may contain malformed formatting, uncanonicalized thinking, extra natural language, or even text that does not match the template's expectations. TITO should not rewrite it after the fact.
3. Summary of verl's Current Logic
verl currently satisfies "basic token-in-token-out":
- The initial prompt fully applies
apply_chat_template. - Model output token ids are appended directly.
- Incremental token ids from the tool/user environment are masked as 0.
- Later generation uses accumulated token ids.
But it still lacks more robust multi-turn TITO components:
- Its model-specialized logic is implemented through hardcoding such as
if Qwen3, without an abstract design. - Incremental ids are not extracted through dummy-context suffix diff; they are standalone-encoded and then stripped of the system prompt.
- The length inference in
initialize_system_promptis unstable for position-dependent templates. - Tool responses do not construct a dummy assistant/tool_calls context to preserve the shape of tool boundaries.
- After finalization, there is no token sequence comparator to distinguish assistant soft mismatches from real structure/non-assistant hard mismatches.
TL; DR
Token-in-token-out (TITO) 的基本概念是:训练侧应该使用推理侧真实产生和看到的 token ids,而不是事后重新 tokenization。verl 目前已经具备最基础的 token-in-token-out 思路:它会保留上一轮累计的 token ids,并正确对齐loss mask。但在 agentic 多轮 rollout 中,涉及到多轮token的拼接。很多开源模型的 chat template 并不是简单 append-only 的;**如果 incremental token ids 的提取和边界拼接处理不严谨,会拼出错误的多轮 prompt。**如果只应对某个模型的tokenzier,那么其实可以通过特定方式来确保正确性,但我们希望能设计一套方案来泛化到不同的tokenzier上,并且尽量少地去做model-specific hardcode。可泛化的多轮TITO主要有四个容易踩坑的点:
- 多轮 Continuous Token不能重新 retokenize 当前 full messages,必须保留之前轮累计的真实 token ids。
- incremental non-assistant token ids 必须从合适的 synthetic context 中提取,不能简单 encode incremental messages。
- incremental ids 拼回旧 token ids 时,部分模型需要显式的边界处理。
- 构造完整 trajectory 后,需要 comparator 检查结构错误;可以容许 assistant 内容与 full chat template 的 canonical render有偏差,但不可以容许special token边界的偏差。
其中,第 1 点是 TITO 的核心不变量,应该由 trajectory/session 层固定;第 2、3 点是模型相关的实现细节,可以通过模型特化策略重写;第 4 点是最终的结构校验机制。
本文会讨论以上四个点verl目前的实现情况,以及说明如何通过ContinuousTokenBuilder抽象实现“核心不变量pipeline+模型部分特化方法”来实现正确的多轮tito。
一、多轮 Continuous Token要注意的问题
1. 不可以对 full messages 重新 retokenization
多轮 rollout 里,上一轮模型看到的是:
prompt_token_ids + model_output_token_ids
下一轮继续生成时,应该直接复用这串真实 token ids。如果重新把 full_messages 过一遍 apply_chat_template + encode,会有两类问题。
- BPE 边界变化的问题。模型可能在推理时分两步生成了两个 token:
output_ids = [A, B]
decode([A, B]) = " international"
但如果把字符串 " international" 放回 message 里重新 encode,BPE 可能把它 merge 成一个 token:
encode(" international") = [C]
这样训练侧的 token 序列就不是推理侧真实产生的 token 序列。
- chat template 位置相关渲染。某些 template 会根据 assistant message 是否是历史消息、是否包含
</think>、是否处在最后一个 user 之后,来插入或删除 token。重新 render full messages 会把推理时真实存在的 prompt token 改掉。
反例:DeepSeek-R1-Distill-Qwen-1.5B {folded="true"}
DeepSeek-R1-Distill-Qwen-1.5B 的 Turn 0 generation prompt 是:
<|Assistant|><think>\n
对应 token 末尾是:
[151645, 151648, 198]
# 151645 = <|Assistant|>
# 151648 = <think>
# 198 = "\n"
模型真实生成的 output ids 是:
output_text = "I should add one and one.\n</think>\n1+1 = 2"
output_ids = [40, 1265, 912, 825, 323, 825, 624, 151649, 198, 16, 10, 16, 284, 220, 17]
真实历史是:
<|Assistant|><think>
I should add one and one.
</think>
1+1 = 2
如果用 padding 重新 apply chat template,DeepSeek 历史 assistant 分支会把 <think>\n 去掉(因为判断"000000000000000"里不含thinking,所以chat_template会把generation prompt里的\n去掉,这是他chat_template自己的逻辑),padded render 变成:
<|Assistant|>000000000000000<|end▁of▁sentence|><|User|>...
或者如果按照原始 output start index 去 restore,会得到类似:
<|Assistant|>00I should add one and one.
</think>
1+1 = 2...
因为 padded 序列里缺了推理时真实存在的 <think>\n 两个 prompt token,后续位置已经不同构。这个问题不是 BPE,而是 generation prompt token 被 completed-message template 吃掉了。
反例:GLM4.7 {folded="true"}
GLM4.7 默认生成 prompt 是:
<|assistant|><think>
但历史 assistant message 分支如果没有 reasoning_content,或者 padding content 里没有 </think>,会渲染:
<|assistant|></think>{content}
所以如果旧 assistant 被替换成 padding,pad 前的 marker 会从真实 runtime 的:
<|assistant|><think>
变成:
<|assistant|></think>
这个 token 在 pad span 前面,restore pad 覆盖不到。
结论
我们必须保留之前轮累计的真实 token ids:
accumulated_token_ids = previous_prompt_ids + previous_completion_ids
下一轮只能追加新的 incremental token ids,不能对整个 full_messages 重新 encode。在这一点上,verl 当前逻辑是对的:它保留旧 trajectory buffer,下一轮将 incremental ids append 到 response_ids。例如 gateway 里 prefix 命中后会 copy active buffer,然后追加 incremental ids,见 verl/verl/agent/gateway/gateway.py:524-545。问题在于后面两件事:incremental token ids 怎么提取,以及 怎么 merge 到旧 token ids 上。
2. 怎么获得 incremental token ids
message-level incremental 很容易得到:
incremental_messages = new_messages[len(old_messages):]
难点是:如何把这些 incremental messages encode 成“纯净的、应该追加到旧 token ids 后面”的 token ids。如果直接:
encode(apply_chat_template(incremental_messages, add_generation_prompt=True))
很多 template 会额外生成 system prompt、tool schema、role prelude 等。这些内容本来已经在最初 prompt 或旧 token ids 中出现过,不应该再次拼进 trajectory。
verl 当前做法
verl 已经发现了这个问题,所以 _encode_incremental 会单独 encode incremental messages,然后删掉 self._system_prompt:
ids = apply_chat_template(incremental_messages, add_generation_prompt=True)
return ids[len(self._system_prompt):]
源码位置:
verl/verl/agent/gateway/gateway.py:412-454- 传统 ToolAgentLoop 也有同样的
remove_system_prompt=True,见verl/verl/experimental/agent_loop/agent_loop.py:243-309但这个方法有两个问题。
问题 1:system prompt 长度提取本身不可靠
Two bad cases: https://github.com/verl-project/verl/issues/6500 https://github.com/verl-project/verl/issues/6501
verl 的 system prompt 提取在 verl/verl/utils/chat_template.py:13-32:
token1 = apply_chat_template([user_empty], add_generation_prompt=False)
token2 = apply_chat_template([user_empty, user_empty], add_generation_prompt=False)
system_prompt = token1[:-(len(token2) - len(token1))]
这个方式假设第二个 user 只是追加了一段固定长度 suffix,所以 len(token2) - len(token1) 就是第一条 user turn 的长度。
但有些 tokenizer 的 turn delimiter / eos / thinking marker 会随消息位置变化。比如一个 message 在“最后一条”时和在“历史消息”时渲染不同,len(token2)-len(token1) 就不再是稳定的 user turn 长度。这样提取出的 system_prompt 长度会错,后续 incremental ids 的起点也会错。所以我们更像倾向于用构造anchor message的方式来提取纯净的incremental token。但是如果随意构造anchor message会引发问题B。
问题 2:tool response 通常依赖前面的 assistant tool call
tool response 不是普通 user 文本。很多 chat template 需要看到:
{"role": "assistant", "tool_calls": [...]}
{"role": "tool", "content": "..."}
才能正确渲染 tool-response boundary。只对 tool message 单独 apply chat template,或者只用 anchor system,很容易直接报错或者得到错误边界。比如某些模板需要根据前一个 assistant tool call 来决定如何渲染。所以构造anchor message也需要特定的方式,并且允许不同模型重写方法。
反例1: MiniMax
如果没有dummy assistant chat template会直接报错
反例2: Nemotron
如果没有dummy assistant 会少渲染 <|im_start|>user
反例3: Llama-3.1-8B-Instruct
如果我们为了提取 tool response 的 incremental ids,只构造 dummy system:
base_messages = [
{"role": "system", "content": "dummy system"},
]
appended_messages = [
{
"role": "tool",
"tool_call_id": "call12345",
"name": "get_weather",
"content": '{"temperature":"20C"}',
}
]
text_without = tokenizer.apply_chat_template(
base_messages,
tools=tools,
tokenize=False,
add_generation_prompt=False,
)
这个 tokenizer 会直接报错:
TemplateError: Cannot put tools in the first user message when there's no first user message!
原因是这个 template 在有 tools 的时候,会试图把 tool schema 放进第一条 user message;但 synthetic context 里只有 system,没有 user,也没有前置 assistant tool call,所以这个上下文对它来说是不合法的。如果构造 dummy assistant:
base_messages = [
{"role": "system", "content": "dummy system"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call12345",
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"city": "SF"},
},
}
],
},
]
full_messages = base_messages + appended_messages
就可以正常 render,并且 suffix diff 能切出干净的 tool result:
<|start_header_id|>ipython<|end_header_id|>
"{\"temperature\":\"20C\"}"<|eot_id|>
这个例子说明:dummy assistant 的作用不是“随便垫一条 assistant”,而是在 synthetic context 里恢复真实 rollout 的前置状态:assistant 刚刚发起了对应 tool call,现在才轮到 tool response。这里还有一个小细节:构造 tool-response synthetic context 时不要顺手加 dummy user。比如 Qwen3 会根据“assistant 是否在最后一个真实 user 之后”“assistant 是否是最后一条消息”来决定是否插入或清理 <think>...</think>。如果 base 写成 [_DUMMY_SYSTEM, _DUMMY_USER, dummy_assistant],text_without 里 dummy assistant 可能因为位于最后一个 user 之后而被插入空 thinking block;但 text_with = base + tool_response 后 assistant 又不再是最后一条,thinking block 被删掉,导致 text_with.startswith(text_without) 失败。这个设计的重点是:不要求完整 conversation 的 chat template append-only (append-only是指,对msgs1+msgs2 apply chat template后的前缀完全等于只对msgs1 apply chat template),只要求 synthetic context 下的append-only即可,稳定切出当前 role 的 suffix即可。
3. incremental ids 如何正确 merge 回 accumulated ids
拿到 incremental token ids 后,verl的做法是简单的:
accumulated_ids + incremental_ids
这个做法是不严谨的。因为模型 stop token 和 chat template 的下一个 turn boundary 之间,经常不是一一对应。
反例1 Qwen3:生成停在 <|im_end|>,template 需要 <|im_end|>\n {folded="true"}
Qwen3 chat template 的每个 message 结尾通常是:
<|im_end|>\n
但模型生成时 stop 在:
<|im_end|>
不会生成后面的 \n。如果下一轮直接 append incremental ids,就少一个 newline。
反例2 GLM4.7:stop token 和下一条消息 BOS 共用
GLM4.7 里 <|user|> 和 <|observation|> 既可能是 assistant 的 stop token,也可能是下一条消息的 start token。例如 tool call 成功时:
runtime prefix ends with: <|observation|>
incremental tool response starts with: <|observation|><tool_response>...
如果直接拼:
...<|observation|><|observation|><tool_response>...
就出现重复 <|observation|>。tool call 失败或没有走 tool 时,模型可能已经停在:
<|observation|>
但下一轮环境追加的是 user retry:
<|user|>tool call fails, please retry
直接拼会变成:
...<|observation|><|user|>tool call fails...
语义也错了,因为 <|observation|> 是模型为了 tool result 预期生成的 stop/boundary,但真实下一轮不是 observation。注意,经验表明special token的错误是语义层面的,比qwen3的\n问题要严重,可能会有较大训崩的风险。
结论
综合以上三点,我们需要一个 ContinuousTokenBuilder 抽象:
class ContinuousTokenBuilder:
def encode_environment_delta(...):
...
def merge(prev_messages, next_messages, runtime_token_ids, tools=None):
delta = self.encode_environment_delta(...)
return [*runtime_token_ids, *delta]
不同模型可以通过继承 ContinuousTokenBuilder 并重写实例方法来定制化增量提取和边界拼接。针对一些常用模型,我们可以写好正确的 model-specific continuous token builder 以供用户直接使用。
4. trajectory 构造后需要 comparator
完整 trajectory 拼好后,需要检查:
non-assistant 内容是否正确
special token 数量/类型是否正确
message boundary 是否正确
但不能简单要求:
accumulated_ids == encode(apply_chat_template(full_messages))
因为 full template canonical render 可能会修改历史 assistant 内容。比如 Qwen3 / DeepSeek / GLM 可能会清掉之前轮的 thinking:
runtime actual:
<think>
previous reasoning
</think>
final answer
canonical full render:
final answer
这种差异应该允许,因为 TITO 的目标是保留真实 runtime token prefix,而不是让历史 assistant 被 template 事后 canonicalize。比较逻辑:
- 先按 special token 切 segment。
- 如果 segment 数量或 special/content pattern 不同,报
special_token_count。 - 如果 special token 类型不同,报
special_token_type。 - 如果普通 content 不同,根据它是否属于 assistant segment,分类为
assistant_text或non_assistant_text。assistant_text是 soft mismatch:允许 assistant 犯错,允许 runtime assistant token 和 canonical template 不同。hard mismatch 是:
special_token_count
special_token_type
non_assistant_text
这些说明 role boundary、tool response、user/system/env 内容等被 TITO 拼坏了。verl 当前没有这样的 comparator。
二、正确的做法和设计
数据结构
# 一个 RolloutTokenState 对应一次 agentic rollout 的一条 sample trajectory。
class RolloutTokenState:
rendered_messages: list[dict]
runtime_token_ids: list[int]
records: list[RequestResponseRecord]
Continuous token builder 抽象
class ContinuousTokenBuilder:
append_only_roles = {"tool"}
def render_chat(self, messages, *, add_generation_prompt, tools=None, tokenize=False):
return tokenizer.apply_chat_template(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
tokenize=tokenize,
**chat_template_kwargs,
)
def encode_render_delta(self, anchor_messages, delta_messages, *, tools=None, add_generation_prompt=False):
before = self.render_chat(anchor_messages, add_generation_prompt=False, tools=tools)
after = self.render_chat(
anchor_messages + delta_messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
)
if not after.startswith(before):
raise ValueError("synthetic context is not append-only for this segment")
return encode(after[len(before):])
def encode_tool_observations(self, tool_messages, tools=None):
assistant_stub = make_tool_call_stub(tool_messages)
return self.encode_render_delta(
[SYNTHETIC_SYSTEM, assistant_stub],
tool_messages,
tools=tools,
)
def encode_plain_turn(self, message, tools=None):
return self.encode_render_delta(
[SYNTHETIC_SYSTEM],
[message],
tools=tools,
)
def encode_environment_delta(self, prev_messages, next_messages, tools=None):
require_message_prefix(prev_messages, next_messages, append_only_roles=self.append_only_roles)
new_tail = next_messages[len(prev_messages):]
pieces = []
for role, segment in group_consecutive_roles(new_tail):
if role == "tool":
pieces.extend(self.encode_tool_observations(segment, tools=tools))
elif role in {"user", "system"}:
pieces.extend(self.encode_plain_turn(segment[0], tools=tools))
pieces.extend(self.encode_render_delta(
next_messages,
[],
tools=tools,
add_generation_prompt=True,
))
return pieces
def merge(self, prev_messages, next_messages, runtime_token_ids, tools=None):
delta = self.encode_environment_delta(prev_messages, next_messages, tools=tools)
return [*runtime_token_ids, *delta]
模型特化 merge
class Qwen3ContinuousTokenBuilder(ContinuousTokenBuilder):
def merge(...):
delta = self.encode_environment_delta(...)
prefix = list(runtime_token_ids)
if prefix and prefix[-1] == im_end_id:
prefix.append(newline_id)
return [*prefix, *delta]
class GLM47ContinuousTokenBuilder(ContinuousTokenBuilder):
def merge(...):
delta = self.encode_environment_delta(...)
prefix = list(runtime_token_ids)
if prefix and prefix[-1] in {user_id, observation_id}:
prefix = prefix[:-1]
return [*prefix, *delta]
Runtime 链路
def build_prompt_tokens(request_messages, tools):
if state.runtime_token_ids is None:
return continuous_builder.render_chat(
request_messages,
tools=tools,
add_generation_prompt=True,
tokenize=True,
)
return continuous_builder.merge(
prev_messages=state.rendered_messages,
next_messages=request_messages,
runtime_token_ids=state.runtime_token_ids,
tools=tools,
)
def update_after_generation(request_messages, prompt_token_ids, completion_token_ids, assistant_message):
# 这里保存的是 runtime 真实 token stream,不是 canonical full render。
state.runtime_token_ids = prompt_token_ids + completion_token_ids
state.rendered_messages = request_messages + [assistant_message]
Finalize / debug comparator
def inspect_runtime_render_gap(state):
canonical_ids = continuous_builder.render_chat(
state.rendered_messages,
add_generation_prompt=False,
tokenize=True,
)
return token_sequence_checker.compare(
expected_ids=canonical_ids,
actual_ids=state.runtime_token_ids,
)
Comparator 只把下面几类作为 hard error:
special_token_count
special_token_type
non_assistant_text
assistant_text 只记录 metric,不作为 hard error。原因是 assistant 内容来自模型真实输出,它可以包含错误格式、未 canonicalize 的 thinking、额外自然语言、甚至不符合模板预期的文本;这些不应该被 TITO 事后改写。
三、对 verl 当前逻辑的总结
verl 当前已经满足“基础 token-in-token-out”:
- 初始 prompt 全量
apply_chat_template。 - 模型输出 token ids 直接 append。
- tool/user 环境增量 token ids mask 为 0。
- 后续 generation 用累计 token ids。
但它还缺少更为 robust的multi-turn TITO 相关组件:
- 他针对模型特化性的逻辑是通过类似
if Qwen3这样hardcode来进行的,没有进行抽象的设计 - incremental ids 不是通过 dummy context suffix diff 提取,而是 standalone encode 后 strip system prompt。
initialize_system_prompt的长度推断对位置相关 template 不稳。- tool response 没有构造 dummy assistant/tool_calls 以保留 tool boundary shape。
- finalize 后没有 token sequence comparator 来区分 assistant soft mismatch 和真正的 structure/non-assistant hard mismatch。
PR Stack
Please review the PR one by one, they were developed in sequential order.
-
Core continuous token builder, wiring, and config
https://github.com/verl-project/verl/pull/6720 -
AgentLoop integration
https://github.com/verl-project/verl/pull/6721 -
CT vs legacy comparison tests and report
https://github.com/verl-project/verl/pull/6722 -
Chat template checker
https://github.com/verl-project/verl/pull/6723
Main Changes
-
Add Continuous Token core builders in
verl/utils/continuous_token.pyContinuousTokenBuilderMergeResult- Qwen, MiniMax, and GLM-specific boundary handling
-
Add builder registry and model-family resolution in
verl/utils/continuous_token_wiring.py -
Add rollout config in:
verl/workers/config/rollout.pyverl/trainer/config/rollout/rollout.yaml
-
Integrate Continuous Token into existing AgentLoop paths:
verl/experimental/agent_loop/agent_loop.pyverl/experimental/agent_loop/single_turn_agent_loop.pyverl/experimental/agent_loop/tool_agent_loop.py
-
Add model-specific tool parsers in
verl/experimental/agent_loop/tool_parser.py -
Add comparison harness and documented results:
tests/experimental/agent_loop/continuous_token/compare_agentloop_ct_vs_legacy.pytests/experimental/agent_loop/continuous_token/mock_trajectories.pytests/experimental/agent_loop/continuous_token/README.md
-
Add standalone chat-template validation tool:
scripts/chat_template_checker.py
TODO
- [ ] Support DeepSeek models that do not expose a Jinja
chat_template. - [ ] Add multimodal Continuous Token support.
Motivation
stated above
Your contribution
stated above