Skip to content

[rl] TokenEnv: pass prompt_ids to parse_response, store tool calls as ToolCall dicts - #6098

Draft
felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/token-env-tool-call-render
Draft

felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/token-env-tool-call-render

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: TokenEnv.step now passes the sampling prompt to the parser and stores tool calls as ToolCall dicts. On main, GPT-OSS AlphabetSort graded the analysis text together with the answer, and later prompts showed it as a past answer. A full re-render of a tool-call turn would crash. No in-repo TokenEnv recipe hits that today.

GPT-OSS's prompt opens the analysis channel, so main parses the whole completion as content while this PR splits off the reasoning; the turn-2 prompt is 115 tokens re-rendered on main and 101 tokens extended with this PR; tool calls are parsed once and stored as ToolCall dicts, so a later render no longer raises AttributeError

# before
parsed = renderer.parse_response(token_ids=completion.token_ids, tools=tools)
completion_message["tool_calls"] = parsed.tool_calls     # ParsedToolCall objects
# after
parsed = renderer.parse_response(token_ids=..., tools=tools, prompt_ids=self._last_prompt.token_ids)
completion_message["tool_calls"] = [                       # ToolCall dicts; calls with no name dropped
    {"type": "function", "function": {"name": call.name, "arguments": call.arguments}}, ...
]

Problem

  1. renderers types Message.tool_calls as ToolCall dicts. Its parser returns ParsedToolCall records and asks for the sampling prompt_ids.
  2. TokenEnv.step passes no prompt_ids and stores the records. CI's pyrefly skips torchtitan/rl, so nothing flags it.
  3. GPT-OSS's prompt already opens the analysis channel. Without the prompt, the whole completion parses as content. The rubric grades it, and the next prompt shows it as a past answer.
  4. When the bridge returns None (a new user turn, with GPT-OSS or Qwen3 / Qwen3.5 thinking on), the full re-render calls .get("function") on a ParsedToolCall. The rollout ends as ERROR.
  5. Fixing only step 3 exposes step 4: AlphabetSort would crash on a turn where GPT-OSS writes a harmony call and the next user turn re-renders.

Solution

  1. TokenEnv.step passes prompt_ids=self._last_prompt.token_ids.
  2. It turns each named call into a ToolCall dict; null arguments become {}. A ToolCall needs a name, so a call with no name is dropped. Its tokens stay in the trained completion.
  3. Envs, the history, the rollout JSONL and the next render see the same dicts. SearchR1Env and the MessageEnv example read call["function"]["arguments"].
  4. The Muse renderers drop _normalize_tool_calls. It accepted the parser's records and flat {"name", "arguments"} dicts; no in-repo code passes either.
  5. GPT-OSS AlphabetSort sets auto_drop_analysis=False. The default drops earlier analysis at each user turn and re-renders. Keeping it lets the bridge extend, so a rollout trains as one sample.
  6. Unchanged: the bridge, the other recipes, and Search-R1's tool replies (TODO in the env).

Results (CPU, renderers 0.1.12, gpt-oss-20b tokenizer, env replies as user)

                         main                                         this PR
completion_message       content='Sort them.<|end|><|start|>...a, b'  content='a, b', reasoning_content='Sort them.'
turn 1 in turn-2 prompt  final<|message|>Sort them.<|end|>            analysis<|message|>Sort them.<|end|>
                         ...final<|message|>a, b<|end|>               ...final<|message|>a, b<|return|>
turn-2 prompt            115 tokens, re-rendered (keeps 73 of 88)     101 tokens, bridged (keeps all 88)
harmony call, no tools   not parsed                                   parsed: sorter {"x": 1}

The 88 tokens are the 75-token turn-1 prompt plus the 13-token completion. With the renderer default, this PR's turn-2 prompt would be 92 tokens, re-rendered (keeps 73 of 88), with no analysis.

You may ask:

  • Why not convert only at the full re-render? The history would hold two shapes of one call, and every other reader must handle both.
  • Why drop a call with no name instead of keeping its text? Rubrics grade content, so the broken block would join the graded answer.
  • Why keep GPT-OSS's earlier analysis? RL libraries that train a rollout as one sequence keep earlier reasoning. Main kept it too, but as answer text.

