Get word embeddings from transformer model

Hi

I would like to plot semantic space for specific words. Usually, we use word embeddings for this. But model I use (xlm-roberta) deala with language on the level of part of words (BPE tokens). It means that if I give to the model a word ‘hello’ I will get 2-3 vectors for each part of this word, right?

model(**tokenizer('hello', return_tensors="tf"),output_hidden_states=True)
# hidden states are embedding I suppose

So, what is the best approach to get one single vector to plot?

To be clear what do I mean by semantic space:

1 Like

I’m not sure what’s the best approach since I’m not an expert in this :slight_smile: , but you can always do mean pooling to the output. Here is a working example


from transformers import AutoTokenizer, AutoModelForMaskedLM

def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)
    sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
    return sum_embeddings / sum_mask
  
tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
model = AutoModelForMaskedLM.from_pretrained("xlm-roberta-base")
encoded_input = tokenizer("hello", return_tensors='pt')
model_output = model(**encoded_input)
mean_pooling(model_output, encoded_input['attention_mask'])

This is inspired in sentence transformers :slight_smile:

3 Likes