LLMs for psycholinguists (Part 4)¶

  • Part 0:   Preparation
  • Part 1:   Basics
  • Part 2:   Surprisals for controlled experiment stimuli
  • Part 3:   Surprisals for large-scale naturalistic corpus data
  • Part 4:   Attention scores   <- this notebook

Earlier in Part 2, we've seen how to get LM surprisal values for the stimuli of controlled psycholinguistic experiments. In this Part 4, we will see how to extract and analyze attention scores from Huggingface LMs.

Again, we will use the stimuli from the Experiment 1 of Dillon et al. (2013) Contrasting intrusion profiles for agreement and anaphora: Experimental and modeling evidence.

We will follow Ryu and Lewis (2021) Accounting for Agreement Phenomena in Sentence Comprehension with Transformer Language Models: Effects of Similarity-based Interference on Surprisal and Attention for the analysis of attention scores.

You can download the stimuli data here.

In [1]:
import pandas as pd
import numpy as np
import torch
import os
from transformers import AutoModelForCausalLM, AutoTokenizer

# Pick the fastest available device
if torch.cuda.is_available():
    device = "cuda"
elif torch.backends.mps.is_available():  # Apple Silicon if you are using MacBook with M1/M2 chip
    device = "mps"
else:
    device = "cpu"
print("Using device:", device)

OUTPUT_DIR = "model_outputs"
Using device: mps
In [2]:
# Initialize model, we will use GPT-2 small for this tutorial.
model = AutoModelForCausalLM.from_pretrained("gpt2")
# model = AutoModelForCausalLM.from_pretrained("gpt2-large") # you can also use larger models

model = model.eval().to(device)
tokenizer = AutoTokenizer.from_pretrained("gpt2")

1. Load and tokenize stimuli¶

Let's first load and tokenize stimuli following the same procedures as in Part 2.

In [3]:
# You can adjust the file path to point to the location of the DillonEtAl2013_Experiment1.csv
stimuli_df = pd.read_csv("data/DillonEtAl2013/DillonEtAl2013_Experiment1.csv")

def get_stimuli_words(stimuli_df):
    '''
    Split behavioral stimuli sentences into individual words.
    Returns a DataFrame with one row per word.
    '''
    words_df = (
        stimuli_df.assign(Word=stimuli_df["Sentence"].str.split()) # each sentence becomes a list of words
          .explode("Word") # one row per word
          .reset_index(drop=True)
    )
    # Word position within each sentence, counting from 1
    words_df["Word_id"] = words_df.groupby(["Condition", "Item"]).cumcount() + 1
    return words_df

def tokenize_words(words_df, tokenizer):
    '''
    Tokenize each sentence for the LM and map every token back to its word.
    Returns a new token-level DataFrame (one row per token); words_df is not modified.
    '''
    tokens_df = words_df.copy()
    tokens_df.insert(0, "global_word_id", tokens_df.index.values)
    tokens_df["hftoken"] = tokens_df["Word"].apply(lambda x: tokenizer.tokenize(" " + str(x)))
    tokens_df = tokens_df.explode("hftoken", ignore_index=True)
    tokens_df["token_id"] = tokens_df["hftoken"].apply(tokenizer.convert_tokens_to_ids)
    return tokens_df

words_df = get_stimuli_words(stimuli_df)
tokens_df = tokenize_words(words_df, tokenizer)

2. Transformer attention scores (illustrated step by step)¶

In this section, I will show step-by-step how to extract attention scores from Transformer LMs for our stimuli. I will put things together into one big function later in Section 3.

2.1 Construct input data (same as Part 2)¶

Again, let's build an input data of batch size of 4 with padding and attention mask.

In [4]:
batch_size = 4

text_groups = list(tokens_df.groupby(["Item", "Condition"], sort=False))

# GPT-2 does not have a pad token, so we use the EOS token as the pad value. 
# If the tokenizer has a pad token, we use that instead.
pad_value = tokenizer.eos_token_id
if tokenizer.pad_token_id is not None:
    pad_value = tokenizer.pad_token_id

batch = text_groups[0:0 + batch_size]

token_lists = [group['token_id'].tolist() for _, group in batch] # list of tokens of batch size