NOTE:

  • GPT-OSS AlphabetSort trains differently: the reward reads the final answer only, and a rollout trains as one sample instead of one per user turn (rollout/branches_per_rollout), unless a turn ends inside its analysis.
  • Prompts keep the analysis, so turn 3 can reach the recipe's 2,048-token seq_len (700 tokens per turn, up to 3 turns) and end as TRUNCATED_LENGTH. Not new vs main: main kept the analysis as text, and its prompts were longer in the probe (turn 2: 115 vs 101 tokens, turn 3: 155 vs 127).
  • The bridged history keeps the sampled <|return|> where harmony's chat template writes <|end|>. An eval with the standard chat template never shows the model this history.
  • The Qwen3 recipes (thinking on or off), the Qwen3.5 recipe (thinking off) and the Muse recipes parse the same (CPU probe).
  • Search-R1 with Qwen3 now ends the rollout on a turn whose calls all lack a name, and the rubric grades the text before the call (usually 0). On main, a call such as {"arguments": {"query": "Hamlet"}} searched "Hamlet". The Muse parsers need a non-empty name, so only Qwen3 is affected.
  • A call with no name leaves the rollout record. A Qwen3 turn whose only call has bad JSON records as {"role": "assistant", "content": ""}; main recorded the raw text with status invalid_json.
  • A name that is not a string ({"name": 5}, which renderers' Qwen3 parser returns) is dropped too. A TODO removes that check once the parser marks it missing.
  • Terminal-Bench runs through Verifiers, not TokenEnv. Verifiers parses with renderers' generate, which passes the prompt, and stores tool calls as dicts. So it hits neither problem.
  • Not run: a GPU run.

Follow up / TODO

  • One GPT-OSS AlphabetSort run vs main: reward, step time, prompt length, TRUNCATED_LENGTH rate, and one eval with the standard chat template.
  • Search-R1: name each tool reply, answer unknown tools and empty queries with an error, count only search calls in the rubric. Changes the Muse Glimmer prompts and the reward. TODO in the env.
  • Record dropped and broken calls (raw text, parse status), so a JSONL reader, a rubric or a loss mask can see them. TODO at the drop line.
  • renderers: parse_qwen3 should mark a name that is not a string as missing (TODO in token_env.py; the issue is not filed yet).

Test plan

  • test_env_parses_with_the_prompt_and_re_renders_tool_calls (Qwen3.5, thinking on): fails on main, without prompt_ids, if unnamed calls are kept, and if the re-render doesn't run.
  • test_env_returns_each_next_prompt_as_a_delta: the second parse gets the latest prompt.
  • pytest tests/rl/unit_tests/cpu: 714 passed, 1 skipped (main: 713 passed, 1 skipped).
  • pytest tests/unit_tests/cpu/models/muse_glimmer tests/unit_tests/cpu/models/muse_spark (MUSE_GLIMMER_TOKENIZER set): 169 passed, 3 xfailed.
  • pyrefly on the 7 touched source files: main 5 errors, this PR 3 (both tool-call errors gone). Touched RL tests pass on renderers 0.2.0. pre-commit passes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 13, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 9s —— View job


I'll analyze this and get back to you.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review (the previous run hit a transient Bedrock 503)

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 8s —— View job


I'll analyze this and get back to you.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 23s —— View job


Approve -- please address the items before merging (empty human-written summary, split out the auto_drop_analysis=False recipe change, link the renderers issue for the {"name": 5} crash): review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The bug is real on main and fixed in the right place: TokenEnv.step now gives the parser its sampling prompt and stores the ToolCall shape that renderers, the history and the envs all expect. The recipe change bundled in here should be its own PR. A maintainer still needs to review, since this touches core RL rollout code.

What this PR does. TokenEnv.step now passes prompt_ids=self._last_prompt.token_ids to parse_response, so a prompt that opens a reasoning block (GPT-OSS analysis, Qwen3.5 <think>) parses as reasoning instead of content. It turns each named ParsedToolCall into an OpenAI-style ToolCall dict and drops calls with no name. With callers no longer passing the old shapes, the Muse renderers' _normalize_tool_calls shims can go, and Search-R1 and the MessageEnv example now read call["function"]["arguments"].

Example.

GPT-OSS, prompt ends "...<|start|>assistant<|channel|>analysis<|message|>"
completion: "Sort them.<|end|><|start|>assistant<|channel|>final<|message|>a, b<|return|>"

main:    content="Sort them.<|end|>...a, b"   -> rubric grades the analysis text too
         new user turn -> bridge None -> render(history with ParsedToolCall)
         -> .get("function") on a dataclass -> rollout ERROR (when a call was parsed)
this PR: content="a, b", reasoning_content="Sort them."
         tool_calls=[{"type": "function", "function": {"name": ..., "arguments": {...}}}]
         -> the re-render works

Must fix

  1. The "Summary (human-written)" section is empty. The author needs to fill it in; agents don't.
  2. torchtitan_recipes/rl/alphabet_sort.py:398 -- auto_drop_analysis=False changes how the recipe trains (one sample per rollout, longer prompts, <|return|> in the trained history but <|end|> at eval), and nothing has run it. The fix doesn't need it. Please split it out with the GPU comparison.
  3. torchtitan/rl/rollout/token_env.py:265 -- the known {"name": 5} crash needs a renderers issue link. A one-line isinstance(call.name, str) check would also close it now.

Questions

  • Dropping an unnamed call changes Search-R1 + Qwen3 rewards. The rollout now ends and the rubric grades the text before the broken call (usually 0), where main ran the search. Did the maintainers choose this over ending the turn as RolloutStatus.ERROR_PARSE? With the drop, the broken call's tokens train with whatever reward that text gets; with ERROR_PARSE, the failure is explicit in the rollout status and the JSONL.
Details
  • Gate. On main, token_env.py stored parsed.tool_calls (dataclasses) in Message.tool_calls. Both the Muse renderers and renderers' own templates read tc["function"]["name"], so the shims in muse_glimmer/renderer.py and muse_spark/renderer.py only existed to cover that mismatch. Converting once in TokenEnv is the right layer: the env, the history, the recorder and the re-render all see the same shape. Net LoC is +62, and almost all of it is the one new test (+86 in test_token_env.py). Source files are net negative.
  • Callsites audited. Both in-repo parse_response implementations (Muse Glimmer and Muse Spark) already take prompt_ids and del it, and the test fakes were updated. Every remaining tool-call reader in the Muse renderers reads the nested function form. Muse parsers always produce dict arguments, so _render_atem's dict check can't fire on a Muse re-render. torchtitan_recipes/models/muse_spark.py:548 (UltraData SFT) already reads nested dicts. The Verifiers recipes don't go through TokenEnv.
  • Tests. test_env_parses_with_the_prompt_and_re_renders_tool_calls guards an invariant nothing else covered (prompt-aware parse + re-render with tool calls), and uses the same QWEN3_5_TOKENIZER pattern as test_multiturn_images.py. The extra assertion in the delta test is cheap.

Not verified: how renderers 0.1.12 handles arguments=None and non-string names in parse_qwen3 (I couldn't inspect the package here), and every training-behavior claim, since none has had a GPU run.

Comment on lines +398 to +403
# Keep earlier analysis in later prompts: the bridge extends, and a rollout usually trains
# as one sample. Cost vs the default (re-render at each user turn): longer prompts, and the
# history keeps the sampled <|return|> where harmony's chat template writes <|end|>.
renderer=from_renderers(
GptOssRendererConfig(reasoning_effort="low", auto_drop_analysis=False)
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The parse fix doesn't need this, and it's a separate change to how the recipe trains. By the PR's own probe, without it this PR re-renders turn 2 (92 tokens) with no crash. With it, each rollout trains as one sample instead of one per user turn (rollout/branches_per_rollout changes), prompts get longer, and the trained history has the sampled <|return|> where the harmony template (and so any eval) writes <|end|>. None of that has a GPU run yet; the run is still an open follow-up item.

Please move it to its own PR along with the reward/step-time/TRUNCATED_LENGTH comparison, so this PR stays one concern (the parse fix plus the ToolCall shape).

Suggested change
# Keep earlier analysis in later prompts: the bridge extends, and a rollout usually trains
# as one sample. Cost vs the default (re-render at each user turn): longer prompts, and the
# history keeps the sampled <|return|> where harmony's chat template writes <|end|>.
renderer=from_renderers(
GptOssRendererConfig(reasoning_effort="low", auto_drop_analysis=False)
),
renderer=from_renderers(GptOssRendererConfig(reasoning_effort="low")),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: I kept it here on purpose. On main, this recipe's later prompts keep the earlier analysis, as answer text (turn 2: 115 tokens). With the parse fix alone, the renderer default drops it (92 tokens), so the fix by itself also changes what the recipe trains on, and removes reasoning that main fed the model. This line keeps the analysis, now in its own channel (101 tokens). Both versions change training without a GPU run; the run is a follow-up in the body. If a maintainer prefers the split, it is this one line plus a separate PR.

Comment thread torchtitan/rl/rollout/token_env.py Resolved
… ToolCall dicts

TokenEnv parsed each completion without the sampling prompt, and stored the
parser's ParsedToolCall records in Message.tool_calls, which renderers types
as OpenAI-style ToolCall dicts.

Without the prompt, GPT-OSS's parser can't see that the prompt opened the
analysis channel, so the whole completion parsed as content, with no
reasoning and no tool calls. When the bridge returned None, the full
re-render called .get("function") on each ParsedToolCall and the rollout
failed.

TokenEnv now passes prompt_ids and turns each named call into a ToolCall
dict where it builds the message. A ToolCall needs a string name, so a
call without one is dropped; its tokens stay in the completion. That also
covers a name that is not a string, which renderers' Qwen3 parser can
return ({"name": 5}); a TODO removes the check once the parser marks it
missing. Envs get the same dicts: SearchR1Env and the MessageEnv example
read call["function"]["arguments"].

Muse Glimmer's and Muse Spark's renderers drop _normalize_tool_calls. It
existed to accept the parser's records, and it also accepted flat
{"name", "arguments"} dicts, which now raise KeyError. No in-repo caller
passes either.

GPT-OSS AlphabetSort sets auto_drop_analysis=False. Main already
re-rendered at each user turn (in a CPU probe, its turn-2 prompt keeps 73
of 88 tokens). Compared with main, the setting changes two things: the
earlier analysis stays, now in its own channel, and a rollout trains as
one sample instead of one per user turn. Compared with the renderer
default, prompts are longer, and the history keeps the sampled <|return|>
where harmony's chat template writes <|end|>.
@felipemello1
felipemello1 force-pushed the felipemello1/token-env-tool-call-render branch from 7888f99 to 0780980 Compare November 13, 2026 23:27
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: On dropping an unnamed call vs ERROR_PARSE: this follows Verifiers, which also drops calls with no name. The tokens stay trained and the rubric scores the text, so a broken call gets the reward its answer earns (usually 0). On main, ERROR_PARSE marks a parse_response that raised, not a call the parser returned without a name. Recording dropped calls (raw text, parse status) is a TODO at the drop line.

@claude please review

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 57s —— View job


Approve -- please address the items before merging (the human-written summary is empty; link the renderers issue in the token_env.py TODO): review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. This re-review checks HEAD 0780980 against my previous review. The non-string-name crash is fixed. The replies on the recipe change and on dropping unnamed calls hold up against the code. Two small items are left. A maintainer still needs to review, since this touches core RL rollout code (token_env.py).

Example.

Qwen3 completion: <tool_call>{"name": 5, "arguments": {}}</tool_call>
previous HEAD: name 5 passes `if not call.name` -> next user turn re-renders -> TypeError, outside any try
this HEAD:     `not isinstance(call.name, str)` -> call dropped, tokens stay in the completion

Earlier items

  • Resolved: token_env.py:269 now checks isinstance(call.name, str), and the TODO is one line.
  • Resolved: the auto_drop_analysis=False split. The reply is right that the parse fix alone also changes what this recipe sees. On main, the earlier analysis reached later prompts as answer text. With the fix and the renderer default, it would be dropped. This line keeps it, now in its own channel. Either way training changes without a GPU run, so this one line is a fair thing to keep with the fix. Whether to split it is the maintainer's call.
  • Resolved: dropping a call with no name vs ERROR_PARSE. ERROR_PARSE is set only when parse_response raises (token_env.py:242-251). A call the parser returns without a name never reaches that path, so dropping it doesn't hide a status that main used to set.

Must fix

  1. The "Summary (human-written)" section is still empty. The author has to write it; agents don't.
  2. torchtitan/rl/rollout/token_env.py:265 -- the TODO works around a renderers parser bug but has no issue link. Please file the renderers issue and link it in the TODO before merging, so the isinstance check can be removed once it's fixed.

Not verified: every training-behavior claim (reward, rollout/branches_per_rollout, TRUNCATED_LENGTH rate). None has had a GPU run.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant