gsm8k.py 4.75 KB
Newer Older
Jonathan Tow's avatar
Jonathan Tow committed
1
2
3
4
"""
"Training Verifiers to Solve Math Word Problems"
https://arxiv.org/abs/2110.14168

Fabrizio Milo's avatar
Fabrizio Milo committed
5
6
State-of-the-art language models can match human performance on many tasks, but
they still struggle to robustly perform multi-step mathematical reasoning. To
7
8
diagnose the failures of current models and support research, we introduce GSM8K,
a dataset of 8.5K high quality linguistically diverse grade school math word problems.
Fabrizio Milo's avatar
Fabrizio Milo committed
9
We find that even the largest transformer models fail to achieve high test performance,
10
11
despite the conceptual simplicity of this problem distribution.

Fabrizio Milo's avatar
Fabrizio Milo committed
12
NOTE: See the official implementation of the task:
13
14
15
16
17
    https://github.com/openai/grade-school-math/blob/master/grade_school_math/calculator.py
for how to make use of the dataset's calculator annotations in your language
model's sample/generation function.

Homepage: https://github.com/openai/grade-school-math
18
19
"""
import re
20
from lm_eval.api.task import Task, register_task
haileyschoelkopf's avatar
haileyschoelkopf committed
21
from lm_eval.api.instance import Instance
22
23
24
25
from lm_eval.api.metrics import mean

from lm_eval import utils
from lm_eval.prompts import get_prompt
26

27
28

_CITATION = """
Jonathan Tow's avatar
Jonathan Tow committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@misc{cobbe2021training,
      title={Training Verifiers to Solve Math Word Problems},
      author={Karl Cobbe and Vineet Kosaraju and Mohammad Bavarian and Jacob Hilton and Reiichiro Nakano and Christopher Hesse and John Schulman},
      year={2021},
      eprint={2110.14168},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
"""


ANS_RE = re.compile(r"#### (\-?[0-9\.\,]+)")
INVALID_ANS = "[invalid]"


44
@register_task("gsm8k")
Jonathan Tow's avatar
Jonathan Tow committed
45
46
class GradeSchoolMath8K(Task):
    VERSION = 0
47
48
    DATASET_PATH = "gsm8k"
    DATASET_NAME = "main"
Jonathan Tow's avatar
Jonathan Tow committed
49

50
51
    OUTPUT_TYPE = "greedy_until"

Jonathan Tow's avatar
Jonathan Tow committed
52
53
54
55
56
57
58
59
60
61
    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return False

    def has_test_docs(self):
        return True

    def training_docs(self):
Jonathan Tow's avatar
Jonathan Tow committed
62
        return self.dataset["train"]
Jonathan Tow's avatar
Jonathan Tow committed
63
64
65
66
67

    def validation_docs(self):
        raise NotImplementedError

    def test_docs(self):
Jonathan Tow's avatar
Jonathan Tow committed
68
        return self.dataset["test"]
Jonathan Tow's avatar
Jonathan Tow committed
69
70

    def doc_to_text(self, doc):
71
72
73
        doc_to_text = get_prompt("qa-basic:question-newline-answer")
        return utils.apply_template(doc_to_text, doc)
        # return "Question: " + doc["question"] + "\nAnswer:"
Jonathan Tow's avatar
Jonathan Tow committed
74
75

    def doc_to_target(self, doc):
Fabrizio Milo's avatar
Fabrizio Milo committed
76
        return " " + doc["answer"]
Jonathan Tow's avatar
Jonathan Tow committed
77

78
    def construct_requests(self, doc, ctx, **kwargs):
Fabrizio Milo's avatar
Fabrizio Milo committed
79
        """Uses RequestFactory to construct Requests and returns an iterable of
Jonathan Tow's avatar
Jonathan Tow committed
80
81
82
83
84
85
86
87
88
        Requests which will be sent to the LM.

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param ctx: str
            The context string, generated by fewshot_context. This includes the natural
            language description, as well as the few shot examples, and the question
            part of the document for `doc`.
        """
Fabrizio Milo's avatar
Fabrizio Milo committed
89
        # NOTE: The paper implements "verifiers" that assign a score to multiple
Jonathan Tow's avatar
Jonathan Tow committed
90
        # solutions and output the highest ranked solution.
haileyschoelkopf's avatar
haileyschoelkopf committed
91
        return Instance(request_type=self.OUTPUT_TYPE, doc=doc, arguments=(ctx, ["\n"]), id_=0, **kwargs)
92
93
        # completion = rf.greedy_until(ctx, ["\n"])
        # return completion
Jonathan Tow's avatar
Jonathan Tow committed
94
95
96
97
98
99
100
101
102
103
104
105
106

    def _extract_answer(self, completion):
        match = ANS_RE.search(completion)
        if match:
            match_str = match.group(1).strip()
            match_str = match_str.replace(",", "")
            return match_str
        else:
            return INVALID_ANS

    def _is_correct(self, completion, answer):
        gold = self._extract_answer(answer)
        assert gold != INVALID_ANS, "No ground truth answer found in the document."
107
108
109
        # return self._extract_answer(completion) == gold
        # print(completion)
        return completion == gold
Jonathan Tow's avatar
Jonathan Tow committed
110
111
112
113
114
115
116
117
118
119
120

    def process_results(self, doc, results):
        """Take a single document and the LM results and evaluates, returning a
        dict where keys are the names of submetrics and values are the values of
        the metric for that one document

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param results:
            The results of the requests created in construct_requests.
        """
121

Jonathan Tow's avatar
Jonathan Tow committed
122
123
        completion = results[0]
        answer = doc["answer"]
Fabrizio Milo's avatar
Fabrizio Milo committed
124
        return {"acc": self._is_correct(completion, answer)}
Jonathan Tow's avatar
Jonathan Tow committed
125
126
127
128
129
130
131

    def aggregation(self):
        """
        :returns: {str: [float] -> float}
            A dictionary where keys are the names of submetrics and values are
            functions that aggregate a list of metrics
        """
Fabrizio Milo's avatar
Fabrizio Milo committed
132
        return {"acc": mean}
Jonathan Tow's avatar
Jonathan Tow committed
133
134
135
136
137
138
139

    def higher_is_better(self):
        """
        :returns: {str: bool}
            A dictionary where keys are the names of submetrics and values are
            whether a higher value of the submetric is better
        """
Fabrizio Milo's avatar
Fabrizio Milo committed
140
        return {"acc": True}