max_len = max(len(x) for x in token_lists) # the maximal length of the sentences in the batch

# tensor of pad values of the shape (batch_size, max_len)
inputs = torch.full((len(token_lists), max_len), pad_value, dtype=torch.long, device=device)

attention_mask = torch.zeros(len(token_lists), max_len, dtype=torch.long, device=device)

for b, token_list in enumerate(token_lists):
    inputs[b, :len(token_list)] = torch.tensor(token_list, dtype=torch.long, device=device)
    attention_mask[b, :len(token_list)] = 1
In [5]:
inputs
Out[5]:
tensor([[  383,  7331, 15849,   508, 19951,   329,   262, 13830, 27075,  4753,
           373, 18416,   284,   670,   890, 15381,    13, 50256],
        [  383,  7331, 15849,   508, 19951,   329,   262, 13830,  9214,  1666,
          4753,   373, 18416,   284,   670,   890, 15381,    13],
        [  383,  7331, 15849,   508, 19951,   329,   262, 13830, 27075,  4753,
           547, 18416,   284,   670,   890, 15381,    13, 50256],
        [  383,  7331, 15849,   508, 19951,   329,   262, 13830,  9214,  1666,
          4753,   547, 18416,   284,   670,   890, 15381,    13]],
       device='mps:0')

Again, we check sequence length explicitly.

In [6]:
# the maximal sequence length allowed by the model (e.g., 1024 for GPT-2):
max_pos = getattr(model.config, "n_positions", None) or getattr(model.config, "max_position_embeddings", None)

# raise an error if the maximal length of the sentences exceeds the model's maximal sequence length:
if max_pos is not None and max_len > max_pos:
    raise IndexError(f"Sequence too long: {max_len} > {max_pos}. Use sliding windows instead.")

2.2 Let's now run the model, with attention scores!¶

Let's first try with the model we initialized earlier. Here we add another argument output_attentions=True so the model will also store attention scores in its output.

In [7]:
with torch.no_grad():
    output = model(inputs, attention_mask=attention_mask, output_attentions=True)

attentions = output.attentions
attentions
Out[7]:
(None, None, None, None, None, None, None, None, None, None, None, None)

You can see that the returned attention scores are all None! That is because recent LMs on Huggingface used a more efficient way to implement self-attention and does not explicitly store attention scores.

In order to let the model explicitly store attention scores, we need to pass an additional argument when initializing the model:

In [8]:
model = AutoModelForCausalLM.from_pretrained("gpt2", attn_implementation="eager")
model = model.eval().to(device)

# forward pass
with torch.no_grad():
    output = model(inputs, attention_mask=attention_mask, output_attentions=True)

attentions = output.attentions

print(f"Number of layers: {len(attentions)}")
print(f"First layer (batch_size, num_heads, seq_query_len, seq_key_len): {attentions[0].shape}")
print(f"Last layer: {attentions[-1].shape}")
Number of layers: 12
First layer (batch_size, num_heads, seq_query_len, seq_key_len): torch.Size([4, 12, 18, 18])
Last layer: torch.Size([4, 12, 18, 18])

Now the attention scores are stored in attentions, which is a tuple consisting of layers.

  • There are 12 layers in GPT-2 small, so we can see there are 12 elements in this tuple
  • For this batch, each element (i.e., layer) is a tensor of the size 4 x 12 x 18 x 18:
    • 4 sentences in this batch
    • 12 attention heads at each layer
    • Maximal sequence length is 18 in this batch, so the last 2 dimensions have 18 query position x 18 key positions
Attention score shape of one sentence and one layer

We can also do a sanity check. At each query position, the attention scores (output of a softmax function) over key positions should sum up to 1. And we can see below that this is indeed the case.

In [9]:
attentions[0].sum(dim=-1)
Out[9]:
tensor([[[1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
          1.0000, 1.0000]]], device='mps:0')

For subsequent analyses, let's stack all layers together.

Note: In order to make our life easier, let's make the layers in the second dimension and batch in the first dimension. So to extract the first sentence in the batch we can simply do attn_all[0]

