verl icon indicating copy to clipboard operation
verl copied to clipboard

# [rollout] perf: `_tokenize_generation_prompt_delta` re-tokenizes the full conversation after every tool turn

Open fshp971 opened this issue 3 months ago • 10 comments

System Info

Problem

The problem is triggered whenever an agent appends a non-assistant message, most commonly a tool response, and asks Continuous Token to merge it into the runtime prompt.

The execution chain is:

AgentLoopBase.ct_merge_non_assistant_msg()
  -> ContinuousTokenBuilder.merge_non_assistant_tokens()
    -> ContinuousTokenBuilder.tokenize_non_assistant_incremental_messages()
      -> _tokenize_tool_group()                         # tokenizes only appended tool messages
      -> _tokenize_generation_prompt_delta()
        -> render_delta_token_id(updated_messages, [])
          -> _render_tokens(updated_messages, add_generation_prompt=False)
          -> _render_tokens(updated_messages, add_generation_prompt=True)
  1. AgentLoopBase.ct_merge_non_assistant_msg() delegates the merge to continuous_token_builder.merge_non_assistant_tokens().
  2. merge_non_assistant_tokens() calls tokenize_non_assistant_incremental_messages().
  3. tokenize_non_assistant_incremental_messages() first tokenizes the newly appended messages with a small synthetic prompt, but then passes the complete updated_messages history to _tokenize_generation_prompt_delta().
  4. _tokenize_generation_prompt_delta() calls render_delta_token_id(updated_messages, [], add_generation_prompt=True, tools=tools).
  5. render_delta_token_id() renders and tokenizes the same complete history twice: once without the generation prompt and once with it.

Therefore, every tool turn performs two full-history renders only to obtain the short scaffold that starts the next assistant turn. Builders using the base implementation are affected. Processor-backed builders make the same issue more expensive because every render also performs processor/template work over the complete message list.

Although the returned token IDs are correct, this path is not fully incremental. As the conversation grows, every turn repeats work over all previous turns, creating approximately quadratic cumulative tokenization work for long agent trajectories.

Suggested Fix

Use bounded pseudo messages to derive the generation-prompt delta instead of passing the accumulated conversation to render_delta_token_id().

Continuous Token already uses this approach when tokenizing appended messages:

More specifically, for templates whose generation scaffold is independent of the preceding conversation, the temporary fix used for the measurement below replaces verl/utils/tokenizer/continuous_token.py#L252 with:

return self.render_delta_token_id(
    [_SYNTHETIC_SYSTEM_MESSAGE, _SYNTHETIC_USER_MESSAGE],
    [],
    add_generation_prompt=True,
    tools=tools,
)

This performs two small renders whose size is independent of the accumulated trajectory, instead of performing two small tool-message renders followed by two full-history generation-prompt renders.

Templates with a history-dependent generation scaffold still require a model-specific implementation or the existing full-history path as a correctness fallback.

Information

  • [ ] The official example scripts
  • [x] My own modified scripts

