File size: 16,421 Bytes
e4c37ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The LAMA Dataset"""


import json
from fnmatch import fnmatch

import datasets


_CITATION = """@inproceedings{petroni2019language,

  title={Language Models as Knowledge Bases?},

  author={F. Petroni, T. Rockt{\"{a}}schel, A. H. Miller, P. Lewis, A. Bakhtin, Y. Wu and S. Riedel},

  booktitle={In: Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing (EMNLP), 2019},

  year={2019}

}

@inproceedings{petroni2020how,

  title={How Context Affects Language Models' Factual Predictions},

  author={Fabio Petroni and Patrick Lewis and Aleksandra Piktus and Tim Rockt{\"a}schel and Yuxiang Wu and Alexander H. Miller and Sebastian Riedel},

  booktitle={Automated Knowledge Base Construction},

  year={2020},

  url={https://openreview.net/forum?id=025X0zPfn}

}

"""


_DESCRIPTION = """LAMA is a dataset used to probe and analyze the factual and commonsense knowledge contained in pretrained language models. See https://github.com/facebookresearch/LAMA.

"""

_HOMEPAGE = "https://github.com/facebookresearch/LAMA"

_LICENSE = "The Creative Commons Attribution-Noncommercial 4.0 International License. see https://github.com/facebookresearch/LAMA/blob/master/LICENSE"

_RELATIONS_URL = "https://s3.amazonaws.com/datasets.huggingface.co/lama/relations.jsonl"

_DATA_URL = "https://dl.fbaipublicfiles.com/LAMA/negated_data.tar.gz"


class Lama(datasets.GeneratorBasedBuilder):
    """Lama Dataset"""

    VERSION = datasets.Version("1.1.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="trex", version=VERSION, description="The TRex part of the Lama dataset"),
        datasets.BuilderConfig(name="squad", version=VERSION, description="The Squad part of the Lama dataset"),
        datasets.BuilderConfig(
            name="google_re", version=VERSION, description="The Google_re part of the Lama dataset"
        ),
        datasets.BuilderConfig(
            name="conceptnet", version=VERSION, description="The Conceptnet part of the Lama dataset"
        ),
    ]

    DEFAULT_CONFIG_NAME = "trex"

    def _info(self):
        if self.config.name == "trex":
            features = datasets.Features(
                {
                    "uuid": datasets.Value("string"),
                    "obj_uri": datasets.Value("string"),
                    "obj_label": datasets.Value("string"),
                    "sub_uri": datasets.Value("string"),
                    "sub_label": datasets.Value("string"),
                    "predicate_id": datasets.Value("string"),
                    "sub_surface": datasets.Value("string"),
                    "obj_surface": datasets.Value("string"),
                    "masked_sentence": datasets.Value("string"),
                    "template": datasets.Value("string"),
                    "template_negated": datasets.Value("string"),
                    "label": datasets.Value("string"),
                    "description": datasets.Value("string"),
                    "type": datasets.Value("string"),
                }
            )
            return datasets.DatasetInfo(
                description=_DESCRIPTION,
                features=features,
                supervised_keys=None,
                homepage=_HOMEPAGE,
                license=_LICENSE,
                citation=_CITATION,
            )
        elif self.config.name == "conceptnet":
            features = datasets.Features(
                {
                    "uuid": datasets.Value("string"),
                    "sub": datasets.Value("string"),
                    "obj": datasets.Value("string"),
                    "pred": datasets.Value("string"),
                    "obj_label": datasets.Value("string"),
                    "masked_sentence": datasets.Value("string"),
                    "negated": datasets.Value("string"),
                }
            )
            return datasets.DatasetInfo(
                description=_DESCRIPTION,
                features=features,
                supervised_keys=None,
                homepage=_HOMEPAGE,
                license=_LICENSE,
                citation=_CITATION,
            )
        elif self.config.name == "squad":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "sub_label": datasets.Value("string"),
                    "obj_label": datasets.Value("string"),
                    "negated": datasets.Value("string"),
                    "masked_sentence": datasets.Value("string"),
                }
            )
            return datasets.DatasetInfo(
                description=_DESCRIPTION,
                features=features,
                supervised_keys=None,
                homepage=_HOMEPAGE,
                license=_LICENSE,
                citation=_CITATION,
            )
        elif self.config.name == "google_re":
            features = datasets.Features(
                {
                    "pred": datasets.Value("string"),
                    "sub": datasets.Value("string"),
                    "obj": datasets.Value("string"),
                    "evidences": datasets.Value("string"),
                    "judgments": datasets.Value("string"),
                    "sub_w": datasets.Value("string"),
                    "sub_label": datasets.Value("string"),
                    "sub_aliases": datasets.Value("string"),
                    "obj_w": datasets.Value("string"),
                    "obj_label": datasets.Value("string"),
                    "obj_aliases": datasets.Value("string"),
                    "uuid": datasets.Value("string"),
                    "masked_sentence": datasets.Value("string"),
                    "template": datasets.Value("string"),
                    "template_negated": datasets.Value("string"),
                }
            )
            return datasets.DatasetInfo(
                description=_DESCRIPTION,
                features=features,
                supervised_keys=None,
                homepage=_HOMEPAGE,
                license=_LICENSE,
                citation=_CITATION,
            )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        archive = dl_manager.download(_DATA_URL)
        if self.config.name == "trex":
            relations_path = dl_manager.download(_RELATIONS_URL)
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "filepaths": ["TREx/*"],
                        "files": dl_manager.iter_archive(archive),
                        "relations_path": relations_path,
                    },
                ),
            ]
        elif self.config.name == "google_re":
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "filepaths": [
                            "Google_RE/date_of_birth_test.jsonl",
                            "Google_RE/place_of_birth_test.jsonl",
                            "Google_RE/place_of_death_test.jsonl",
                        ],
                        "files": dl_manager.iter_archive(archive),
                    },
                ),
            ]
        elif self.config.name == "conceptnet":
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "filepaths": ["ConceptNet/test.jsonl"],
                        "files": dl_manager.iter_archive(archive),
                    },
                ),
            ]
        elif self.config.name == "squad":
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "filepaths": ["Squad/test.jsonl"],
                        "files": dl_manager.iter_archive(archive),
                    },
                ),
            ]

    def _generate_examples(self, filepaths, files, relations_path=None):
        """Yields examples from the LAMA dataset."""
        filepaths = list(filepaths)
        if self.config.name == "trex":
            all_rels = {}
            with open(relations_path, encoding="utf-8") as f:
                for row in f:
                    data = json.loads(row)
                    all_rels[data["relation"]] = data
            id_ = -1
            inside_trec_directory = False
            for path, f in files:
                if any(fnmatch(path, pattern) for pattern in filepaths):
                    inside_trec_directory = True
                    for row in f:
                        data = json.loads(row)
                        pred = all_rels.get(data["predicate_id"], {})
                        for evidences in data["evidences"]:
                            id_ += 1
                            yield id_, {
                                "uuid": str(data["uuid"]),
                                "obj_uri": str(data["obj_uri"]),
                                "obj_label": str(data["obj_label"]),
                                "sub_uri": str(data["sub_uri"]),
                                "sub_label": str(data["sub_label"]),
                                "predicate_id": str(data["predicate_id"]),
                                "sub_surface": str(evidences["sub_surface"]),
                                "obj_surface": str(evidences["obj_surface"]),
                                "masked_sentence": str(evidences["masked_sentence"]),
                                "template": str(pred.get("template", "")),
                                "template_negated": str(pred.get("template_negated", "")),
                                "label": str(pred.get("label", "")),
                                "description": str(pred.get("description", "")),
                                "type": str(pred.get("type", "")),
                            }
                elif inside_trec_directory:
                    break
        elif self.config.name == "conceptnet":
            id_ = -1
            for path, f in files:
                if not filepaths:
                    break
                if path in list(filepaths):
                    for row in f:
                        data = json.loads(row)
                        if data.get("negated") is not None:
                            for masked_sentence, negated in zip(data["masked_sentences"], data["negated"]):
                                id_ += 1
                                yield id_, {
                                    "uuid": str(data["uuid"]),
                                    "sub": str(data.get("sub", "")),
                                    "obj": str(data.get("obj", "")),
                                    "pred": str(data["pred"]),
                                    "obj_label": str(data["obj_label"]),
                                    "masked_sentence": str(masked_sentence),
                                    "negated": str(negated),
                                }
                        else:
                            for masked_sentence in data["masked_sentences"]:
                                id_ += 1
                                yield id_, {
                                    "uuid": str(data["uuid"]),
                                    "sub": str(data.get("sub", "")),
                                    "obj": str(data.get("obj", "")),
                                    "pred": str(data["pred"]),
                                    "obj_label": str(data["obj_label"]),
                                    "masked_sentence": str(masked_sentence),
                                    "negated": str(""),
                                }
                    filepaths.remove(path)
        elif self.config.name == "squad":
            id_ = -1
            for path, f in files:
                if not filepaths:
                    break
                if path in filepaths:
                    for row in f:
                        data = json.loads(row)
                        for masked_sentence in data["masked_sentences"]:
                            id_ += 1
                            yield id_, {
                                "id": str(data["id"]),
                                "sub_label": str(data["sub_label"]),
                                "obj_label": str(data["obj_label"]),
                                "negated": str(data.get("negated", "")),
                                "masked_sentence": str(masked_sentence),
                            }
                    filepaths.remove(path)
        elif self.config.name == "google_re":
            id_ = -1
            for path, f in files:
                if path in filepaths:
                    if not filepaths:
                        break
                    if path in filepaths:
                        # from https://github.com/facebookresearch/LAMA/blob/master/scripts/run_experiments.py
                        if "place_of_birth" in path:
                            pred = {
                                "relation": "place_of_birth",
                                "template": "[X] was born in [Y] .",
                                "template_negated": "[X] was not born in [Y] .",
                            }
                        elif "date_of_birth" in path:
                            pred = {
                                "relation": "date_of_birth",
                                "template": "[X] (born [Y]).",
                                "template_negated": "[X] (not born [Y]).",
                            }
                        else:
                            pred = {
                                "relation": "place_of_death",
                                "template": "[X] died in [Y] .",
                                "template_negated": "[X] did not die in [Y] .",
                            }
                        for row in f:
                            data = json.loads(row)
                            for masked_sentence in data["masked_sentences"]:
                                id_ += 1
                                yield id_, {
                                    "pred": str(data["pred"]),
                                    "sub": str(data["sub"]),
                                    "obj": str(data["obj"]),
                                    "evidences": str(data["evidences"]),
                                    "judgments": str(data["judgments"]),
                                    "sub_w": str(data["sub_w"]),
                                    "sub_label": str(data["sub_label"]),
                                    "sub_aliases": str(data["sub_aliases"]),
                                    "obj_w": str(data["obj_w"]),
                                    "obj_label": str(data["obj_label"]),
                                    "obj_aliases": str(data["obj_aliases"]),
                                    "uuid": str(data["uuid"]),
                                    "masked_sentence": str(masked_sentence),
                                    "template": str(pred["template"]),
                                    "template_negated": str(pred["template_negated"]),
                                }
                        filepaths.remove(path)