In [10]:
# (batch, layers, heads, query_seq_len, key_seq_len)
attn_all = torch.stack(output.attentions, dim=1).float().cpu()
attn_all.shape
Out[10]:
torch.Size([4, 12, 12, 18, 18])

2.3 Token level to word level¶

Let's first do it for one sentence in our batch.

Recall that our batch is a list of DataFrames with their groupby keys that looks like:

[((1, 'a'), <DataFrame for item 1, cond a>),
 ((1, 'b'), <DataFrame for item 1, cond b>),
 ...]

So the first sentence is:

In [11]:
group_key, first_sent_df = batch[0]
first_sent_df.head()
Out[11]:
global_word_id Item Condition Dep Gram Attr Crit_region Sentence Word Word_id hftoken token_id
0 0 1 a agreement grammatical singular 11 The tall nurse who cared for the elderly widow... The 1 Ä The 383
1 1 1 a agreement grammatical singular 11 The tall nurse who cared for the elderly widow... tall 2 Ä tall 7331
2 2 1 a agreement grammatical singular 11 The tall nurse who cared for the elderly widow... nurse 3 Ä nurse 15849
3 3 1 a agreement grammatical singular 11 The tall nurse who cared for the elderly widow... who 4 Ä who 508
4 4 1 a agreement grammatical singular 11 The tall nurse who cared for the elderly widow... cared 5 Ä cared 19951

Recall that this DataFrame has already been expanded so each row corresponds to a LM token. So if two rows represent two tokens that belong to the same word, they will have the same Word_id. Let's extract this Word_id column for the mapping from token-level attention to word-level attention. As a sanity check, the last two tokens belong to the same word 'shifts.'

Note: We do Word_id - 1 because attention-score indexing starts from 0 but our Word_id starts from 1.

In [12]:
word_id_for_tokens = first_sent_df["Word_id"].to_numpy() - 1
word_id_for_tokens
Out[12]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 15])

Similar to what we've done in Part 2, before mapping tokens to words, we first remove paddings:

In [13]:
n = len(first_sent_df)
attn_first_sent = attn_all[0, :, :, :n, :n]

Now let's define a matrix to represent the membership of tokens to words.

As you can see below:

  • Each row is a word (16 words in total)
  • Each column is a token
  • 1 means the token of a column is for the word of a row. For most words, each row is a one-hot vector, meaning that there is only one token for most words. But for the last row (the word 'shifts.'), you can see it has been split into two tokens, with two 1s for the last two tokens both belonging to that word.
In [14]:
n_words = int(word_id_for_tokens.max()) + 1
M = torch.zeros(n_words, len(word_id_for_tokens))  # shape (n_words, n_tokens)
M[word_id_for_tokens, torch.arange(len(word_id_for_tokens))] = 1.0

print(f"Shape of membership matrix: {M.shape}")
M
Shape of membership matrix: torch.Size([16, 17])
Out[14]:
tensor([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1.]])

With this membership matrix, we can map from token attentions to word attentions. Here we need to do some linear algebra tricks.

In [15]:
M_mean = M / M.sum(dim=1, keepdim=True)
word_attn = M_mean @ attn_first_sent @ M.T

Feel free to skip the mathematical details of these matrix multiplication if they look too obsure to you. But here is the intuition:

Taking a short phrase as an example "The shifts." We know that LM split " shifts." into two tokens " shifts" and the punctuation".". We handle queries and keys separately:

  • For keys, we simply sum up the attention scores of both tokens of "shifts." So any query that pays attention to "shifts." would now have an attention to this word as a whole by summing up the attention scores of both tokens.

  • For queries, if we wanna know the attention score distribution that " shifts." as a whole pay to, we simply take the average of the two query tokens.

So now, both the query and the key are at the word level. (Claude gave me this nice diagram below to illustrate the mapping process through matrix multiplication)

Converting token-level attention to word-level attention

We can check that word-level attention matrix now has sequence length 16, which matches the number of words in the sentence.

We can also check that the word-level attentions still sum up to 1 for each query word.

In [16]:
print(f"Number of words in the first sentence: {n_words}")
print(f"Shape of token-level attention matrix: {attn_first_sent.shape}")
print(f"Shape of word-level attention matrix: {word_attn.shape}")
word_attn.sum(dim=-1)
Number of words in the first sentence: 16
Shape of token-level attention matrix: torch.Size([12, 12, 17, 17])
Shape of word-level attention matrix: torch.Size([12, 12, 16, 16])
Out[16]:
tensor([[[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]],

        ...,

        [[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]],

        [[1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         ...,
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000],
         [1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]]])

Now let's put the token-to-word mapping of attention scores for one sentence in a function:

In [17]:
def token_to_word_attention(attn, word_id_for_tokens):
    '''
    attn: (n_layers, n_heads, n_tokens, n_tokens) for one sentence, padding removed
    word_id_for_tokens: length n_tokens, word_id (0, 1, 2, ...) of each token
    
    Returns (n_layers, n_heads, n_words, n_words); rows still sum to 1
    '''
    word_id_for_tokens = torch.as_tensor(word_id_for_tokens)
    n_words = int(word_id_for_tokens.max()) + 1
    M = torch.zeros(n_words, len(word_id_for_tokens))   # shape (n_words, n_tokens)
    M[word_id_for_tokens, torch.arange(len(word_id_for_tokens))] = 1.0
    M_mean = M / M.sum(dim=1, keepdim=True)              # average over a word's tokens (queries)
    return M_mean @ attn @ M.T                           # sum over a word's tokens (keys)

With this function, let's get the word-level attention scores for all 4 sentences in our batch. We store the output to a dictionary indexed by sentence.

Since the attention matrix is often huge, let's not store them in the DataFrame directly. Instead, we will store them as a separate file.

In [18]:
# one flattened attention array per sentence, one metadata row per sentence
flat_attn_scores, meta_index = [], []

offset = 0  # where the next sentence starts in the big flat array

# Token-level attention: (batch, layers, heads, query_seq_len, key_seq_len)
attn_all = torch.stack(output.attentions, dim=1).float().cpu()

for b, (group_key, group) in enumerate(batch):
    n = len(group)
    word_id_for_tokens = group["Word_id"].to_numpy() - 1    
    word_attn = token_to_word_attention(attn_all[b, :, :, :n, :n], word_id_for_tokens)

    # float32 to float16 to save memory
    word_attn = word_attn.half().numpy()  # (layers, heads, n_words, n_words)

    item, cond = group_key
    flat_attn_scores.append(word_attn.ravel()) # flatten to 1D
    meta_index.append({"Item": item, 
                       "Condition": cond,
                       "n_words": word_attn.shape[-1],
                       "offset": offset, 
                       "size": word_attn.size}) # total number of values in the attention matrix for this sentence
    offset += word_attn.size

attn_data = np.concatenate(flat_attn_scores)   # big flat float16 array
attn_index = pd.DataFrame(meta_index)  # metadata for each sentence


os.makedirs(f"{OUTPUT_DIR}/batch_demo", exist_ok=True)
np.savez_compressed(
    f"{OUTPUT_DIR}/batch_demo/attention_word.npz",
    data=attn_data,
    n_layers=word_attn.shape[0],
    n_heads=word_attn.shape[1],
)

attn_index.to_csv(f"{OUTPUT_DIR}/batch_demo/attention_word_index.csv", index=False)
print(f"Wrote word-level attention to {OUTPUT_DIR}/batch_demo/attention_word.npz")
print(f"Wrote attention index to {OUTPUT_DIR}/batch_demo/attention_word_index.csv")
Wrote word-level attention to model_outputs/batch_demo/attention_word.npz
Wrote attention index to model_outputs/batch_demo/attention_word_index.csv

To load and reconstruct the attention scores we just wrote to the np file:

In [19]:
attn_file = np.load(f"{OUTPUT_DIR}/batch_demo/attention_word.npz")

attn_data = attn_file["data"]
n_layers, n_heads = int(attn_file["n_layers"]), int(attn_file["n_heads"])

# get the index metadata for attention scores
attn_index = pd.read_csv(f"{OUTPUT_DIR}/batch_demo/attention_word_index.csv")
attn_index = attn_index.set_index(["Item", "Condition"])

