-
Notifications
You must be signed in to change notification settings - Fork 4.6k
[feat] Add multi-turn format checking reward managers with refactored… #4593
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
Closed
albertimff
wants to merge
1
commit into
verl-project:release/v0.6.1
from
albertimff:releasev0.6.1_multiturn_format_check_reward_manager
Closed
Changes from all commits
Commits
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
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,32 @@ | ||
| # Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # 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 numpy as np | ||
|
|
||
| from verl import DataProto | ||
| from verl.experimental.reward.reward_loop import register | ||
| from verl.utils.format_reward import apply_format_reward_to_score | ||
| from verl.experimental.reward.reward_loop.dapo import DAPORewardLoopManager | ||
|
|
||
|
|
||
| @register("format_check_dapo") | ||
| class FormatCheckDAPORewardLoopManager(DAPORewardLoopManager): | ||
| """Reward loop that validates assistant message formatting and adds it to DAPO reward.""" | ||
|
|
||
| def __init__(self, config, tokenizer, compute_score=None, reward_router_address=None, reward_model_tokenizer=None): | ||
| super().__init__(config, tokenizer, compute_score, reward_router_address, reward_model_tokenizer) | ||
|
|
||
| async def run_single(self, data: DataProto) -> dict: | ||
| base_result = await super().run_single(data) | ||
| return apply_format_reward_to_score(data[0], base_result) |
30 changes: 30 additions & 0 deletions
30
verl/experimental/reward/reward_loop/format_check_naive.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,30 @@ | ||
| # Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # 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. | ||
|
|
||
| from verl import DataProto | ||
| from verl.experimental.reward.reward_loop import register | ||
| from verl.utils.format_reward import apply_format_reward_to_score | ||
| from verl.experimental.reward.reward_loop.naive import NaiveRewardLoopManager | ||
|
|
||
|
|
||
| @register("format_check_naive") | ||
| class FormatCheckNaiveRewardLoopManager(NaiveRewardLoopManager): | ||
| """Naive reward loop with additional format reward.""" | ||
|
|
||
| def __init__(self, config, tokenizer, compute_score=None, reward_router_address=None, reward_model_tokenizer=None): | ||
| super().__init__(config, tokenizer, compute_score, reward_router_address, reward_model_tokenizer) | ||
|
|
||
| async def run_single(self, data: DataProto) -> dict: | ||
| base_result = await super().run_single(data) | ||
| return apply_format_reward_to_score(data[0], base_result) |
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,110 @@ | ||
| # Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # 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 re | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
| from verl import DataProto | ||
|
|
||
| __all__ = [ | ||
| "compute_format_reward", | ||
| "apply_format_reward_to_score", | ||
| "apply_format_reward_to_tensor", | ||
| ] | ||
|
|
||
| # Note: | ||
| # "You can define what the 'assistant' message format should be by modifying the patterns and logic in this file. | ||
| # For example, the current implementation enforces that each assistant message must match a sequence of tags such as | ||
| # <thinking>...</thinking> followed by either <tool_call>...</tool_call> or <answer>...</answer> (see regex patterns below). | ||
| # Adjust or extend these patterns as needed to adapt to different formatting requirements." | ||
|
|
||
| def _extract_messages(messages_obj: Any) -> list[dict[str, Any]] | None: | ||
| """Normalize messages to a list of dicts.""" | ||
| if messages_obj is None: | ||
| return None | ||
| if isinstance(messages_obj, np.ndarray): | ||
| try: | ||
| messages_obj = messages_obj.item() | ||
| except ValueError: | ||
| messages_obj = messages_obj.tolist() | ||
| if isinstance(messages_obj, list): | ||
| return messages_obj | ||
| return None | ||
|
|
||
|
|
||
| def compute_format_reward(messages_obj: Any) -> tuple[float, dict[str, Any]]: | ||
| """Compute a format reward (+0.5 / -0.5) without attaching verbose metadata.""" | ||
| messages = _extract_messages(messages_obj) | ||
| if messages is None: | ||
| return -0.5, {} | ||
|
|
||
| assistant_contents = [] | ||
| for msg in messages: | ||
| if isinstance(msg, dict) and msg.get("role") == "assistant": | ||
| assistant_contents.append(str(msg.get("content", ""))) | ||
|
|
||
| if not assistant_contents: | ||
| return -0.5, {} | ||
|
|
||
| # Allow 0, 1, or 2 line breaks between </thinking> and the subsequent tag, | ||
| # to flexibly accept tight, single line, or double line formatting. | ||
| tool_pattern = re.compile( | ||
| r"^<thinking>.*?</thinking>\n{0,2}<tool_call>.*?</tool_call>$", re.DOTALL | ||
| ) | ||
| answer_pattern = re.compile( | ||
| r"^<thinking>.*?</thinking>\n{0,2}<answer>.*?</answer>$", re.DOTALL | ||
| ) | ||
|
|
||
| for idx, content in enumerate(assistant_contents): | ||
| is_last = idx == len(assistant_contents) - 1 | ||
| expected_pattern = answer_pattern if is_last else tool_pattern | ||
| if not expected_pattern.match(content): | ||
| return -0.5, {} | ||
|
|
||
| return 0.5, {} | ||
|
|
||
|
|
||
| def apply_format_reward_to_score(data_item: DataProto, base_result: dict) -> dict: | ||
| """Add format reward to a scalar reward score result.""" | ||
| messages = data_item.non_tensor_batch["tool_extra_fields"].get("messages") | ||
| format_reward, _ = compute_format_reward(messages) | ||
|
|
||
| reward_score = base_result["reward_score"] + format_reward | ||
| reward_extra_info = dict(base_result.get("reward_extra_info", {})) | ||
| reward_extra_info["format_reward"] = format_reward | ||
|
|
||
| return {"reward_score": reward_score, "reward_extra_info": reward_extra_info} | ||
|
|
||
|
|
||
| def apply_format_reward_to_tensor(data: DataProto, reward_tensor, reward_extra_info): | ||
| """Add format reward to the final token reward in a tensor and log extra info.""" | ||
| if "format_reward" not in reward_extra_info: | ||
| reward_extra_info["format_reward"] = [] | ||
|
|
||
| for i in range(len(data)): | ||
| data_item = data[i] | ||
| prompt_ids = data_item.batch["prompts"] | ||
| prompt_length = prompt_ids.shape[-1] | ||
| valid_response_length = data_item.batch["attention_mask"][prompt_length:].sum() | ||
|
|
||
| messages = data_item.non_tensor_batch["tool_extra_fields"].get("messages") | ||
| format_reward, _ = compute_format_reward(messages) | ||
|
|
||
| if valid_response_length > 0: | ||
| reward_tensor[i, valid_response_length - 1] += format_reward | ||
|
|
||
| reward_extra_info["format_reward"].append(format_reward) | ||
|
|
||
| return reward_tensor, reward_extra_info | ||
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,47 @@ | ||
| # Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # 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. | ||
|
|
||
| from collections import defaultdict | ||
|
|
||
| from verl.utils.format_reward import apply_format_reward_to_tensor | ||
| from verl.workers.reward_manager import register | ||
| from verl.workers.reward_manager.dapo import DAPORewardManager | ||
|
|
||
|
|
||
| @register("format_check_dapo") | ||
| class FormatCheckDAPORewardManager(DAPORewardManager): | ||
| """DAPO reward manager with an extra formatting bonus/penalty.""" | ||
|
|
||
| def __call__(self, data, return_dict=False): | ||
| if "rm_scores" in data.batch.keys(): | ||
| if return_dict: | ||
| reward_extra_keys = data.meta_info.get("reward_extra_keys", []) | ||
| reward_extra_info = {key: data.non_tensor_batch[key] for key in reward_extra_keys} | ||
| return {"reward_tensor": data.batch["rm_scores"], "reward_extra_info": reward_extra_info} | ||
| else: | ||
| return data.batch["rm_scores"] | ||
|
|
||
| base_result = super().__call__(data, return_dict=True) | ||
| reward_tensor = base_result["reward_tensor"] | ||
|
|
||
| base_extra_info = base_result.get("reward_extra_info", {}) | ||
| reward_extra_info = defaultdict(list, base_extra_info) | ||
|
|
||
| reward_tensor, reward_extra_info = apply_format_reward_to_tensor( | ||
| data, reward_tensor, reward_extra_info | ||
| ) | ||
|
|
||
| if return_dict: | ||
| return {"reward_tensor": reward_tensor, "reward_extra_info": reward_extra_info} | ||
| return reward_tensor |
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,47 @@ | ||
| # Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # 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. | ||
|
|
||
| from collections import defaultdict | ||
|
|
||
| from verl.utils.format_reward import apply_format_reward_to_tensor | ||
| from verl.workers.reward_manager import register | ||
| from verl.workers.reward_manager.naive import NaiveRewardManager | ||
|
|
||
|
|
||
| @register("format_check_naive") | ||
| class FormatCheckNaiveRewardManager(NaiveRewardManager): | ||
| """Naive reward manager with an extra formatting bonus/penalty.""" | ||
|
|
||
| def __call__(self, data, return_dict=False): | ||
| if "rm_scores" in data.batch.keys(): | ||
| if return_dict: | ||
| reward_extra_keys = data.meta_info.get("reward_extra_keys", []) | ||
| reward_extra_info = {key: data.non_tensor_batch[key] for key in reward_extra_keys} | ||
| return {"reward_tensor": data.batch["rm_scores"], "reward_extra_info": reward_extra_info} | ||
| else: | ||
| return data.batch["rm_scores"] | ||
|
|
||
| base_result = super().__call__(data, return_dict=True) | ||
| reward_tensor = base_result["reward_tensor"] | ||
|
|
||
| base_extra_info = base_result.get("reward_extra_info", {}) | ||
| reward_extra_info = defaultdict(list, base_extra_info) | ||
|
|
||
| reward_tensor, reward_extra_info = apply_format_reward_to_tensor( | ||
| data, reward_tensor, reward_extra_info | ||
| ) | ||
|
|
||
| if return_dict: | ||
| return {"reward_tensor": reward_tensor, "reward_extra_info": reward_extra_info} | ||
| return reward_tensor |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation for format validation using
expected_pattern.match(content)is sensitive to any leading or trailing whitespace in the assistant's messagecontent. Language models can sometimes generate extraneous whitespace, which would cause an otherwise correctly formatted message to fail validation and receive an incorrect penalty. This could negatively impact the training process by providing wrong reward signals.To improve the robustness of the format check, I recommend stripping whitespace from the
contentbefore applying the regular expression match.