-
Notifications
You must be signed in to change notification settings - Fork 48
Refactor RewardFn #118
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
Merged
Refactor RewardFn #118
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2994bb2
add reward for rm_gallery
hiyuchang f619d8f
add files for several rewards
hiyuchang 517307b
fix pre-premmit
hiyuchang df7273a
fix import
hiyuchang f4d8bbe
fix workflow_test
hiyuchang 2b6c300
add a TODO
hiyuchang d908e48
Merge branch 'main' into dev/rm_factor
hiyuchang 8257684
fix a comment
hiyuchang 6e709c6
add unittest for rm-gallery
hiyuchang cbddf3a
skip rm_gallery test
hiyuchang 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
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 |
|---|---|---|
| @@ -1,11 +1,23 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """Reward functions for RFT""" | ||
|
|
||
| from .reward_fn import REWARD_FUNCTIONS, AccuracyReward, FormatReward, RewardFn | ||
| # isort: off | ||
| from .reward_fn import REWARD_FUNCTIONS, RewardFn, RMGalleryFn | ||
|
|
||
| from .accuracy_reward import AccuracyReward | ||
| from .countdown_reward import CountDownRewardFn | ||
| from .format_reward import FormatReward | ||
| from .math_reward import MathBoxedRewardFn, MathRewardFn | ||
|
|
||
| # isort: on | ||
|
|
||
| __all__ = [ | ||
| "RewardFn", | ||
| "RMGalleryFn", | ||
| "REWARD_FUNCTIONS", | ||
| "AccuracyReward", | ||
| "CountDownRewardFn", | ||
| "FormatReward", | ||
| "MathRewardFn", | ||
| "MathBoxedRewardFn", | ||
| ] |
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 |
|---|---|---|
| @@ -1,33 +1,68 @@ | ||
| from typing import Any, Callable, Dict, List | ||
| # -*- coding: utf-8 -*- | ||
| """Accuracy Reward Function Class.""" | ||
| from typing import Callable, Optional | ||
|
|
||
| from .base import RewardShapper | ||
| from latex2sympy2_extended import NormalizationConfig | ||
| from math_verify import LatexExtractionConfig, parse, verify | ||
|
|
||
| from trinity.common.rewards.reward_fn import REWARD_FUNCTIONS, RewardFn | ||
| from trinity.utils.log import get_logger | ||
|
|
||
| class AccuracyRewardShapper(RewardShapper): | ||
| """Shapper for accuracy-based rewards""" | ||
| logger = get_logger(__name__) | ||
|
|
||
| def __init__( | ||
| self, | ||
| answer_parser: Callable[[str], str], | ||
| correct_reward: float = 1.0, | ||
| incorrect_reward: float = 0.0, | ||
| kwargs: Dict[str, Any] = {}, | ||
| ): | ||
|
|
||
| @REWARD_FUNCTIONS.register_module("accuracy_reward") | ||
| class AccuracyReward(RewardFn): | ||
| """A reward function that rewards correct answers. | ||
| Ref: https://github.com/huggingface/open-r1/blob/main/src/open_r1/rewards.py | ||
| """ | ||
|
|
||
| def __init__(self, answer_parser: Optional[Callable[[str], str]] = None): | ||
| self.answer_parser = answer_parser | ||
| self.correct_reward = correct_reward | ||
| self.incorrect_reward = incorrect_reward | ||
| self.response_key = kwargs.get("response", "response") | ||
| self.truth_key = kwargs.get("ground_truth", "ground_truth") | ||
|
|
||
| def shape(self, sample: Dict[str, Any]) -> Dict[str, Any]: | ||
| response = sample[self.response_key] | ||
| truth = sample[self.truth_key] | ||
| def __call__( # type: ignore | ||
| self, | ||
| response: str, | ||
| prompt: Optional[str] = None, | ||
| truth: Optional[str] = None, | ||
| ) -> dict[str, float]: | ||
| if self.answer_parser: | ||
| answer_parsed = self.answer_parser(response) | ||
| truth_parsed = self.answer_parser(truth) # type: ignore [arg-type] | ||
|
|
||
| parsed_response = self.answer_parser(response) | ||
| reward = self.correct_reward if parsed_response == truth else self.incorrect_reward | ||
| else: | ||
| truth_parsed = parse( | ||
| truth, | ||
| extraction_mode="first_match", | ||
| extraction_config=[LatexExtractionConfig()], | ||
| ) | ||
| if len(truth_parsed) == 0: | ||
| truth_parsed = truth | ||
|
|
||
| sample["accuracy_reward"] = reward | ||
| return sample | ||
| answer_parsed = parse( | ||
| response, | ||
| extraction_config=[ | ||
| LatexExtractionConfig( | ||
| normalization_config=NormalizationConfig( | ||
| nits=False, | ||
| malformed_operators=False, | ||
| basic_latex=True, | ||
| equations=True, | ||
| boxed="all", | ||
| units=True, | ||
| ), | ||
| # Ensures that boxed is tried first | ||
| boxed_match_priority=0, | ||
| try_extract_without_anchor=False, | ||
| ) | ||
| ], | ||
| extraction_mode="first_match", | ||
| ) | ||
|
|
||
| def batch_shape(self, samples: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | ||
| return [self.shape(sample) for sample in samples] | ||
| # Reward 1 if the content is the same as the ground truth, 0 otherwise | ||
| try: | ||
| reward = float(verify(answer_parsed, truth_parsed)) | ||
| except Exception as e: | ||
| logger.info(f"verify failed: {e}, answer: {answer_parsed}, gold: {truth_parsed}") | ||
| reward = 0.0 | ||
| return {"accuracy": reward} |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
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,58 @@ | ||
| """Base Reward Function Class.""" | ||
| import json | ||
| from typing import Optional | ||
|
|
||
| from trinity.common.rewards.reward_fn import REWARD_FUNCTIONS, RewardFn | ||
| from trinity.utils.eval_utils import ( | ||
| evaluate_equation, | ||
| extract_solution, | ||
| validate_equation, | ||
| ) | ||
| from trinity.utils.log import get_logger | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| @REWARD_FUNCTIONS.register_module("countdown_reward") | ||
| class CountDownRewardFn(RewardFn): | ||
| """A reward function that rewards for countdown task. | ||
| Ref: Jiayi-Pan/TinyZero verl/utils/reward_score/countdown.py | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| pass | ||
|
|
||
| def __call__( # type: ignore | ||
| self, | ||
| response: str, | ||
| prompt: Optional[str] = None, | ||
| truth: Optional[str] = None, | ||
| ) -> dict[str, float]: | ||
| truth = json.loads(truth) # type: ignore | ||
| target = truth["target"] # type: ignore | ||
| numbers = truth["numbers"] # type: ignore | ||
|
|
||
| solution_str = response | ||
| equation = extract_solution(solution_str=solution_str) | ||
| format_score = 0.1 | ||
| score = 1.0 | ||
|
|
||
| if equation is None: | ||
| return {"score": 0} | ||
|
|
||
| # Validate equation uses correct numbers | ||
| if not validate_equation(equation, numbers): | ||
| return {"score": format_score} | ||
|
|
||
| # Evaluate equation | ||
| try: | ||
| result = evaluate_equation(equation) | ||
| if result is None: | ||
| return {"score": format_score} | ||
|
|
||
| if abs(result - target) < 1e-5: # Account for floating point precision | ||
| return {"score": score} | ||
| else: | ||
| return {"score": format_score} | ||
| except Exception as e: # noqa: F841 | ||
| return {"score": format_score} |
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 |
|---|---|---|
| @@ -1,29 +1,28 @@ | ||
| import re | ||
| from typing import Any, Dict, List | ||
| """Base Reward Function Class.""" | ||
|
|
||
| from .base import RewardShapper | ||
| import re | ||
| from typing import Optional | ||
|
|
||
| from trinity.common.rewards.reward_fn import REWARD_FUNCTIONS, RewardFn | ||
| from trinity.utils.log import get_logger | ||
|
|
||
| class FormatRewardShapper(RewardShapper): | ||
| """Shapper for format-based rewards""" | ||
| logger = get_logger(__name__) | ||
|
|
||
| def __init__( | ||
| self, pattern: str, correct_format_reward: float = 1.0, incorrect_format_reward: float = 0.0 | ||
| ): | ||
| self.pattern = re.compile(pattern, re.DOTALL | re.MULTILINE) | ||
| self.correct_format_reward = correct_format_reward | ||
| self.incorrect_format_reward = incorrect_format_reward | ||
|
|
||
| def shape(self, sample: Dict[str, Any]) -> Dict[str, Any]: | ||
| response = sample["response"] | ||
| reward = ( | ||
| self.correct_format_reward | ||
| if self.pattern.match(response) | ||
| else self.incorrect_format_reward | ||
| ) | ||
| @REWARD_FUNCTIONS.register_module("format_reward") | ||
| class FormatReward(RewardFn): | ||
| """A reward function that checks if the reasoning process is enclosed within <think> and </think> tags, while the final answer is enclosed within <answer> and </answer> tags. | ||
| Ref: https://github.com/huggingface/open-r1/blob/main/src/open_r1/rewards.py | ||
| """ | ||
|
|
||
| sample["format_reward"] = reward | ||
| return sample | ||
| def __init__(self, pattern: Optional[str] = None): | ||
| self.pattern = pattern if pattern else r"^<think>\n.*?\n</think>\n<answer>\n.*?\n</answer>$" | ||
|
|
||
| def batch_shape(self, samples: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | ||
| return [self.shape(sample) for sample in samples] | ||
| def __call__( # type: ignore | ||
| self, | ||
| response, | ||
| ) -> dict[str, float]: | ||
| if re.match(self.pattern, response, re.DOTALL | re.MULTILINE): | ||
| return {"format_score": 0.1} | ||
| else: | ||
| return {"format_score": -0.1} |
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.