def get_attn_per_sentence(attn_data, attn_index, item, cond):
    '''
    Reconstruct word-level attention score from attention data for one sentence.
    Returns a tensor (layers, heads, n_words, n_words)
    '''
    sent_meta = attn_index.loc[(item, cond)]
    # get the corresponding slice of flat attention score for this sentence
    flat_attn = attn_data[sent_meta["offset"] : sent_meta["offset"] + sent_meta["size"]]

    result = flat_attn.reshape(n_layers, n_heads, sent_meta["n_words"], sent_meta["n_words"])

    return result

# attention scores for the first sentence, which is item 1 condition a
word_attn_first_sent_loaded = get_attn_per_sentence(attn_data, attn_index, 1, "a")
print(f"Shape of attention scores for the first sentence: {word_attn_first_sent_loaded.shape}")
Shape of attention scores for the first sentence: (12, 12, 16, 16)

3. Putting things together¶

In this section, we are going to process the whole stimuli set of Dillon et al. (2013), generating both the surprisal and the attention score distribution for each word.

In [20]:
def extract_attention_scores(attentions, batch, current_offset):
    '''
    Extract word-level attention scores from token-level attentions.
    Args:
        attentions: List of token-level attention tensors.
        batch: Batch of sentences.
        current_offset: Current offset in the flattened attention array.

    Returns:
        flat_attn_scores: List of flattened word-level attention arrays.
        meta_index: List of metadata dictionaries for each sentence.
        current_offset: Updated offset after processing the batch.
    '''
    # one flattened attention array per sentence, one metadata row per sentence
    flat_attn_scores, meta_index = [], []

    # Token-level attention: (batch, layers, heads, query_seq_len, key_seq_len)
    attn_all = torch.stack(attentions, dim=1).float().cpu()

    for b, (group_key, group) in enumerate(batch):
        n = len(group)
        word_id_for_tokens = group["Word_id"].to_numpy() - 1    
        word_attn = token_to_word_attention(attn_all[b, :, :, :n, :n], word_id_for_tokens)

        # float32 to float16 to save memory
        word_attn = word_attn.half().numpy()  # (layers, heads, n_words, n_words)

        item, cond = group_key
        flat_attn_scores.append(word_attn.ravel()) # flatten to 1D
        meta_index.append({"Item": item, 
                        "Condition": cond,
                        "n_words": word_attn.shape[-1],
                        "offset": current_offset, 
                        "size": word_attn.size})
        current_offset += word_attn.size

    return flat_attn_scores, meta_index, current_offset


def save_attention_scores(flat_attn_scores, n_layers, n_heads, output_path):
    '''
    Save the flattened attention scores and metadata to a compressed .npz file.

    Args:
        flat_attn_scores: List of flattened word-level attention arrays.
        n_layers: Number of layers in the attention model.
        n_heads: Number of heads in the attention model.
        output_path: Path to save the .npz file.

    No returns
    '''
    attn_data = np.concatenate(flat_attn_scores)

    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    np.savez_compressed(
        output_path,
        data=attn_data,
        n_layers=n_layers,
        n_heads=n_heads,
    )
    print(f"Wrote word-level attention for {len(flat_attn_scores)} sentences to {output_path}")

Below is the function to align tokenization for surprisals, taken from Part 2.

In [21]:
def align_tokenization(token_surp_df):
    '''
    - Surprisal: Reduce token-level surprisals to word-level by summing over tokens that belong to 
        the same word. NaN if any token is NaN (e.g., the first token of a sentence)
    - Entropy: Reduce token-level predictive entropies to word-level by taking the entropy of 
        the first token

    Returns a new DataFrame with tokenization aligned
    '''

    token_cols = ["token_id", "hftoken", "token_surprisal", "token_entropy"]
    word_cols = [c for c in token_surp_df.columns if c not in token_cols + ["global_word_id"]]

    g = token_surp_df.groupby("global_word_id", sort=False)

    aligned_df = g[word_cols].first()     
    aligned_df["hftokens"] = g["hftoken"].agg(list)
    aligned_df["word_surprisal"] = g["token_surprisal"].agg(lambda x: x.sum(skipna=False)) # if any token is NaN, the word surprisal will be NaN
    aligned_df["word_entropy"] = g["token_entropy"].agg(lambda x: x.iloc[0])

    return aligned_df.reset_index(drop=True)

Now, let's put these previous functions into one big function called surprisal_with_attention(). This function will take the preprocessed stimuli DataFrame words_df. It will

  • Return a new DataFrame with additional columns for LM surprisals.
  • Write attention score data and the indexing metadata to the output dir.

Like Part 2, we need to specify through groupby_col what are the columns in the stimuli that uniquely identify a sentence.

I set the default batch size to be 4. But you can also try bigger batch size. It won't make a big difference here because our stimuli set is relatively small, but usually bigger batch size can be faster if you have a big set of sentences to process. If a memory issue occurs, you can always switch to a smaller batch size.

In [22]:
def surprisal_with_attention(
    model, 
    tokenizer,
    words_df, 
    groupby_col,
    attention_path=f"{OUTPUT_DIR}/attention_word.npz",
    use_nats=False,
    batch_size=4,
    device=device
):
    """
    Get word surprisals and entropies.
    Token surprisals are summed if belonging to the same word.

    Args:
        model: Language model object (e.g., GPT-2)
        tokenizer: tokenizer object corresponding to the model
        words_df: DataFrame containing the words data
        groupby_col: column names to group by for coherent discourse (e.g., ["Item", "Condition"])
        attention_path: where to save the word-level attention scores
        use_nats: whether to use log probabilities in nats (True) or in bits (False)
        batch_size: number of sequences to process simultaneously in a batch
        device: the fastest available device (e.g., "cuda", "mps", or "cpu")
    
    Returns: a tuple (word_surprisal_df, attn_index)
        A new DataFrame with word-level surprisals and entropies, aligned with the original words_df.
        A DataFrame with global indexing metadata for attention scores.
    
    Writes word-level attention scores to attention_path.
    """
    model.eval().to(device)

    tokens_df = tokenize_words(words_df, tokenizer)

    if isinstance(groupby_col, str):
        groupby_col = [groupby_col]
    missing = [col for col in groupby_col if col not in tokens_df.columns]
    assert not missing, f"Columns not found in tokens_df: {missing}"

    pad_value = tokenizer.eos_token_id
    if tokenizer.pad_token_id is not None:
        pad_value = tokenizer.pad_token_id
    
    text_groups = list(tokens_df.groupby(groupby_col, sort=False))


    all_out = []

    # global indexing metadata for attention scores
    all_flat_attn, all_attn_meta = [], []
    attn_offset = 0

    # loop through the text groups in batches
    for i in range(0, len(text_groups), batch_size):

        batch = text_groups[i:i + batch_size]

        token_lists = [group['token_id'].tolist() for _, group in batch] # list of tokens of batch size
        max_len = max(len(x) for x in token_lists) # the maximal length of the sentences in the batch

        # Check sequence length
        max_pos = getattr(model.config, "n_positions", None) or getattr(model.config, "max_position_embeddings", None)
        if max_pos is not None and max_len > max_pos:
            raise IndexError(f"Sequence too long: {max_len} > {max_pos}. Use sliding windows instead.")
        
        # tensor of pad values of the shape (batch_size, max_len)
        inputs = torch.full((len(token_lists), max_len), pad_value, dtype=torch.long, device=device)

        attention_mask = torch.zeros(len(token_lists), max_len, dtype=torch.long, device=device)

        for b, token_list in enumerate(token_lists):
            inputs[b, :len(token_list)] = torch.tensor(token_list, dtype=torch.long, device=device)
            attention_mask[b, :len(token_list)] = 1


        # generating log probability distributions for the batch
        with torch.no_grad():
            output = model(inputs, attention_mask=attention_mask, output_attentions=True)
            logits = output.logits  # shape: (batch_size, n_tokens, vocab_size)
            log_probs = logits.log_softmax(dim=-1).cpu()  # shape: (batch_size, n_tokens, vocab_size)
            entropies = torch.distributions.Categorical(logits=log_probs).entropy()

        # check if attention scores are returned
        if output.attentions is None or output.attentions[0] is None:
            raise ValueError('No attention scores returned. Load the model with attn_implementation="eager" and output_attentions=True.')
        

        #### Extract surprisal and entropy
        
        target_ids = inputs[:, 1:].cpu()  # target token at t predicted from logits at t-1, shape: (batch_size, seq_len-1)

        # log_probs[:, :-1, :] removes the last token's log_prob distribution, shape: (batch_size, seq_len-1, vocab_size)
        # target_ids[:, :, None] add another dimension for vocab_size, shape: (batch_size, seq_len-1, 1) 
        token_logps = log_probs[:, :-1, :].gather(
            dim=-1, # along the vocab_size dimension, gather the entry corresponding to the target token id
            index=target_ids[:, :, None]
        ).squeeze(-1)

        if not use_nats:
            token_logps = token_logps / np.log(2)  # convert to bits
            entropies = entropies / np.log(2)

        for b, (_, group) in enumerate(batch):
            group = group.copy()
            n = len(group)
            logp_array = np.full(n, np.nan) # shape: (n_tokens)

            # first token logp of a sequence is always nan
            logp_array[1:] = token_logps[b, :n-1].numpy()
            group["token_surprisal"] = -logp_array

            entropy_array = np.full(n, np.nan) # shape: (n_tokens)
            entropy_array[1:] = entropies[b, :n-1].numpy()
            group["token_entropy"] = entropy_array

            all_out.append(group)

        #### Extract attention scores for the batch
        flat_attn_scores, meta_index, attn_offset = extract_attention_scores(output.attentions, batch, attn_offset)
        all_flat_attn.extend(flat_attn_scores)
        all_attn_meta.extend(meta_index)


    token_surprisal_df = pd.concat(all_out, ignore_index=True)
    word_surprisal_df = align_tokenization(token_surprisal_df)

    # Wrote word-level attention scores to attention_path
    save_attention_scores(
        all_flat_attn,
        n_layers=len(output.attentions),
        n_heads=output.attentions[0].shape[1],
        output_path=attention_path,
    )

    # DataFrame with global indexing metadata for attention scores
    attn_index = pd.DataFrame(all_attn_meta)

    return word_surprisal_df, attn_index
