File size: 11,151 Bytes
b1b0ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3cd77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b0ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3cd77
b1b0ea9
 
 
 
 
 
 
 
 
8f3cd77
 
b1b0ea9
8f3cd77
 
 
b1b0ea9
 
 
 
 
 
 
 
 
8f3cd77
b1b0ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3cd77
b1b0ea9
 
8f3cd77
b1b0ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3cd77
b1b0ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3cd77
 
 
 
 
 
 
 
b1b0ea9
8f3cd77
b1b0ea9
8f3cd77
 
 
 
 
 
 
 
 
 
 
 
 
b1b0ea9
8f3cd77
 
 
 
 
 
 
 
b1b0ea9
 
8f3cd77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b0ea9
8f3cd77
b1b0ea9
8f3cd77
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
# Copyright 2022 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.
"""Blimp Metric."""

import datasets
import evaluate
import torch
from evaluate import logging
from transformers import AutoModelForCausalLM, AutoTokenizer

datasets.logging.set_verbosity_error()

BLIMP_PHENOMENA = [
    "adjunct_island",
    "anaphor_gender_agreement",
    "anaphor_number_agreement",
    "animate_subject_passive",
    "animate_subject_trans",
    "causative",
    "complex_NP_island",
    "coordinate_structure_constraint_complex_left_branch",
    "coordinate_structure_constraint_object_extraction",
    "determiner_noun_agreement_1",
    "determiner_noun_agreement_2",
    "determiner_noun_agreement_irregular_1",
    "determiner_noun_agreement_irregular_2",
    "determiner_noun_agreement_with_adj_2",
    "determiner_noun_agreement_with_adj_irregular_1",
    "determiner_noun_agreement_with_adj_irregular_2",
    "determiner_noun_agreement_with_adjective_1",
    "distractor_agreement_relational_noun",
    "distractor_agreement_relative_clause",
    "drop_argument",
    "ellipsis_n_bar_1",
    "ellipsis_n_bar_2",
    "existential_there_object_raising",
    "existential_there_quantifiers_1",
    "existential_there_quantifiers_2",
    "existential_there_subject_raising",
    "expletive_it_object_raising",
    "inchoative",
    "intransitive",
    "irregular_past_participle_adjectives",
    "irregular_past_participle_verbs",
    "irregular_plural_subject_verb_agreement_1",
    "irregular_plural_subject_verb_agreement_2",
    "left_branch_island_echo_question",
    "left_branch_island_simple_question",
    "matrix_question_npi_licensor_present",
    "npi_present_1",
    "npi_present_2",
    "only_npi_licensor_present",
    "only_npi_scope",
    "passive_1",
    "passive_2",
    "principle_A_c_command",
    "principle_A_case_1",
    "principle_A_case_2",
    "principle_A_domain_1",
    "principle_A_domain_2",
    "principle_A_domain_3",
    "principle_A_reconstruction",
    "regular_plural_subject_verb_agreement_1",
    "regular_plural_subject_verb_agreement_2",
    "sentential_negation_npi_licensor_present",
    "sentential_negation_npi_scope",
    "sentential_subject_island",
    "superlative_quantifiers_1",
    "superlative_quantifiers_2",
    "tough_vs_raising_1",
    "tough_vs_raising_2",
    "transitive",
    "wh_island",
    "wh_questions_object_gap",
    "wh_questions_subject_gap",
    "wh_questions_subject_gap_long_distance",
    "wh_vs_that_no_gap",
    "wh_vs_that_no_gap_long_distance",
    "wh_vs_that_with_gap",
    "wh_vs_that_with_gap_long_distance",
]

_CITATION = r"""
@article{warstadt2020blimp,
    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. }
}
"""

_DESCRIPTION = """BLiMP is a challenge set for evaluating what language models (LMs) know about major grammatical phenomena in English.
BLiMP consists of 67 sub-datasets, each containing 1000 minimal pairs isolating specific contrasts in syntax, morphology, or semantics.
The data is automatically generated according to expert-crafted grammars. Aggregate human agreement with the labels is 96.4%.
We use BLiMP to evaluate an n-gram LM, LSTM LM, GPT-2, and Transformer-XL.

For more info see https://github.com/alexwarstadt/blimp.
"""

_KWARGS_DESCRIPTION = """
Args:
    model_id (str): model used for calculating Blimp, NOTE: should be a causal LM model
    predictions (list[str]): names of metrics to run. pass empty list or ["*"] to run all of them
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    device (str): device to run on, defaults to 'cuda' when available.
    samples_per_set (int): the number of samples per phenomenon, defaults to 1_000.
    
Returns:
    blimp: dictionary containing the blimp scores for each of the 67 sub-datasets, as well as the overall accuracy.
    An LM’s overall accuracy on BLiMP is simply the proportion of the 67,000 minimal pairs in which the model assigns a higher probability to the acceptable sentence. 
Examples:
    TODO: examples.
"""


