File size: 7,012 Bytes
340b7b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""BLIMP Acceptability"""

from __future__ import absolute_import, division, print_function

import csv
import os
import textwrap

import six

import datasets


_Blimp_CITATION = r"""
@article{warstadt2019blimp,
    author = {Warstadt, Alex and Parrish, Alicia and Liu, Haokun and Mohananey, Anhad and Peng, Wei and Wang, Sheng-Fu and Bowman, Samuel R.},
    title = {BLiMP: The Benchmark of Linguistic Minimal Pairs for English},
    journal = {Transactions of the Association for Computational Linguistics},
    volume = {8},
    number = {},
    pages = {377-392},
    year = {2020},
    doi = {10.1162/tacl\_a\_00321},
    URL = {https://doi.org/10.1162/tacl_a_00321},
    eprint = {https://doi.org/10.1162/tacl_a_00321},
    abstract = { We introduce The Benchmark of Linguistic Minimal Pairs (BLiMP),1 a challenge set for evaluating the linguistic knowledge of language models (LMs) on major grammatical phenomena in English. BLiMP consists of 67 individual datasets, each containing 1,000 minimal pairs—that is, pairs of minimally different sentences that contrast in grammatical acceptability and isolate specific phenomenon in syntax, morphology, or semantics. We generate the data according to linguist-crafted grammar templates, and human aggregate agreement with the labels is 96.4\%. We evaluate n-gram, LSTM, and Transformer (GPT-2 and Transformer-XL) LMs by observing whether they assign a higher probability to the acceptable sentence in each minimal pair. We find that state-of-the-art models identify morphological contrasts related to agreement reliably, but they struggle with some subtle semantic and syntactic phenomena, such as negative polarity items and extraction islands. }
}
@inproceedings{sileo2021analysis,
      title={Analysis and Prediction of NLP Models Via Task Embeddings}, 
      author={Damien Sileo and Marie-Francine Moens},
      booktitle = "Proceedings of the 12th Language Resources and Evaluation Conference",
      year={2022},
}
"""

_Blimp_DESCRIPTION = """\
Acceptable/non acceptable sentences (recasted as a classification task)
"""

DATA_URL = "https://www.dropbox.com/s/28s8qj97nuiwyoh/blimp.zip?dl=1"


def get_labels(task):
    return ["unacceptable","acceptable"]


class BlimpConfig(datasets.BuilderConfig):
    """BuilderConfig for Blimp."""

    def __init__(
        self,
        text_features,
        label_classes=None,
        **kwargs,
    ):
        """BuilderConfig for Blimp.
        Args:
          text_features: `dict[string, string]`, map from the name of the feature
            dict for each text field to the name of the column in the tsv file
          label_column: `string`, name of the column in the tsv file corresponding
            to the label
          data_url: `string`, url to download the zip file from
          data_dir: `string`, the path to the folder containing the tsv files in the
            downloaded zip
          citation: `string`, citation for the data set
          url: `string`, url for information about the data set
          label_classes: `list[string]`, the list of classes if the label is
            categorical. If not provided, then the label will be of type
            `datasets.Value('float32')`.
          process_label: `Function[string, any]`, function  taking in the raw value
            of the label and processing it to the form required by the label feature
          **kwargs: keyword arguments forwarded to super.
        """

        super(BlimpConfig, self).__init__(
            version=datasets.Version("1.0.0", ""), **kwargs
        )

        self.text_features = text_features
        self.label_column = "label"
        self.label_classes = get_labels(self.name)
        self.data_url = DATA_URL
        self.data_dir = os.path.join("blimp", self.name)
        self.citation = textwrap.dedent(_Blimp_CITATION)
        self.description = ""
        self.url = ""


class Blimp(datasets.GeneratorBasedBuilder):

    """The General Language Understanding Evaluation (Blimp) benchmark."""

    BUILDER_CONFIG_CLASS = BlimpConfig

    BUILDER_CONFIGS = [
        BlimpConfig(
            name=name,
            text_features={"sentence": "sentence"},
        ) for name in ["semantics","syntax","morphology","syntax+semantics","syntax_semantics"]
    ]

    def _info(self):
        features = {
            text_feature: datasets.Value("string")
            for text_feature in six.iterkeys(self.config.text_features)
        }
        if self.config.label_classes:
            features["label"] = datasets.features.ClassLabel(
                names=self.config.label_classes
            )
        else:
            features["label"] = datasets.Value("float32")
        features["idx"] = datasets.Value("int32")
        return datasets.DatasetInfo(
            description=_Blimp_DESCRIPTION,
            features=datasets.Features(features),
            homepage=self.config.url,
            citation=self.config.citation + "\n" + _Blimp_CITATION,
        )

    def _split_generators(self, dl_manager):
        dl_dir = dl_manager.download_and_extract(self.config.data_url)
        data_dir = os.path.join(dl_dir, self.config.data_dir)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "data_file": os.path.join(data_dir or "", "train.tsv"),
                    "split": "train",
                },
            ),
        ]

    def _generate_examples(self, data_file, split):

        label_classes = self.config.label_classes

        with open(data_file) as f:
            reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_ALL)

            for n, row in enumerate(reader):

                example = {
                    feat: row[col.replace("sentence","text")]
                    for feat, col in six.iteritems(self.config.text_features)
                }
                example["idx"] = n

                if self.config.label_column in row:
                    label = row[self.config.label_column]
                    if label_classes and label not in label_classes:
                        print(row)
                        continue
                    example["label"] =label
                else:
                    example["label"] = -1
                yield example["idx"], example