Tasks

  • [ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [x] My own task or dataset (give details below)

Reproduction

For Qwen3.5-9B with a 96K context length and a tool-call turn limit of 200:

Tokenization share of average rollout wall time Maximum tokenization time for one full trajectory
Before the temporary fix 33.75% 135.76 minutes
After the temporary fix 0.11% 42.93 seconds

Expected behavior

After the initial prompt has been rendered, appending a tool response should require work proportional to the appended messages and generation scaffold rather than the complete conversation.

This is a rollout scalability issue rather than an observed token-correctness failure.

fshp971 avatar Aug 30 '26 21:08 fshp971

Hi Thank you very much for your insight. The purpose of encoding full message history for generation prompt derivation is that some chat template will render generation prompt based on the full message history instead of simply the last incremental message. But the performance cost is indeed avoidable for chat template that has been verified to render generation prompt only depending on the last message.

gxlvera avatar Aug 30 '26 21:08 gxlvera

I can take this. Plan: derive the generation-prompt delta from a bounded pseudo tail keyed by the last message's role (same trick _tokenize_tool_group already uses), validate it against the full render once per role at runtime, and add full-vs-incremental equivalence tests across the Qwen / GPT-OSS / MiniMax builders. PR shortly.

ruiling-smartbear avatar Aug 30 '26 23:08 ruiling-smartbear

Thanks @gxlvera - I had not seen your reply when I opened #7619. Rescoped it to match: the base class keeps the full-history render as the fallback, the Qwen ChatML builders (qwen / qwen25 / qwen3 / qwen35) override with the bounded render, and QwenVL stays on the fallback until its templates are checked. Verified token-for-token against the real Qwen3-0.6B/8B and Qwen3.5-9B/35B-A3B templates (80 cases). @fshp971 if you had already started on this, happy to hand it over or fold your changes in.

ruiling-smartbear avatar Aug 31 '26 01:08 ruiling-smartbear

Hi Thank you very much for your insight. The purpose of encoding full message history for generation prompt derivation is that some chat template will render generation prompt based on the full message history instead of simply the last incremental message. But the performance cost is indeed avoidable for chat template that has been verified to render generation prompt only depending on the last message. As for the suggested fix, I agree with the direction. One detail is that ContinuousTokenBuilder serves as the fallback for unknown models and custom chat templates, so changing the base implementation to assume synthetic-context equivalence may introduce correctness issue. I think it would be safer to keep the current full-history implementation as the default fallback and override _tokenize_generation_prompt_delta() for verified model families such as Qwen3/Qwen3.5. Models with history-dependent rendering can continue using the full-history encode path.

@gxlvera @ruiling-smartbear It incurs too much overhead by encoding full messages twice but only to get the generation prompt id(add_generation_prompt=True). There're some other model series that users are testing and training, e.g DeepSeek, GLM, etc, default fallback to full encoding is not a good idea. Can we cache the generation prompt id since it's remain the same across multi-turns?

wuxibin89 avatar Aug 31 '26 02:08 wuxibin89

Hi Thank you very much for your insight. The purpose of encoding full message history for generation prompt derivation is that some chat template will render generation prompt based on the full message history instead of simply the last incremental message. But the performance cost is indeed avoidable for chat template that has been verified to render generation prompt only depending on the last message. As for the suggested fix, I agree with the direction. One detail is that ContinuousTokenBuilder serves as the fallback for unknown models and custom chat templates, so changing the base implementation to assume synthetic-context equivalence may introduce correctness issue. I think it would be safer to keep the current full-history implementation as the default fallback and override _tokenize_generation_prompt_delta() for verified model families such as Qwen3/Qwen3.5. Models with history-dependent rendering can continue using the full-history encode path.

@gxlvera @ruiling-smartbear It incurs too much overhead by encoding full messages twice but only to get the generation prompt id(add_generation_prompt=True). There're some other model series that users are testing and training, e.g DeepSeek, GLM, etc, default fallback to full encoding is not a good idea. Can we cache the generation prompt id since it's remain the same across multi-turns?

Hi Thank you very much for your insight. The purpose of encoding full message history for generation prompt derivation is that some chat template will render generation prompt based on the full message history instead of simply the last incremental message. But the performance cost is indeed avoidable for chat template that has been verified to render generation prompt only depending on the last message. As for the suggested fix, I agree with the direction. One detail is that ContinuousTokenBuilder serves as the fallback for unknown models and custom chat templates, so changing the base implementation to assume synthetic-context equivalence may introduce correctness issue. I think it would be safer to keep the current full-history implementation as the default fallback and override _tokenize_generation_prompt_delta() for verified model families such as Qwen3/Qwen3.5. Models with history-dependent rendering can continue using the full-history encode path.

@gxlvera @ruiling-smartbear It incurs too much overhead by encoding full messages twice but only to get the generation prompt id(add_generation_prompt=True). There're some other model series that users are testing and training, e.g DeepSeek, GLM, etc, default fallback to full encoding is not a good idea. Can we cache the generation prompt id since it's remain the same across multi-turns?

I will keep cached generation prompt id as default, and allow model-specific override to support special behavior on generation prompt encode.

gxlvera avatar Aug 31 '26 03:08 gxlvera

For Qwen3.5-9B with a 96K context length and a tool-call turn limit of 200:

Tokenization share of average rollout wall time Maximum tokenization time for one full trajectory
Before the temporary fix 33.75% 135.76 minutes
After the temporary fix 0.11% 42.93 seconds

@fshp971, I have a quick question regarding this. Even in the worst-case scenario, it seems like tokenizing a 96K trajectory 200 times shouldn't take 136 minutes. Do you think there might be other factors contributing to this time overhead? Just wondering if there are some extra preprocessing steps involved that might be driving up the cost?

yt0428 avatar Aug 31 '26 03:08 yt0428

For Qwen3.5-9B with a 96K context length and a tool-call turn limit of 200:

Tokenization share of average rollout wall time Maximum tokenization time for one full trajectory
Before the temporary fix 33.75% 135.76 minutes
After the temporary fix 0.11% 42.93 seconds

@fshp971, I have a quick question regarding this. Even in the worst-case scenario, it seems like tokenizing a 96K trajectory 200 times shouldn't take 136 minutes. Do you think there might be other factors contributing to this time overhead? Just wondering if there are some extra preprocessing steps involved that might be driving up the cost?

maybe it's because GIL is not truly released when doing tokenization even if we currently run it in thread pool with multi worker. A reproduction is very welcome and needed~

gxlvera avatar Aug 31 '26 03:08 gxlvera

@wuxibin89 @gxlvera I measured the exact change under discussion: drop the two full-history renders and instead render the last append group with add_generation_prompt=True, so one render yields the group and the generation prompt together. Upstream main @8e4a572, real tokenizers (tokenizer files only, transformers 5.16.1), token ids compared against what main produces today.

Trajectories are shaped exactly the way tool_agent_loop builds them: optional system prompt → user prompt → per turn an assistant message whose tool_calls[].function.arguments is a JSON object (what OpenAIFunctionCallSchema.model_dump() gives) and one tool message per call carrying only content and tool_call_id. The append under test is the last tool group, which is the only append group that loop ever produces. 24 cases per model: system prompt on/off × 0 / 10 / 50 prior tool turns × 1 or 2 parallel calls × enable_thinking default / False (templates without that switch ignore it, so their two halves are the same renders).

builder model folded == today's path today's path == full-history diff folded == full-history diff
qwen Qwen2-7B-Instruct 24/24 24/24 24/24
qwen25 Qwen2.5-7B-Instruct 24/24 24/24 24/24
qwen3 Qwen3-8B 24/24 n/a¹ n/a¹
qwen35 Qwen3.5-9B 24/24 24/24 24/24
minimaxm2 MiniMax-M2 24/24 24/24 24/24
glm47 GLM-4.7 24/24 24/24 24/24
gemma4 gemma-4-12b-it 24/24 24/24 24/24
gptoss gpt-oss-20b 0/24² 0/24² 0/24²
deepseek DeepSeek-V3.2-Exp –³ –³ –³
default Qwen3-8B via the base builder 24/24 n/a¹ n/a¹

¹ For Qwen3-8B, rendering previous is not a token prefix of rendering previous + appended (its template re-renders earlier assistant turns), so the naive full-history diff raises rather than giving a reference. That is why the bounded synthetic-prefix renders exist in the first place; the folded render still matches today's path on all 24.

² gpt-oss never goes through the template for tool groups — GptOssContinuousTokenBuilder._tokenize_tool_group formats the response with an f-string and calls tokenizer.encode — so the flag has nothing to act on and the folded output is today's output minus the trailing <|start|>assistant. Folding there is one line: append that constant to the hand-built string. Unrelated to this issue but visible in the same run: today's path never matches the full-history render for gpt-oss either, because the template writes tool content JSON-encoded and _format_tool_response writes it raw:

template : <|start|>functions.lookup to=assistant<|channel|>commentary<|message|>"Pittsburgh had 302,971 residents..."<|end|>
verl main: <|start|>functions.lookup to=assistant<|channel|>commentary<|message|>Pittsburgh had 302,971 residents...<|end|>

³ DeepSeek-V3.2-Exp: every tool append fails on main today, before this change enters the picture. _synthetic_assistant_for_tools sets "arguments": {} and that template concatenates arguments as a string (TypeError: can only concatenate str (not "dict") to str when rendered through jinja2 directly); the harness passes a mapping too, so the full-history render of a real trajectory fails the same way.

Gemma 4 is the interesting row: its generation prompt is conditional on what the previous message was ({%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}{{ '<|turn>model\n' }} ...), i.e. nothing is emitted after a tool response. The last append group carries that state, so the folded render reproduces it, and so does the full-history render — 24/24 on all three columns.

So: 192 template-rendered cases over 8 rows (7 distinct templates, plus Qwen3-8B through the base builder), zero differences, on the trajectories the loop actually produces. The generation prompt comes out of the last group's render on every template I could load, with 0, 10 and 50 turns of history alike. DeepSeek V4's builder already works this way in deepseek.py (_encode(appended_messages, add_generation_prompt=True)).

Two things an implementation needs that the one-liner does not say: only the last append group of a call gets the flag, and builders that build a group without the chat template (gpt-oss) append the generation prompt themselves.

On @gxlvera's point about unknown templates: the assumption behind this is the same one the bounded synthetic-prefix renders already make — the tail of the conversation determines what the template emits next. Every template measured satisfies it, but a custom one might not. A cheap way to keep the fallback without paying for it per turn: the first time a final role is seen on a builder, render both ways and compare; on a mismatch that role keeps the full-history render, otherwise never render the full history again. One extra render pair per role per rollout.

Write-up with the exact trajectories and the script: https://github.com/ruiling-smartbear/verl-experiments/blob/main/generation_prompt_fold_experiment.md

#7619 now implements the cached-id default from the comment above (keyed by final role + tools, checked against the full render on the first uses of each key, _render_generation_prompt_delta as the override hook, VL builders left uncached). Folding is the zero-extra-render version of the same assumption; if you would rather have that in the base class instead of the cache, I can switch #7619 over.

ruiling-smartbear avatar Aug 31 '26 03:08 ruiling-smartbear

@gxlvera Sounds good. One data point for the cached-id default, from the same run: the cache has to be keyed on the role of the final message, not only on the model. DeepSeek-V3.2-Exp's template emits <|Assistant|></think> after a user turn and nothing at all after a tool output ({% if add_generation_prompt and not ns.is_tool %}), so one id per model would append a generation prompt where the template would not. Keyed on (final role, tools), every template I measured is stable across 20 turns.

I have that version ready — cache keyed by (final role, tools), checked against the full-history render on the first uses of each key, model-specific override for anything special — and can rework #7619 into it today if you'd rather review than write it. If you're already on it, I'll close #7619 and stay out of the way.

On the 136 minutes @yt0428 asked about: tokenization alone for a 200-turn tool loop with a ~40K-char history on Qwen3.5-9B is about 24 s single-threaded here (per-turn cost 4 -> 264 ms), so that figure looks like contention on top of the quadratic render rather than the render itself.

ruiling-smartbear avatar Aug 31 '26 03:08 ruiling-smartbear

@gxlvera Sounds good. One data point for the cached-id default, from the same run: the cache has to be keyed on the role of the final message, not only on the model. DeepSeek-V3.2-Exp's template emits <|Assistant|></think> after a user turn and nothing at all after a tool output ({% if add_generation_prompt and not ns.is_tool %}), so one id per model would append a generation prompt where the template would not. Keyed on (final role, tools), every template I measured is stable across 20 turns.

I have that version ready — cache keyed by (final role, tools), checked against the full-history render on the first uses of each key, model-specific override for anything special — and can rework #7619 into it today if you'd rather review than write it. If you're already on it, I'll close #7619 and stay out of the way.

On the 136 minutes @yt0428 asked about: tokenization alone for a 200-turn tool loop with a ~40K-char history on Qwen3.5-9B is about 24 s single-threaded here (per-turn cost 4 -> 264 ms), so that figure looks like contention on top of the quadratic render rather than the render itself.

Thanks for the explaination. This sounds much more reasonable.

yt0428 avatar Aug 31 '26 04:08 yt0428