| from transformers import AutoTokenizer, AutoModel
|
| import torch
|
| import torch.nn.functional as F
|
|
|
|
|
| def mean_pooling(model_output, attention_mask):
|
| token_embeddings = model_output.last_hidden_state
|
| input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
|
|
|
|
|
|
| def encode(texts, tokenizer, model, device='cpu'):
|
|
|
| encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
|
| encoded_input.to(device)
|
|
|
|
|
| with torch.no_grad():
|
| model_output = model(**encoded_input, return_dict=True)
|
|
|
|
|
| embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
|
|
|
|
| embeddings = F.normalize(embeddings, p=2, dim=1)
|
|
|
| embeddings = embeddings.to(device)
|
|
|
| return embeddings
|
|
|
|
|
| def get_embeddings(batch_size, tokenizer, model, captions=None, neg_captions=None, device='cpu'):
|
| embeddings = encode([""]*batch_size, tokenizer, model, device)
|
|
|
| if captions is not None:
|
| caption_embeddings = encode(captions, tokenizer, model, device)
|
| embeddings = torch.cat((embeddings, caption_embeddings), dim=0)
|
|
|
| if neg_captions is not None:
|
| neg_embeddings = encode(neg_captions, tokenizer, model, device)
|
| embeddings = torch.cat((neg_embeddings, embeddings), dim=0)
|
|
|
|
|
| embeddings = embeddings.unsqueeze(1)
|
|
|
| return embeddings
|
|
|
|
|
|
|
|
|
| def get_embeddings_split(batch_size, tokenizer, model, captions=None, neg_captions=None, device='cpu', max_length=20):
|
|
|
| padding_length = max(max([s.count(".") for s in captions]) if captions else 1,
|
| max([s.count(".") for s in neg_captions]) if neg_captions else 1)
|
| if (padding_length>max_length):
|
| raise ValueError(f"Token sequence length {padding_length} exceeds specified length {max_length}.")
|
|
|
|
|
| empty_split = split_sentences([""] * batch_size, padding_length)
|
| embeddings = get_embeddings_from_split(empty_split, tokenizer, model, device)
|
|
|
| if(captions is not None):
|
| captions_split = split_sentences(captions, padding_length)
|
| caption_embeddings = get_embeddings_from_split(captions_split, tokenizer, model, device)
|
| embeddings = torch.cat((embeddings, caption_embeddings), dim=0)
|
|
|
| if(neg_captions is not None):
|
| neg_split = split_sentences(neg_captions, padding_length)
|
| neg_embeddings = get_embeddings_from_split(neg_split, tokenizer, model, device)
|
| embeddings = torch.cat((neg_embeddings, embeddings), dim=0)
|
|
|
|
|
|
|
|
|
| return embeddings.to(device)
|
|
|
|
|
|
|
| def split_sentences(caption_array, padding_length=20):
|
| split_caption_array = []
|
|
|
|
|
| for caption in caption_array:
|
| split_caption = [s.strip() for s in caption.split(".") if s.strip()]
|
|
|
| split_caption += [""] * (padding_length - len(split_caption))
|
| split_caption_array.append(split_caption)
|
|
|
| return split_caption_array
|
|
|
|
|
|
|
| def get_embeddings_from_split(caption_batch, tokenizer, model, device='cpu'):
|
| all_caption_encodings = []
|
| for caption_sequence in caption_batch:
|
|
|
| caption_sequence = encode(caption_sequence, tokenizer, model, device)
|
|
|
|
|
| all_caption_encodings.append(caption_sequence)
|
|
|
| all_caption_encodings = torch.stack(all_caption_encodings, dim=0)
|
| return all_caption_encodings
|
|
|
|
|
|
|
| if __name__ == "__main__":
|
| cap = split_sentences(["Hello. My name is George. How. Are you doing. Today?", "I am doing. Just fine. Thanks."])
|
| model_url = "sentence-transformers/multi-qa-MiniLM-L6-cos-v1"
|
| device = 'cuda'
|
| tokenizer = AutoTokenizer.from_pretrained(model_url)
|
| model = AutoModel.from_pretrained(model_url, trust_remote_code=True).to(device)
|
| get_embeddings_from_split(cap, tokenizer, model, device)
|
|
|