blimp / blimp.py
yu-val-weiss
add model max length
f053fe4
# 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."""
from collections import defaultdict
from typing import Optional
import datasets
import evaluate
import torch
from evaluate import logging
from transformers import AutoModelForCausalLM, AutoTokenizer
datasets.logging.set_verbosity_error()
BLIMP_UIDS = [
"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 (Optional[int]): the number of samples per phenomenon. Max is 1,000 (but will not error if higher value given.) If None, defaults to 1000.
trust_remote_code (bool): whether to trust datasets code , default False.
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.
"""
@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: Optional[int] = None,
trust_remote_code: bool = False,
):
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")
)
samples_per_set = 1000 if samples_per_set is None else samples_per_set
if samples_per_set <= 0 or samples_per_set > 1000:
samples_per_set = 1000
model = AutoModelForCausalLM.from_pretrained(
model_id, trust_remote_code=trust_remote_code
)
model = model.to(device)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(
model_id,
trust_remote_code=trust_remote_code,
max_model_length=150,
)
# 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]})
run_all = len(predictions) == 0 or predictions[0] == "*"
if run_all:
blimp_sets = BLIMP_UIDS
else:
blimp_sets = []
for p in predictions:
if p in BLIMP_UIDS:
blimp_sets.append(p)
else:
logging.logging.warning(f"{p} not a valid UID, skipping...")
assert len(blimp_sets) > 0, "no valid phenomena selected"
results = {}
phenom_results = defaultdict(list)
for category in logging.tqdm(blimp_sets, desc="Evaluating phenomena..."):
dataset = datasets.load_dataset(
"nyu-mll/blimp", category, trust_remote_code=trust_remote_code
)["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[:samples_per_set])
# Get probabilities in batches
good_probs = _get_batch_probabilities(
model,
tokenizer,
good_sents,
device,
batch_size,
category,
sent_type="good",
)
bad_probs = _get_batch_probabilities(
model,
tokenizer,
bad_sents,
device,
batch_size,
category,
sent_type="bad",
)
# compute accuracy (mean of instances where good prob > bad prob) for this UID
sub_acc = (good_probs > bad_probs).float().mean().item()
phenom = dataset[0]["linguistics_term"]
results[category] = sub_acc
phenom_results[phenom].append(sub_acc)
return {
"by_uid": results,
"accuracy": sum(results.values()) / len(results), # overall accuracy
"by_phenomenon": {
term: sum(acc) / len(acc) for term, acc in phenom_results.items()
},
}
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 = torch.zeros(len(sentences))
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)
logits = outputs.logits[..., :-1, :].contiguous()
labels = inputs.input_ids[..., 1:].contiguous()
# compute log probabilities
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)
# get per-token probability
token_log_probs = torch.gather(log_probs, 2, labels.unsqueeze(-1)).squeeze(-1)
if batch_size > 1:
# mask padding tokens
token_log_probs.masked_fill_(labels == tokenizer.pad_token_id, 0.0)
# sum log probabilities
sequence_log_probs = token_log_probs.sum(dim=1)
probs[i : i + batch_size] = sequence_log_probs
return probs