@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class Blimp(evaluate.Metric):
    def _info(self):
        return evaluate.MetricInfo(
            module_type="metric",
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            features=datasets.Features(
                {
                    "predictions": datasets.Value("string"),
                }
            ),
            reference_urls=[
                "https://github.com/alexwarstadt/blimp",
                "https://huggingface.co/datasets/nyu-mll/blimp",
            ],
        )

    def _compute(
        self,
        model_id,
        predictions=None,
        batch_size: int = 16,
        device=None,
        samples_per_set: int = 1_000,
    ):
        if device is not None:
            assert device in ["gpu", "cpu", "cuda", "mps"], (
                "device should be either gpu, cpu or mps."
            )
            if device == "gpu":
                device = "cuda"
        else:
            device = (
                "cuda"
                if torch.cuda.is_available()
                else ("mps" if torch.mps.is_available() else "cpu")
            )

        model = AutoModelForCausalLM.from_pretrained(model_id)
        model = model.to(device)
        model.eval()

        tokenizer = AutoTokenizer.from_pretrained(model_id)

        # if batch_size > 1 (which generally leads to padding being required), and
        # if there is not an already assigned pad_token, assign an existing
        # special token to also be the padding token
        if tokenizer.pad_token is None and batch_size > 1:
            existing_special_tokens = list(
                tokenizer.special_tokens_map_extended.values()
            )
            # check that the model already has at least one special token defined
            assert len(existing_special_tokens) > 0, (
                "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
            )
            # assign one of the special tokens to also be the pad token
            tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]})

        print("PAD", tokenizer.pad_token_id)

        run_all = len(predictions) == 0 or predictions[0] == "*"
        blimp_sets = (
            BLIMP_PHENOMENA
            if run_all
            else [p for p in BLIMP_PHENOMENA if p.lower() in predictions]
        )

        assert len(blimp_sets) > 0, "no valid phenomena selected"

        results = {}

        for phenomenon in logging.tqdm(blimp_sets, desc="Evaluating phenomena..."):
            dataset = datasets.load_dataset("nyu-mll/blimp", phenomenon)["train"]

            # Prepare batches of good and bad sentences

            sents = [(x["sentence_good"], x["sentence_bad"]) for x in dataset]
            good_sents, bad_sents = zip(*sents[: min(1000, samples_per_set)])

            # Get probabilities in batches
            good_probs = get_batch_probabilities(
                model, tokenizer, good_sents, device, batch_size, phenomenon
            )
            bad_probs = get_batch_probabilities(
                model,
                tokenizer,
                bad_sents,
                device,
                batch_size,
                phenomenon,
                sent_type="bad",
            )

            # Compare probabilities
            correct = sum(g > b for g, b in zip(good_probs, bad_probs))
            accuracy = correct / len(good_probs)
            results[phenomenon] = accuracy

        # Calculate overall accuracy
        overall_accuracy = sum(results.values()) / len(results)

        return {"phenomenon_accuracies": results, "overall_accuracy": overall_accuracy}


def get_batch_probabilities(
    model,
    tokenizer,
    sentences: list[str],
    device: str,
    batch_size: int,
    phenomenon: str,
    sent_type: str = "good",
):
    """Compute log probabilities for a batch of sentences"""
    probs = []

    for i in logging.tqdm(
        range(0, len(sentences), batch_size),
        desc=f"{phenomenon} - {sent_type} sentences...",
        leave=False,
    ):
        batch = sentences[i : i + batch_size]
        inputs = tokenizer(
            batch, padding=batch_size > 1, return_tensors="pt", truncation=True
        ).to(device)

        with torch.no_grad():
            outputs = model(**inputs)

        labels = inputs.input_ids

        # Compute log probabilities
        log_probs = torch.nn.functional.log_softmax(outputs.logits, dim=-1)

        # Get probability of each actual token
        token_log_probs = torch.gather(log_probs, 2, labels.unsqueeze(-1)).squeeze(-1)

        if batch_size > 1:
            # Create attention mask for padding
            mask = (labels != tokenizer.pad_token_id).float()
            token_log_probs *= mask

        # sum log probabilities
        sequence_log_probs = (token_log_probs).sum(dim=1)

        probs.extend(sequence_log_probs.cpu().tolist())

    return probs