Views
No views yet
pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer, util
2
3query = "How many people live in London?"
4docs = ["Around 9 Million people live in London", "London is known for its financial district"]
5
6#Load the model
7model = SentenceTransformer('sentence-transformers/msmarco-bert-base-dot-v5')
8
9#Encode query and documents
10query_emb = model.encode(query)
11doc_emb = model.encode(docs)
12
13#Compute dot score between query and all document embeddings
14scores = util.dot_score(query_emb, doc_emb)[0].cpu().tolist()
15
16#Combine docs & scores
17doc_score_pairs = list(zip(docs, scores))
18
19#Sort by decreasing score
20doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
21
22#Output passages & scores
23print("Query:", query)
24for doc, score in doc_score_pairs:
25 print(score, doc)1from transformers import AutoTokenizer, AutoModel
2import torch
3
4#Mean Pooling - Take attention mask into account for correct averaging
5def mean_pooling(model_output, attention_mask):
6 token_embeddings = model_output.last_hidden_state
7 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
8 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
9
10
11#Encode text
12def encode(texts):
13 # Tokenize sentences
14 encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
15
16 # Compute token embeddings
17 with torch.no_grad():
18 model_output = model(**encoded_input, return_dict=True)
19
20 # Perform pooling
21 embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
22
23 return embeddings
24
25
26# Sentences we want sentence embeddings for
27query = "How many people live in London?"
28docs = ["Around 9 Million people live in London", "London is known for its financial district"]
29
30# Load model from HuggingFace Hub
31tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/msmarco-bert-base-dot-v5")
32model = AutoModel.from_pretrained("sentence-transformers/msmarco-bert-base-dot-v5")
33
34#Encode query and docs
35query_emb = encode(query)
36doc_emb = encode(docs)
37
38#Compute dot score between query and all document embeddings
39scores = torch.mm(query_emb, doc_emb.transpose(0, 1))[0].cpu().tolist()
40
41#Combine docs & scores
42doc_score_pairs = list(zip(docs, scores))
43
44#Sort by decreasing score
45doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
46
47#Output passages & scores
48print("Query:", query)
49for doc, score in doc_score_pairs:
50 print(score, doc)| Setting | Value |
|---|---|
| Dimensions | 768 |
| Max Sequence Length | 512 |
| Produces normalized embeddings | No |
| Pooling-Method | Mean pooling |
| Suitable score functions | dot-product (e.g. util.dot_score) |
train_script.py in this repository for the used training script.torch.utils.data.dataloader.DataLoader of length 7858 with parameters:{'batch_size': 64, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}sentence_transformers.losses.MarginMSELoss.MarginMSELoss{
"callback": null,
"epochs": 30,
"evaluation_steps": 0,
"evaluator": "NoneType",
"max_grad_norm": 1,
"optimizer_class": "<class 'transformers.optimization.AdamW'>",
"optimizer_params": {
"lr": 1e-05
},
"scheduler": "WarmupLinear",
"steps_per_epoch": null,
"warmup_steps": 10000,
"weight_decay": 0.01
}SentenceTransformer(
(0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: bert-base-uncased
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
)1@inproceedings{reimers-2019-sentence-bert,
2 title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
3 author = "Reimers, Nils and Gurevych, Iryna",
4 booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
5 month = "11",
6 year = "2019",
7 publisher = "Association for Computational Linguistics",
8 url = "http://arxiv.org/abs/1908.10084",
9}