|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import torch |
| 8 | +from tensordict.tensorclass import NonTensorData, NonTensorStack |
| 9 | +from torchrl.envs import Transform |
| 10 | +from torchrl.data import Composite, TensorSpec, Unbounded |
| 11 | +from tensordict.utils import _zip_strict |
| 12 | +from tensordict import TensorDictBase, TensorDict |
| 13 | +from tensordict import NestedKey |
| 14 | +BASE_PROMPT = ( |
| 15 | + "A conversation between User and Assistant. The user asks a question, and the Assistant solves it. " |
| 16 | + "The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " |
| 17 | + "The reasoning process and answer are enclosed within <think></think> and <answer></answer> tags, respectively, " |
| 18 | + "i.e., <think>reasoning process here</think> <answer>answer here</answer>. User: %s. Assistant: <think>" |
| 19 | +) |
| 20 | + |
| 21 | +class PrepareQuestion(Transform): |
| 22 | + def __init__(self, in_keys: list[NestedKey] | None = None, out_keys: list[NestedKey] | None = None): |
| 23 | + if in_keys is None: |
| 24 | + in_keys = ["text"] |
| 25 | + if out_keys is None: |
| 26 | + out_keys = list(in_keys) |
| 27 | + super().__init__(in_keys, out_keys) |
| 28 | + |
| 29 | + def _reset_env_preprocess(self, tensordict: TensorDictBase) -> TensorDictBase: |
| 30 | + for in_key, out_key in _zip_strict(self.in_keys, self.out_keys): |
| 31 | + string = tensordict.get(in_key) |
| 32 | + tensordict.set(out_key, self._modify_str(string)) |
| 33 | + return tensordict |
| 34 | + |
| 35 | + def _modify_str(self, obs: str | list[str] | NonTensorData | NonTensorStack) -> NonTensorData | NonTensorStack: |
| 36 | + if isinstance(obs, NonTensorData): |
| 37 | + return self._modify_str(obs.data) |
| 38 | + if isinstance(obs, NonTensorStack): |
| 39 | + return self._modify_str(obs.tolist()) |
| 40 | + if isinstance(obs, list): |
| 41 | + return NonTensorStack( |
| 42 | + *[BASE_PROMPT % obs for obs in obs] |
| 43 | + ) |
| 44 | + return NonTensorData(BASE_PROMPT % obs) |
| 45 | + |
| 46 | + def _apply_transform(self, obs: torch.Tensor) -> None: |
| 47 | + return obs |
| 48 | + def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec: |
| 49 | + for in_key, out_key in _zip_strict(self.in_keys, self.out_keys): |
| 50 | + if out_key != in_key: |
| 51 | + observation_spec[out_key] = observation_spec[in_key].clone() |
| 52 | + return observation_spec |
| 53 | + |
| 54 | +class ShapedCorrectnessReward(Transform): |
| 55 | + def __init__(self, tokenizer, in_keys: list[NestedKey] | None=None, out_keys: list[NestedKey] | None = None): |
| 56 | + super().__init__() |
| 57 | + self.tokenizer = tokenizer |
| 58 | + if in_keys is None: |
| 59 | + in_keys = ["text", "answer"] |
| 60 | + if not isinstance(in_keys, list) or len(in_keys) != 2: |
| 61 | + raise ValueError("ShapedCorrectnessReward requires in_keys to be of type list and have 2 elements.") |
| 62 | + if out_keys is None: |
| 63 | + out_keys = ["reward_answer", "reward_think", "reward_right", "reward_contained", "reward", "success"] |
| 64 | + super().__init__(in_keys, out_keys) |
| 65 | + |
| 66 | + def _step( |
| 67 | + self, tensordict: TensorDictBase, next_tensordict: TensorDictBase |
| 68 | + ) -> TensorDictBase: |
| 69 | + from xml.etree import ElementTree as ET |
| 70 | + # Get the completion |
| 71 | + responses = next_tensordict[self.in_keys[0]] # batch_size, grpo_size, L |
| 72 | + answers = next_tensordict[self.in_keys[1]] # batch_size, grpo_size |
| 73 | + if isinstance(responses, torch.Tensor): |
| 74 | + if responses.ndim == 3: |
| 75 | + batch_size, grpo_size, _ = responses.shape |
| 76 | + # decode |
| 77 | + text_completion = self.tokenizer.decode( |
| 78 | + responses.flatten(0, 1).tolist() |
| 79 | + ) |
| 80 | + else: |
| 81 | + text_completion = responses |
| 82 | + # Decomposed reward |
| 83 | + tds = [] |
| 84 | + for answer, compl in zip(answers, text_completion): |
| 85 | + try: |
| 86 | + cot, potential_answer = self.extract_tags("<think>" + compl) #.replace("<<", "").replace(">>", "")) |
| 87 | + except ET.ParseError: |
| 88 | + cot, potential_answer = ("", "") |
| 89 | + tds.append(self.single_shaped_correctness_reward(potential_answer, cot)) |
| 90 | + tds = torch.stack(tds) |
| 91 | + if isinstance(responses, torch.Tensor) and responses.ndim == 3: |
| 92 | + tds = tds.reshape(batch_size, grpo_size) |
| 93 | + tds = tds.apply(lambda t: t.unsqueeze(-1)) |
| 94 | + return next_tensordict.update(tds) |
| 95 | + |
| 96 | + def transform_reward_spec(self, reward_spec: Composite) -> Composite: |
| 97 | + shape = reward_spec.shape + (1,) |
| 98 | + reward_spec.update(Composite( |
| 99 | + reward_answer=Unbounded(shape), |
| 100 | + reward_think=Unbounded(shape), |
| 101 | + reward_right=Unbounded(shape), |
| 102 | + reward_contained=Unbounded(shape), |
| 103 | + reward=Unbounded(shape), |
| 104 | + success=Unbounded(shape, dtype=torch.bool), |
| 105 | + )) |
| 106 | + return reward_spec |
| 107 | + |
| 108 | + @classmethod |
| 109 | + def single_shaped_correctness_reward(cls, answer: str, cot: str) -> TensorDict: |
| 110 | + |
| 111 | + reward_answer = 5.0 * (len(answer) == 1) |
| 112 | + |
| 113 | + reward_think = 5.0 * (len(cot) == 1) |
| 114 | + |
| 115 | + # One of the answer tags has the right answer |
| 116 | + reward_right = 20.0 * (any(attempt == answer for attempt in answer)) |
| 117 | + |
| 118 | + # One of the answer tags contains the right answer (might be e.g. $20 instead of 20) |
| 119 | + reward_contained = 10.0 * (any((answer in attempt) for attempt in answer)) |
| 120 | + |
| 121 | + success = len(answer) > 0 and answer[-1] == answer |
| 122 | + # Compose the rewards |
| 123 | + reward = 100.0 * float(success) + (reward_answer + reward_think + reward_contained + reward_right) * (1- float(success)) |
| 124 | + |
| 125 | + rewards = TensorDict( |
| 126 | + reward_answer=reward_answer, |
| 127 | + reward_think=reward_think, |
| 128 | + reward_right=reward_right, |
| 129 | + reward_contained=reward_contained, |
| 130 | + reward=reward, |
| 131 | + success=success, |
| 132 | + ) |
| 133 | + return rewards |
| 134 | + |
| 135 | + @staticmethod |
| 136 | + def extract_tags(text: str) -> Tuple[str, str]: |
| 137 | + """ |
| 138 | + Parse XML-like tags from text. Returns a dictionary with keys 'think' and 'answer'. |
| 139 | + The values are lists of strings, with each string being the content of a tag. |
| 140 | + """ |
| 141 | + from xml.etree import ElementTree as ET |
| 142 | + |
| 143 | + xml_string = f"<root>{text}</root>" |
| 144 | + try: |
| 145 | + root = ET.fromstring(xml_string) |
| 146 | + except ET.ParseError as e: |
| 147 | + return ("", "") |
| 148 | + |
| 149 | + return ( |
| 150 | + root.find("think").text if root.find("think") is not None else "", |
| 151 | + root.find("answer").text if root.find("answer") is not None else "", |
| 152 | + ) |
0 commit comments