cbt.py 4.87 KB
Newer Older
1
2
3
4
"""
The Children’s Book Test (CBT) from the paper:
https://research.fb.com/wp-content/uploads/2016/11/the_goldilocks_principle_reading_children_s_books_with_explicit_memory_representations.pdf

bzantium's avatar
bzantium committed
5
The Children's Book Test (CBT) is test of how well language models capture
6
7
8
9
10
11
12
13
14
meaning in children's books. Unlike standard language modelling benchmarks,
it distinguishes the task of predicting syntactic function words from that
of predicting lower-frequency words, which carry greater semantic content.

NOTE: This evaluation is based on the (context + query) question-answering variant
used by the Recurrent Language Models described in the paper. See section 4.4.

Homepage: https://github.com/facebookresearch/ParlAI/tree/main/parlai/tasks/cbt
"""
15
import numpy as np
Jonathan Tow's avatar
Jonathan Tow committed
16
from lm_eval.base import rf, Task
17
18
19
from lm_eval.metrics import mean


20
21
_CITATION = """
@misc{hill2016goldilocks,
bzantium's avatar
bzantium committed
22
    title={The Goldilocks Principle: Reading Children's Books with Explicit Memory Representations},
23
24
25
26
27
28
29
30
31
    author={Felix Hill and Antoine Bordes and Sumit Chopra and Jason Weston},
    year={2016},
    eprint={1511.02301},
    archivePrefix={arXiv},
    primaryClass={cs.CL}
}
"""


Jonathan Tow's avatar
Jonathan Tow committed
32
class CBTBase(Task):
33
    VERSION = 0
34
35
36
    DATASET_PATH = "cbt"
    DATASET_NAME = None

Jonathan Tow's avatar
Jonathan Tow committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

    def training_docs(self):
        if self._training_docs is None:
            self._training_docs = list(self.dataset["train"])
        return self._training_docs

    def validation_docs(self):
        return self.dataset["validation"]

    def test_docs(self):
        return self.dataset["test"]
Leo Gao's avatar
Leo Gao committed
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    def detokenize(self, text):
        text = text.replace(" '", "'")
        text = text.replace(" \n", "\n")
        text = text.replace("\n ", "\n")
        text = text.replace(" n't", "n't")
        text = text.replace("`` ", '"')
        text = text.replace("''", '"')
        # punctuation
        text = text.replace(" :", ":")
        text = text.replace(" ;", ";")
        text = text.replace(" !", "!")
        text = text.replace(" ?", "?")
        text = text.replace(" ,", ",")
        text = text.replace(" .", ".")
        return text

    def doc_to_text(self, doc):
        passage = " ".join(doc["sentences"])
        text = "Passage: " + passage + "\nQuestion: " + doc["question"]
        return self.detokenize(text)

bzantium's avatar
bzantium committed
78
79
80
81
82
83
84
    def should_decontaminate(self):
        return True

    def doc_to_decontamination_query(self, doc):
        passage = " ".join(doc["sentences"])
        return passage

85
86
87
88
    def doc_to_target(self, doc):
        return ""

    def fewshot_examples(self, k, rnd):
bzantium's avatar
bzantium committed
89
90
91
        assert (
            k == 0
        ), f"CBT is only implemented for the zero-shot setting. Given k={k}."
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
        return super().fewshot_examples(k, rnd)

    def construct_requests(self, doc, ctx):
        """Uses RequestFactory to construct Requests and returns an iterable of
        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`.
        """
        lls = []
        for option in doc["options"]:
            # Following Section 4.4 "Recurrent Language Models" in the CBT paper:
            # "we rank candidate [option] c based on p(q1 . . . qk−1, c, qk+1 . . . ql)
            # rather than simply p(q1 . . . qk−1, c)."
            lls.append(rf.loglikelihood("", ctx.replace("XXXXX", option))[0])
        return lls

    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.
        """
        gold = doc["options"].index(doc["answer"])
        pred = np.argmax(results)
bzantium's avatar
bzantium committed
125
        return {"acc": pred == gold}
126
127
128
129
130
131
132

    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
        """
bzantium's avatar
bzantium committed
133
        return {"acc": mean}
134
135
136
137
138
139
140

    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
        """
bzantium's avatar
bzantium committed
141
        return {"acc": True}
142
143
144
145
146
147
148
149


class CBTCN(CBTBase):
    DATASET_NAME = "CN"


class CBTNE(CBTBase):
    DATASET_NAME = "NE"