|
| 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 | +from collections.abc import Callable |
| 8 | +from typing import Any, Literal, TYPE_CHECKING |
| 9 | + |
| 10 | +import torch |
| 11 | +from tensordict import TensorDict |
| 12 | +from torchrl.envs import StepCounter |
| 13 | +from torchrl.envs.llm.chat import DatasetChatEnv |
| 14 | +from torchrl.envs.llm.reward.math import MATHRewardParser |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + import transformers |
| 18 | + |
| 19 | + |
| 20 | +def _collate_fn(batch): |
| 21 | + batch = torch.stack([TensorDict.from_dict(_batch) for _batch in batch]) |
| 22 | + batch.rename_key_("problem", "query") |
| 23 | + batch.rename_key_("solution", "answer") |
| 24 | + return batch |
| 25 | + |
| 26 | + |
| 27 | +class MATHEnv(DatasetChatEnv): |
| 28 | + r"""MATH (competition mathematics) dataset environment. |
| 29 | +
|
| 30 | + Uses the ``DigitalLearningGmbH/MATH-lighteval`` dataset on Hugging Face |
| 31 | + (a drop-in replacement for the original ``hendrycks/competition_math``). |
| 32 | +
|
| 33 | + Answers are in LaTeX ``\boxed{}`` format. When ``math-verify`` is |
| 34 | + installed the reward parser uses symbolic equivalence checking; otherwise |
| 35 | + it falls back to normalised string comparison. |
| 36 | +
|
| 37 | + Keyword Args: |
| 38 | + dataset (str, optional): HuggingFace dataset name. |
| 39 | + Defaults to ``"DigitalLearningGmbH/MATH-lighteval"``. |
| 40 | + shuffle (bool, optional): Shuffle the dataset. Defaults to ``True``. |
| 41 | + num_envs (int, optional): Number of parallel envs. Defaults to ``1``. |
| 42 | + repeats (int | None, optional): Repeats per sample for MC estimation. |
| 43 | + batch_size_dl (int, optional): Dataloader batch size. Defaults to ``1``. |
| 44 | + seed (int | None, optional): Random seed. |
| 45 | + group_repeats (bool, optional): Group repeated samples. Defaults to ``False``. |
| 46 | + tokenizer: Tokenizer for text processing. |
| 47 | + device: Device for computation. |
| 48 | + template_kwargs: Extra kwargs for ``apply_chat_template``. |
| 49 | + apply_template (bool): Apply chat template. Defaults to ``False``. |
| 50 | + compute_reward (bool): Compute rewards. Defaults to ``True``. |
| 51 | + collate_fn: Custom collate function. |
| 52 | + max_steps (int): Max steps per episode. Defaults to ``1``. |
| 53 | + input_mode: ``"history"``, ``"text"``, or ``"tokens"``. |
| 54 | + ray_backend (bool): Use Ray backend for data loading. |
| 55 | + dataloader_actor_name (str): Ray actor name for data loading. |
| 56 | +
|
| 57 | + Examples: |
| 58 | + >>> import transformers |
| 59 | + >>> from torchrl.envs.llm.datasets.math import MATHEnv |
| 60 | + >>> tokenizer = transformers.AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B") |
| 61 | + >>> env = MATHEnv(tokenizer=tokenizer, apply_template=True) |
| 62 | + >>> r = env.reset() |
| 63 | + >>> assert "history" in r |
| 64 | +
|
| 65 | + """ |
| 66 | + |
| 67 | + SYSTEM_PROMPT = ( |
| 68 | + "A conversation between User and Assistant. The user asks a math problem, " |
| 69 | + "and the Assistant solves it.\n" |
| 70 | + "The assistant first thinks about the reasoning process in the mind and " |
| 71 | + "then provides the user with the answer.\n" |
| 72 | + "The reasoning process and answer are enclosed within <think></think> and " |
| 73 | + "<answer></answer> tags, respectively, i.e.,\n" |
| 74 | + "<think>reasoning process here</think> <answer>answer here</answer>.\n" |
| 75 | + "The answer should be a mathematical expression (use LaTeX if needed)." |
| 76 | + ) |
| 77 | + |
| 78 | + def __init__( |
| 79 | + self, |
| 80 | + *, |
| 81 | + dataset: str = "DigitalLearningGmbH/MATH-lighteval", |
| 82 | + shuffle: bool = True, |
| 83 | + num_envs: int = 1, |
| 84 | + repeats: int | None = None, |
| 85 | + batch_size_dl: int = 1, |
| 86 | + seed: int | None = None, |
| 87 | + group_repeats: bool = False, |
| 88 | + tokenizer: transformers.AutoTokenizer | None = None, # noqa |
| 89 | + device: torch.device | None = None, |
| 90 | + template_kwargs: dict[str, Any] | None = None, |
| 91 | + apply_template: bool | None = False, |
| 92 | + compute_reward: bool = True, |
| 93 | + collate_fn: Callable | None = None, |
| 94 | + max_steps: int = 1, |
| 95 | + input_mode: Literal["history", "text", "tokens"] = "history", |
| 96 | + ray_backend: bool = False, |
| 97 | + dataloader_actor_name: str | None = None, |
| 98 | + ): |
| 99 | + if ray_backend and dataloader_actor_name is None: |
| 100 | + dataloader_actor_name = "math_dataloader" |
| 101 | + if collate_fn is None: |
| 102 | + collate_fn = _collate_fn |
| 103 | + super().__init__( |
| 104 | + dataset=dataset, |
| 105 | + shuffle=shuffle, |
| 106 | + num_envs=num_envs, |
| 107 | + repeats=repeats, |
| 108 | + batch_size_dl=batch_size_dl, |
| 109 | + seed=seed, |
| 110 | + group_repeats=group_repeats, |
| 111 | + tokenizer=tokenizer, |
| 112 | + device=device, |
| 113 | + template_kwargs=template_kwargs, |
| 114 | + apply_template=apply_template, |
| 115 | + collate_fn=collate_fn, |
| 116 | + input_mode=input_mode, |
| 117 | + ray_backend=ray_backend, |
| 118 | + dataloader_actor_name=dataloader_actor_name, |
| 119 | + ) |
| 120 | + if max_steps: |
| 121 | + self.append_transform(StepCounter(max_steps=max_steps)) |
| 122 | + if compute_reward: |
| 123 | + self.append_transform(MATHRewardParser(tokenizer=tokenizer)) |
0 commit comments