|
| 1 | +from typing import Tuple, Optional, List, Dict |
| 2 | +from easydict import EasyDict |
| 3 | +from torch.utils.tensorboard import SummaryWriter |
| 4 | +from transformers import AutoTokenizer |
| 5 | +import re |
| 6 | + |
| 7 | +from ding.utils import REWARD_MODEL_REGISTRY |
| 8 | +from .base_reward_model import BaseRewardModel |
| 9 | + |
| 10 | + |
| 11 | +@REWARD_MODEL_REGISTRY.register('math_rule') |
| 12 | +class MathRuleRewardModel(BaseRewardModel): |
| 13 | + config = dict( |
| 14 | + # (str) The type of the reward model. |
| 15 | + type='math_rule', |
| 16 | + # (str) The name of the dataset, usually the huggingface dataset name. |
| 17 | + dataset_name='', |
| 18 | + # (str) The name of the tokenizer, usually the huggingface tokenizer name. |
| 19 | + tokenizer_name='', |
| 20 | + # (float) The score of format error. |
| 21 | + format_error_reward=-2, |
| 22 | + # (float) The score of answer error. |
| 23 | + answer_error_reward=-1, |
| 24 | + # (float) The score of correct. |
| 25 | + correct_reward=1, |
| 26 | + ) |
| 27 | + |
| 28 | + def __init__(self, config: EasyDict, device: str, logger, tb_logger: 'SummaryWriter') -> None: # noqa |
| 29 | + self.cfg = config |
| 30 | + self.device = device |
| 31 | + self.logger = logger |
| 32 | + self.tb_logger = tb_logger |
| 33 | + |
| 34 | + def estimate(self, data: List[str]) -> List[Dict]: |
| 35 | + """ |
| 36 | + Arguments: |
| 37 | + - data (:obj:`List[str]`): The list of data queries used for estimation, each query is a string of the \ |
| 38 | + form "1 + 1 = ?" |
| 39 | + Returns: |
| 40 | + - reward (:obj:`List[Dict]`): The estimated reward. |
| 41 | + """ |
| 42 | + # 1. parse the query to get question and predicted answer |
| 43 | + # 2. get the ground truth answer according to the question |
| 44 | + # 3. calculate the reward based on the predicted answer and the ground truth answer (format error -2, answer error -1, correct 1) |
| 45 | + pass |
| 46 | + |
| 47 | + # rule-based reward model does not need training, thus the following methods are empty |
| 48 | + def train(self): |
| 49 | + pass |
| 50 | + |
| 51 | + def collect_data(self, data: list) -> None: |
| 52 | + pass |
| 53 | + |
| 54 | + def clear_data(self) -> None: |
| 55 | + pass |
| 56 | + |
| 57 | + |
| 58 | +def strip_sequence(text: str, pad_token: str, eos_token: str) -> str: |
| 59 | + """ |
| 60 | + Overview: |
| 61 | + Remove leading and trailing sequences of padding/eos tokens from a text. |
| 62 | +
|
| 63 | + .. note:: |
| 64 | + This function uses regular expressions to strip all consecutive occurrences |
| 65 | + of the specified padding and end-of-sequence tokens from both the beginning |
| 66 | + and end of the input text. Tokens in the middle of the text are preserved. |
| 67 | +
|
| 68 | + Arguments: |
| 69 | + - text (str): The input text to be processed. |
| 70 | + - pad_token (str): The padding token to be stripped (e.g., "<PAD>"). |
| 71 | + - eos_token (str): The end-of-sequence token to be stripped (e.g., "<EOS>"). |
| 72 | +
|
| 73 | + Returns: |
| 74 | + - cleaned_text (str): The cleaned text with leading/trailing padding/eos tokens removed. |
| 75 | +
|
| 76 | + Examples: |
| 77 | + >>> strip_sequence("<PAD><EOS>Hello<EOS><PAD>", "<PAD>", "<EOS>") |
| 78 | + 'Hello' |
| 79 | +
|
| 80 | + >>> strip_sequence("Test<EOS>Middle<PAD>Keep", "<PAD>", "<EOS>") |
| 81 | + 'Test<EOS>Middle<PAD>Keep' |
| 82 | +
|
| 83 | + >>> strip_sequence("<EOS><EOS><PAD>Full removal<PAD><EOS>", "<PAD>", "<EOS>") |
| 84 | + 'Full removal' |
| 85 | +
|
| 86 | + >>> strip_sequence("No tokens here", "<PAD>", "<EOS>") |
| 87 | + 'No tokens here' |
| 88 | +
|
| 89 | + >>> strip_sequence("<PAD><PAD>", "<PAD>", "<EOS>") |
| 90 | + '' |
| 91 | + """ |
| 92 | + pad_token_escaped = re.escape(pad_token) |
| 93 | + eos_token_escaped = re.escape(eos_token) |
| 94 | + |
| 95 | + # Remove leading tokens |
| 96 | + pattern = f"^({eos_token_escaped}|{pad_token_escaped})+" |
| 97 | + text = re.sub(pattern, "", text) |
| 98 | + |
| 99 | + # Remove trailing tokens |
| 100 | + pattern = f"({eos_token_escaped}|{pad_token_escaped})+$" |
| 101 | + text = re.sub(pattern, "", text) |
| 102 | + return text |
| 103 | + |
| 104 | + |
| 105 | +def normalize_text(text: str) -> str: |
| 106 | + """ |
| 107 | + Overview: |
| 108 | + This function is designed to standardize text by: |
| 109 | + - Converting all text to lowercase |
| 110 | + - Replacing various punctuation marks and special characters with spaces |
| 111 | + - Removing import statements |
| 112 | + - Normalizing whitespace by replacing multiple spaces with a single space |
| 113 | + - Stripping leading and trailing whitespace |
| 114 | + Arguments: |
| 115 | + - text (str): The input text to be processed. |
| 116 | + Returns: |
| 117 | + - normalized_text (str): The normalized text. |
| 118 | + """ |
| 119 | + text = re.sub("[,.:\"'\[\]\-=\+\\|!@#$%^&*();<>?/!¥…()—\{\}:”“《》?]", " ", text.lower()) |
| 120 | + text = re.sub("import\s[a-zA-Z\.]+(\sas\s[a-zA-Z\.]+)\n", " ", text) |
| 121 | + text = re.sub("\s+", " ", text) |
| 122 | + return text.strip() |
0 commit comments