|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Reward Function with Overlong Reward Shaping described in DAPO (https://arxiv.org/pdf/2503.14476)""" |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import torch |
| 6 | + |
| 7 | +from trinity.common.rewards.reward_fn import REWARD_FUNCTIONS, RewardFn |
| 8 | +from trinity.utils.eval_utils import compute_score |
| 9 | +from trinity.utils.log import get_logger |
| 10 | + |
| 11 | +logger = get_logger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +@REWARD_FUNCTIONS.register_module("math_dapo_reward") |
| 15 | +class MathDAPORewardFn(RewardFn): |
| 16 | + """A reward function that follows the definition in DAPO for math task.""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + enable_overlong_penalty: Optional[bool] = None, |
| 21 | + penalty_factor: Optional[float] = None, |
| 22 | + max_response_length: Optional[int] = None, |
| 23 | + cache_length: Optional[int] = None, |
| 24 | + ) -> None: |
| 25 | + self.enable_overlong_penalty = enable_overlong_penalty |
| 26 | + self.penalty_factor = penalty_factor |
| 27 | + self.max_response_length = max_response_length |
| 28 | + self.cache_length = cache_length |
| 29 | + |
| 30 | + def __call__( # type: ignore |
| 31 | + self, |
| 32 | + response: str, |
| 33 | + response_token: torch.Tensor, |
| 34 | + truth: Optional[str] = None, |
| 35 | + **kwargs, |
| 36 | + ) -> dict[str, float]: |
| 37 | + accuracy_score = compute_score(response, truth) |
| 38 | + |
| 39 | + format_score = 0.0 |
| 40 | + |
| 41 | + if self.enable_overlong_penalty: |
| 42 | + format_score = self.compute_overlong_penalty(response_token) |
| 43 | + |
| 44 | + return { |
| 45 | + "accuracy": accuracy_score, |
| 46 | + "format_score": format_score, |
| 47 | + } |
| 48 | + |
| 49 | + def compute_overlong_penalty(self, response_token): |
| 50 | + assert ( |
| 51 | + self.max_response_length is not None |
| 52 | + and self.cache_length is not None |
| 53 | + and self.penalty_factor is not None |
| 54 | + ), "When enable_overlong_penalty = true, max_response_length, penalty_factor, cache_length must be set" |
| 55 | + assert ( |
| 56 | + self.max_response_length > self.cache_length |
| 57 | + ), "max_response_length must be greater than cache_length" |
| 58 | + |
| 59 | + response_len = len(response_token) |
| 60 | + excepted_len = self.max_response_length - self.cache_length |
| 61 | + |
| 62 | + if response_len < excepted_len: |
| 63 | + return 0.0 |
| 64 | + elif response_len > self.max_response_length: |
| 65 | + return -self.penalty_factor |
| 66 | + else: |
| 67 | + return (excepted_len - response_len) / self.cache_length * self.penalty_factor |
0 commit comments