In [23]:
surprisal_result, attn_index = surprisal_with_attention(
    model=model,
    tokenizer=tokenizer,
    words_df=words_df,
    groupby_col=["Item", "Condition"],
    attention_path=f"{OUTPUT_DIR}/DillonEtAl2013/attention_word.npz",
    use_nats=False,
    batch_size=4,
    device=device
)

surprisal_result.to_csv(f"{OUTPUT_DIR}/DillonEtAl2013/word_surprisal.csv", index=False)
attn_index.to_csv(f"{OUTPUT_DIR}/DillonEtAl2013/attention_word_index.csv", index=False)
Wrote word-level attention for 384 sentences to model_outputs/DillonEtAl2013/attention_word.npz

4. Analyze model outputs¶

After completing the steps above, you should now have three model_outputs files in your output directory:

  • word_surprisal.csv
  • attention_word_index.csv
  • attention_word.npz

For each sentence, we will look at the attention score distribution at the critical word (main verb or the reflexive) of Dillon et al. 2013.

In Ryu and Lewis (2021), the authors analyzed attention head4_3 and head1_5, which has been identified by the authors as taking charge of processing subject--verb agreement and reflexives respectively. So we will look at the attention score distribution from these two heads specifically.

In [24]:
# load the attention scores and metadata

attn_file = np.load(f"{OUTPUT_DIR}/DillonEtAl2013/attention_word.npz")

attn_data = attn_file["data"]
n_layers, n_heads = int(attn_file["n_layers"]), int(attn_file["n_heads"])

attn_index = pd.read_csv(f"{OUTPUT_DIR}/DillonEtAl2013/attention_word_index.csv")
attn_index = attn_index.set_index(["Item", "Condition"])

The paper used a metric called attention entropy, which measures how sharply focused (low entropy) or diffused (high entropy) the attention pattern is:

$$ \text{AttnEntropy}_{l,h}(w_i) = -\sum_{j=1}^{i-1} \text{Attn}_{l,h}(w_i, w_j) \, \log_2 \text{Attn}_{l,h}(w_i, w_j) $$

where $l$ and $h$ are the layer and head indices (e.g., $l=4, h=3$ for head4_3).

