Getting Bert Embeddings in Batch
Hi all

I have a list of sentences(a batch during training) and for every word in each sentence, I need an aligned bert embedding which should be the mean of every word-piece that word was split into.

Right now, I am doing it sentence by sentence and obtain the aligned embedding for every word by reiterating over the sentence, tokenise the individual word, note the number of word-pieces it was split into and lookup into the Bert embedding matrix to average out those rows of the matrix. Following is the code to get the aligned embeddings:

`
  
       def get_bert_aligned_embeddings(self, last_hidden_states, tokens):     

            count = 0
            aligned_embeddings = []

            for i in tokens:

                 tokenisation_length = len(self.tokenizer.tokenize(i))

                 emb = torch.mean(last_hidden_states[count:count+tokenisation_length], axis = 0)

                 count += tokenisation_length

                 aligned_embeddings.append(emb)


            aligned_embeddings = torch.stack(aligned_embeddings)

            return aligned_embeddings
`

tokens is the list of words in a sentence, last_hidden_states are the embeddings I obtained from Bert. 

So, the above function runs for every sentence and every sentence is passed one by one to Bert Model. 

I want to know if there is any faster way of doing this? Can this entire process be done in batches? Any suggestions that could help me speed up this process would be great. Thanks
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
