Repository navigation
feat: multi-reward tool-call environment and reward_components for GDPO #1525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cmunley1
merged 9 commits into
NVIDIA-NeMo:main
from
anjalibshah:gdpo-multireward-env-upstream
Jun 12, 2026
Merged
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6a6f526
feat: multi-reward tool-call environment and reward_components for GDPO
anjalibshah db35348
fix: scope reward_components to the env response subclass; ruff forma…
anjalibshah f6d50dc
data: add example-validation artifacts for tool_call_multireward
anjalibshah 0d18c49
docs: add tool_call_multireward to the README environment catalog
anjalibshah 829f0c8
refactor: rename tool_call_multireward -> example_tool_call_multireward
anjalibshah e4fb791
config: add value field to example_tool_call_multireward
anjalibshah ada2e41
Merge branch 'main' into gdpo-multireward-env-upstream
cmunley1 1146e5d
Merge branch 'main' into gdpo-multireward-env-upstream
cmunley1 603a0a7
Merge branch 'main' into gdpo-multireward-env-upstream
cmunley1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # Description | ||
|
|
||
| A single-tool-call environment that returns **multiple decoupled reward components**, | ||
| intended for multi-reward RL such as GDPO (https://arxiv.org/abs/2601.05242). | ||
|
|
||
| Each rollout asks the model to call `get_weather` for a city. The verifier scores the | ||
| response on three independent `{0, 1}` components: | ||
|
|
||
| - `correctness` — a predicted call matches the expected name and arguments. | ||
| - `schema_valid` — the call's arguments parse as a JSON object containing every required | ||
| parameter of the tool. | ||
| - `format` — exactly one tool call was emitted, with no extra assistant text. | ||
|
|
||
| These are returned in the `reward_components` field of the verify response (in addition | ||
| to the summed scalar `reward`). NeMo-RL's NeMo Gym bridge exposes them as | ||
| `reward1, reward2, ...` (ordered by component name: `correctness`, `format`, | ||
| `schema_valid`) for the GDPO advantage estimator. A GRPO baseline reads the summed | ||
| `reward` and therefore cannot distinguish responses with the same total but different | ||
| composition — the advantage collapse GDPO is designed to fix. | ||
|
|
||
| The example data can be found in `tool_call_multireward/data/example.jsonl` and is | ||
| regenerated with `python resources_servers/tool_call_multireward/create_examples.py`. | ||
|
|
||
| # Licensing information | ||
| Code: Apache 2.0 | ||
| Data: Apache 2.0 | ||
|
|
||
| Dependencies | ||
| - nemo_gym: Apache 2.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Single-tool-call environment scored on three decoupled reward components. | ||
|
|
||
| This is a multi-reward environment intended for GDPO | ||
| (https://arxiv.org/abs/2601.05242). A single expected tool call is graded on three | ||
| independent {0, 1} components: | ||
|
|
||
| - ``correctness`` : a predicted call matches the expected name + expected arguments. | ||
| - ``schema_valid`` : the call's arguments parse as a JSON object containing every | ||
| required parameter of the tool. | ||
| - ``format`` : exactly one tool call was emitted and no extra assistant text. | ||
|
|
||
| These decouple: a response can be well-formed but wrong, correct but malformed, etc. | ||
| GDPO normalizes each component independently, so two responses with the same total | ||
| reward but different composition receive different advantages (whereas GRPO, which | ||
| normalizes the summed reward, collapses them). | ||
|
|
||
| The components are returned in ``reward_components``; NeMo-RL exposes them as reward1, | ||
| reward2, ... ordered by component name (correctness, format, schema_valid). ``reward`` | ||
| is set to the sum so a single-reward (GRPO) baseline reads the same aggregate. | ||
| """ | ||
|
|
||
| import json | ||
| from typing import Any, Dict, List | ||
|
|
||
| from pydantic import Field | ||
|
|
||
| from nemo_gym.base_resources_server import ( | ||
| BaseResourcesServerConfig, | ||
| BaseVerifyRequest, | ||
| BaseVerifyResponse, | ||
| SimpleResourcesServer, | ||
| ) | ||
|
|
||
|
|
||
| class ToolCallMultiRewardResourcesServerConfig(BaseResourcesServerConfig): | ||
| pass | ||
|
|
||
|
|
||
| class ToolCallMultiRewardVerifyRequest(BaseVerifyRequest): | ||
| # The single tool call the model is expected to make, e.g. | ||
| # {"name": "get_weather", "arguments": {"city": "San Francisco"}}. | ||
| expected_call: Dict[str, Any] = Field(default_factory=dict) | ||
|
|
||
|
|
||
| class ToolCallMultiRewardVerifyResponse(BaseVerifyResponse): | ||
| # Per-component scores are also surfaced as top-level fields so the aggregate | ||
| # metrics endpoint profiles each one in addition to the combined reward. | ||
| # Decoupled per-component rewards (name -> score) for GDPO. NeMo-RL's NeMo Gym | ||
| # bridge reads this from the verify result and exposes the components as reward1, | ||
| # reward2, ... ordered by name. Defined here (not on BaseVerifyResponse) so other | ||
| # environments' verify responses are unchanged. | ||
| reward_components: Dict[str, float] | None = None | ||
| correctness: float = 0.0 | ||
| schema_valid: float = 0.0 | ||
| format: float = 0.0 | ||
| predicted_calls: List[Dict[str, Any]] = Field(default_factory=list) | ||
|
|
||
|
|
||
| class ToolCallMultiRewardResourcesServer(SimpleResourcesServer): | ||
| config: ToolCallMultiRewardResourcesServerConfig | ||
|
|
||
| @staticmethod | ||
| def _parse_arguments(arguments: Any) -> tuple[Dict[str, Any], bool]: | ||
| """Return (parsed_dict, is_valid_json_object).""" | ||
| if isinstance(arguments, dict): | ||
| return arguments, True | ||
| if isinstance(arguments, str): | ||
| try: | ||
| value = json.loads(arguments) | ||
| except json.JSONDecodeError: | ||
| return {}, False | ||
| return (value, True) if isinstance(value, dict) else ({}, False) | ||
| return {}, False | ||
|
|
||
| def _extract_function_calls(self, body: BaseVerifyRequest) -> List[Dict[str, Any]]: | ||
| calls = [] | ||
| for output_item in body.response.output: | ||
| if output_item.type == "function_call": | ||
| calls.append({"name": output_item.name, "arguments": output_item.arguments}) | ||
| return calls | ||
|
|
||
| @staticmethod | ||
| def _has_assistant_text(body: BaseVerifyRequest) -> bool: | ||
| return any(getattr(item, "type", None) == "message" for item in body.response.output) | ||
|
|
||
| def _required_params(self, body: BaseVerifyRequest, tool_name: str) -> List[str]: | ||
| tools = getattr(body.responses_create_params, "tools", None) or [] | ||
| for tool in tools: | ||
| tool_dict = tool if isinstance(tool, dict) else tool.model_dump() | ||
| if tool_dict.get("name") == tool_name: | ||
| return tool_dict.get("parameters", {}).get("required", []) or [] | ||
| return [] | ||
|
|
||
| @staticmethod | ||
| def _call_matches(predicted: Dict[str, Any], expected: Dict[str, Any]) -> bool: | ||
| if not expected: | ||
| return False | ||
| if predicted.get("name") != expected.get("name"): | ||
| return False | ||
| predicted_args, _ = ToolCallMultiRewardResourcesServer._parse_arguments(predicted.get("arguments", {})) | ||
| expected_args = expected.get("arguments", {}) or {} | ||
| for key, value in expected_args.items(): | ||
| if predicted_args.get(key) != value: | ||
| return False | ||
| return True | ||
|
|
||
| async def verify(self, body: ToolCallMultiRewardVerifyRequest) -> ToolCallMultiRewardVerifyResponse: | ||
| predicted_calls = self._extract_function_calls(body) | ||
|
|
||
| # format: exactly one tool call and no extra assistant prose. | ||
| format_score = 1.0 if len(predicted_calls) == 1 and not self._has_assistant_text(body) else 0.0 | ||
|
|
||
| # schema_valid: the first call's arguments are a valid object with all required params. | ||
| schema_score = 0.0 | ||
| if predicted_calls: | ||
| first = predicted_calls[0] | ||
| parsed, is_valid = self._parse_arguments(first["arguments"]) | ||
| required = self._required_params(body, first["name"]) | ||
| schema_score = 1.0 if is_valid and all(k in parsed for k in required) else 0.0 | ||
|
|
||
| # correctness: some predicted call matches the expected name + arguments. | ||
| correctness_score = 1.0 if any(self._call_matches(c, body.expected_call) for c in predicted_calls) else 0.0 | ||
|
|
||
| reward_components = { | ||
| "correctness": correctness_score, | ||
| "schema_valid": schema_score, | ||
| "format": format_score, | ||
| } | ||
|
|
||
| return ToolCallMultiRewardVerifyResponse( | ||
| **body.model_dump(), | ||
| reward=sum(reward_components.values()), | ||
| reward_components=reward_components, | ||
| correctness=correctness_score, | ||
| schema_valid=schema_score, | ||
| format=format_score, | ||
| predicted_calls=[ | ||
| {"name": c["name"], "arguments": self._parse_arguments(c["arguments"])[0]} for c in predicted_calls | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| ToolCallMultiRewardResourcesServer.run_webserver() |
21 changes: 21 additions & 0 deletions
21
resources_servers/tool_call_multireward/configs/tool_call_multireward.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| tool_call_multireward: | ||
| resources_servers: | ||
| tool_call_multireward: | ||
| entrypoint: app.py | ||
| domain: agent | ||
| verified: false | ||
| description: Single tool call scored on decoupled correctness / schema_valid / format rewards (multi-reward, for GDPO) | ||
| tool_call_multireward_simple_agent: | ||
| responses_api_agents: | ||
| simple_agent: | ||
| entrypoint: app.py | ||
| resources_server: | ||
| type: resources_servers | ||
| name: tool_call_multireward | ||
| model_server: | ||
| type: responses_api_models | ||
| name: policy_model | ||
| datasets: | ||
| - name: example | ||
| type: example | ||
| jsonl_fpath: resources_servers/tool_call_multireward/data/example.jsonl | ||
75 changes: 75 additions & 0 deletions
75
resources_servers/tool_call_multireward/create_examples.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import json | ||
|
|
||
| from nemo_gym.openai_utils import ( | ||
| NeMoGymEasyInputMessage, | ||
| NeMoGymResponseCreateParamsNonStreaming, | ||
| ) | ||
|
|
||
|
|
||
| # (user query, expected city argument) | ||
| queries = [ | ||
| ("what's the weather in San Francisco?", "San Francisco"), | ||
| ("how hot is it in New York today?", "New York"), | ||
| ("tell me the forecast for Seattle", "Seattle"), | ||
| ("is it raining in London right now?", "London"), | ||
| ("weather in Tokyo please", "Tokyo"), | ||
| ] | ||
|
|
||
| base_response_create_params = NeMoGymResponseCreateParamsNonStreaming( | ||
| input=[ | ||
| { | ||
| "role": "developer", | ||
| "content": ( | ||
| "You are a helpful assistant. When the user asks about the weather, " | ||
| "respond with exactly one get_weather tool call and no other text." | ||
| ), | ||
| }, | ||
| ], | ||
| tools=[ | ||
| { | ||
| "type": "function", | ||
| "name": "get_weather", | ||
| "description": "Get the current weather for a city.", | ||
| "parameters": { | ||
| "type": "object", | ||
| "properties": { | ||
| "city": { | ||
| "type": "string", | ||
| "description": "The city to get the weather for.", | ||
| }, | ||
| }, | ||
| "required": ["city"], | ||
| "additionalProperties": False, | ||
| }, | ||
| "strict": True, | ||
| } | ||
| ], | ||
| ) | ||
|
|
||
| example_strs = [] | ||
| for query, city in queries: | ||
| example = base_response_create_params.model_copy( | ||
| update={"input": base_response_create_params.input + [NeMoGymEasyInputMessage(role="user", content=query)]} | ||
| ) | ||
| row = { | ||
| "responses_create_params": example.model_dump(exclude_unset=True), | ||
| "expected_call": {"name": "get_weather", "arguments": {"city": city}}, | ||
| } | ||
| example_strs.append(json.dumps(row) + "\n") | ||
|
|
||
|
|
||
| with open("resources_servers/tool_call_multireward/data/example.jsonl", "w") as f: | ||
| f.writelines(example_strs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| *train.jsonl | ||
| *validation.jsonl | ||
| *train_prepare.jsonl | ||
| *validation_prepare.jsonl | ||
| *example_prepare.jsonl |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.