In [25]:
def attention_entropy(attn_row):
    '''
    A variant of shannon entropy of the attention one word pays to the words before it.
    '''
    p = attn_row[attn_row > 0] 
    return float(-(p * np.log2(p)).sum())
In [26]:
HEADS = {"agreement": (4, 3), "reflexives": (1, 5)}

def interference(gram, attr):
    '''
    Interfering = attractor number matches the number on the critical word.
    '''
    return "int" if (gram == "grammatical") == (attr == "singular") else "non-int"

sentences = surprisal_result.drop_duplicates(["Item", "Condition"]) 
rows = []

for _, sent in sentences.iterrows():
    words = sent["Sentence"].split()
    crit = sent["Crit_region"] - 1  # critical word (was/were, himself/herself/themselves)
    subj = words.index("who") - 1   # target noun position: subject noun right before "who"
    attr = crit - 2 if sent["Dep"] == "agreement" else crit - 3  # attractor noun position
    layer, head = HEADS[sent["Dep"]]

    # (layer, head, seq_len, seq_len)
    attn = get_attn_per_sentence(attn_data, attn_index, sent["Item"], sent["Condition"]).astype(np.float32)
    # selecting the attention head at (layer, head)
    attn_row = attn[layer, head, crit, :crit]  # from the critical word to previous words only

    rows.append({
        "Item": sent["Item"], "Condition": sent["Condition"],
        "Dep": sent["Dep"], "Gram": sent["Gram"], "Attr": sent["Attr"],
        "Interference": interference(sent["Gram"], sent["Attr"]),
        "head": f"head{layer}_{head}",
        "attn_entropy": attention_entropy(attn_row),
        "attn_to_target": attn_row[subj],
        "attn_to_distractor": attn_row[attr],
    })

attn_metrics = pd.DataFrame(rows)
crit_surp = surprisal_result[surprisal_result["Word_id"] == surprisal_result["Crit_region"]]
analysis_df = attn_metrics.merge(crit_surp[["Item", "Condition", "word_surprisal"]], on=["Item", "Condition"])
In [27]:
import matplotlib.pyplot as plt

metrics = {"word_surprisal": "Surprisal (bits)",
           "attn_entropy": "Attention entropy (bits)",
           "attn_to_target": "Attention to target"}

summary = analysis_df.groupby(["Dep", "Gram", "Interference"])[list(metrics)].agg(["mean", "sem"])

int_order = ["non-int", "int"]
gram_styles = {
    "grammatical":   dict(color="#257de0", marker="o", linestyle="-"),
    "ungrammatical": dict(color="#f47230", marker="s", linestyle="--"),
}

fig, axes = plt.subplots(2, 3, figsize=(11, 6.5))
for r, dep in enumerate(["agreement", "reflexives"]):
    head = analysis_df.loc[analysis_df["Dep"] == dep, "head"].iloc[0]
    for c, (metric, label) in enumerate(metrics.items()):
        ax = axes[r, c]
        for gram, style in gram_styles.items():
            d = summary.loc[(dep, gram)].loc[int_order, metric]
            ax.errorbar(range(2), d["mean"], yerr=d["sem"], capsize=4, linewidth=2,
                        markersize=7, label=gram.capitalize(), **style)
        ax.set_xticks(range(2), ["Non-interfering", "Interfering"])
        ax.set_xlim(-0.4, 1.4)
        title = f"{dep.capitalize()}: {label}"
        if metric != "word_surprisal":
            title += f"\n({head})"
        ax.set_title(title, fontsize=10)
        ax.grid(axis="y", color="#e5e5e5", linewidth=0.8)
        ax.set_axisbelow(True)
        for side in ["top", "right"]:
            ax.spines[side].set_visible(False)

axes[0, 2].legend(title="Grammaticality", frameon=False, fontsize=9)
fig.tight_layout()
plt.show()
No description has been provided for this image

We can see that, as reported in Ryu and Lewis (2021), the attention entropy is higher for ungrammatical conditions overall. Moreover, for subject--verb agreement, there is an attraction effect, where the attention entropy is much higher in the interfering condition of ungrammatical sentences. In other words, the attention distribution is more diffused for ungrammatical sentences when there is the attractor matches the number feature of the main verb.