Views
No views yet
bfloat16 precision ⚠️1from transformers import AutoTokenizer, AutoModelForTextEncoding
2
3tokenizer = AutoTokenizer.from_pretrained("pszemraj/flan-ul2-text-encoder")
4model = AutoModelForTextEncoding.from_pretrained("pszemraj/flan-ul2-text-encoder")
5
6inputs = tokenizer("Hello, my dog loves memes", return_tensors="pt")
7outputs = model(**inputs)
8
9last_hidden_states = outputs.last_hidden_statenote: this is 'one way' to use the encoder, not 'the only way'. suggestions and ideas welcome.
model_name, returning a tuple containing the loaded model and tokenizer.1from typing import List, Tuple
2
3import torch
4from transformers import AutoModel, AutoTokenizer
5from transformers import AutoModelForTextEncoding
6
7
8def load_model_and_tokenizer(model_name: str) -> Tuple[AutoModel, AutoTokenizer]:
9 """
10 Load the model and tokenizer based on the given model name.
11
12 Args:
13 model_name (str): The name of the model to be loaded.
14
15 Returns:
16 Tuple[AutoModelForTextEncoding, AutoTokenizer]: The loaded model and tokenizer.
17 """
18 model = AutoModelForTextEncoding.from_pretrained(
19 model_name, torch_dtype=torch.bfloat16, device_map="auto"
20 ).eval()
21 tokenizer = AutoTokenizer.from_pretrained(model_name)
22 return model, tokenizer1def get_embeddings(
2 model: AutoModel, tokenizer: AutoTokenizer, texts: List[str]
3) -> torch.Tensor:
4 """
5 compute text embeddings via weighted mean pooling across seq_len
6
7 Args:
8 model (AutoModel): The model to be used for getting embeddings.
9 tokenizer (AutoTokenizer): The tokenizer to be used for tokenizing the texts.
10 texts (List[str]): The texts for which embeddings are to be calculated.
11
12 Returns:
13 torch.Tensor: The calculated embeddings.
14 """
15 # Tokenize input texts
16 batch_tokens = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
17
18 # Get the embeddings
19 with torch.no_grad():
20 last_hidden_state = model(
21 **batch_tokens, output_hidden_states=True, return_dict=True
22 ).last_hidden_state
23
24 # Get weights
25 weights = (
26 torch.arange(start=1, end=last_hidden_state.shape[1] + 1)
27 .unsqueeze(0)
28 .unsqueeze(-1)
29 .expand(last_hidden_state.size())
30 .float()
31 .to(last_hidden_state.device)
32 )
33
34 # Get attn mask
35 input_mask_expanded = (
36 batch_tokens["attention_mask"]
37 .unsqueeze(-1)
38 .expand(last_hidden_state.size())
39 .float()
40 )
41
42 # Perform weighted mean pooling across seq_len: bs, seq_len, hidden_dim -> bs, hidden_dim
43 sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded * weights, dim=1)
44 sum_mask = torch.sum(input_mask_expanded * weights, dim=1)
45
46 embeddings = sum_embeddings / sum_mask
47
48 return embeddings1from scipy.spatial.distance import cosine
2
3def calculate_cosine_similarity(embeddings: torch.Tensor, texts: List[str]) -> None:
4 """compute and print the cosine sim between the first text and all others"""
5 # Calculate cosine similarities
6 for i in range(1, len(embeddings)):
7 cosine_sim = 1 - cosine(embeddings[0], embeddings[i])
8 print(
9 'Cosine similarity between "%s" and "%s" is: %.3f'
10 % (texts[0], texts[i], cosine_sim)
11 )pip install transformers accelerate sentencepiece scipy1model_name = "pszemraj/flan-ul2-text-encoder"
2model, tokenizer = load_model_and_tokenizer(model_name)
3
4texts = [
5 "deep learning",
6 "artificial intelligence",
7 "deep diving",
8 "artificial snow",
9]
10
11embeddings = get_embeddings(model, tokenizer, texts)
12calculate_cosine_similarity(embeddings, texts)@article{muennighoff2022sgpt,
title={SGPT: GPT Sentence Embeddings for Semantic Search},
author={Muennighoff, Niklas},
journal={arXiv preprint arXiv:2202.08904},
year={2022}
}