Delete sentence_transformers_helper.py
Browse files- sentence_transformers_helper.py +0 -114
sentence_transformers_helper.py
DELETED
|
@@ -1,114 +0,0 @@
|
|
| 1 |
-
from transformers import AutoTokenizer, AutoModel
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn.functional as F
|
| 4 |
-
|
| 5 |
-
#Mean Pooling - Take average of all tokens
|
| 6 |
-
def mean_pooling(model_output, attention_mask):
|
| 7 |
-
token_embeddings = model_output.last_hidden_state
|
| 8 |
-
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 9 |
-
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
#Encode text
|
| 13 |
-
def encode(texts, tokenizer, model, device='cpu'):
|
| 14 |
-
# Tokenize sentences
|
| 15 |
-
encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
|
| 16 |
-
encoded_input.to(device)
|
| 17 |
-
|
| 18 |
-
# Compute token embeddings
|
| 19 |
-
with torch.no_grad():
|
| 20 |
-
model_output = model(**encoded_input, return_dict=True)
|
| 21 |
-
|
| 22 |
-
# Perform pooling
|
| 23 |
-
embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
| 24 |
-
|
| 25 |
-
# Normalize embeddings
|
| 26 |
-
embeddings = F.normalize(embeddings, p=2, dim=1)
|
| 27 |
-
|
| 28 |
-
embeddings = embeddings.to(device)
|
| 29 |
-
|
| 30 |
-
return embeddings
|
| 31 |
-
|
| 32 |
-
# Get embeddings for a batch of captions and optional negative captions
|
| 33 |
-
def get_embeddings(batch_size, tokenizer, model, captions=None, neg_captions=None, device='cpu'):
|
| 34 |
-
embeddings = encode([""]*batch_size, tokenizer, model, device)
|
| 35 |
-
|
| 36 |
-
if captions is not None:
|
| 37 |
-
caption_embeddings = encode(captions, tokenizer, model, device)
|
| 38 |
-
embeddings = torch.cat((embeddings, caption_embeddings), dim=0)
|
| 39 |
-
|
| 40 |
-
if neg_captions is not None:
|
| 41 |
-
neg_embeddings = encode(neg_captions, tokenizer, model, device)
|
| 42 |
-
embeddings = torch.cat((neg_embeddings, embeddings), dim=0)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
embeddings = embeddings.unsqueeze(1)
|
| 46 |
-
|
| 47 |
-
return embeddings
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
def get_embeddings_split(batch_size, tokenizer, model, captions=None, neg_captions=None, device='cpu', max_length=20):
|
| 53 |
-
|
| 54 |
-
padding_length = max(max([s.count(".") for s in captions]) if captions else 1,
|
| 55 |
-
max([s.count(".") for s in neg_captions]) if neg_captions else 1)
|
| 56 |
-
if (padding_length>max_length):
|
| 57 |
-
raise ValueError(f"Token sequence length {padding_length} exceeds specified length {max_length}.")
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
empty_split = split_sentences([""] * batch_size, padding_length)
|
| 61 |
-
embeddings = get_embeddings_from_split(empty_split, tokenizer, model, device)
|
| 62 |
-
|
| 63 |
-
if(captions is not None):
|
| 64 |
-
captions_split = split_sentences(captions, padding_length)
|
| 65 |
-
caption_embeddings = get_embeddings_from_split(captions_split, tokenizer, model, device)
|
| 66 |
-
embeddings = torch.cat((embeddings, caption_embeddings), dim=0)
|
| 67 |
-
|
| 68 |
-
if(neg_captions is not None):
|
| 69 |
-
neg_split = split_sentences(neg_captions, padding_length)
|
| 70 |
-
neg_embeddings = get_embeddings_from_split(neg_split, tokenizer, model, device)
|
| 71 |
-
embeddings = torch.cat((neg_embeddings, embeddings), dim=0)
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
#We don't need to unsqueeze this, we have an array of (batch_size, padding_length, encoding_size) already
|
| 75 |
-
|
| 76 |
-
return embeddings.to(device)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
#This method takes a caption batch in list form, and outputs a 2d list where every caption has been split by period
|
| 80 |
-
def split_sentences(caption_array, padding_length=20):
|
| 81 |
-
split_caption_array = []
|
| 82 |
-
|
| 83 |
-
#Padding happens here
|
| 84 |
-
for caption in caption_array:
|
| 85 |
-
split_caption = [s.strip() for s in caption.split(".") if s.strip()]
|
| 86 |
-
#This is the token padding, we just use an empty string
|
| 87 |
-
split_caption += [""] * (padding_length - len(split_caption))
|
| 88 |
-
split_caption_array.append(split_caption)
|
| 89 |
-
|
| 90 |
-
return split_caption_array
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
#Expects all split vectors to be the same length
|
| 94 |
-
def get_embeddings_from_split(caption_batch, tokenizer, model, device='cpu'):
|
| 95 |
-
all_caption_encodings = []
|
| 96 |
-
for caption_sequence in caption_batch:
|
| 97 |
-
#Encode the sequence of split captions as if it was a batch, should now be a [maxlength, embeddingsize] tensor
|
| 98 |
-
caption_sequence = encode(caption_sequence, tokenizer, model, device)
|
| 99 |
-
|
| 100 |
-
#We don't reshape this to avoid having to unsqueeze it later
|
| 101 |
-
all_caption_encodings.append(caption_sequence)
|
| 102 |
-
|
| 103 |
-
all_caption_encodings = torch.stack(all_caption_encodings, dim=0)
|
| 104 |
-
return all_caption_encodings
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
if __name__ == "__main__":
|
| 109 |
-
cap = split_sentences(["Hello. My name is George. How. Are you doing. Today?", "I am doing. Just fine. Thanks."])
|
| 110 |
-
model_url = "sentence-transformers/multi-qa-MiniLM-L6-cos-v1"
|
| 111 |
-
device = 'cuda'
|
| 112 |
-
tokenizer = AutoTokenizer.from_pretrained(model_url)
|
| 113 |
-
model = AutoModel.from_pretrained(model_url, trust_remote_code=True).to(device)
|
| 114 |
-
get_embeddings_from_split(cap, tokenizer, model, device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|