from transformers import AutoTokenizer, AutoModelimport torch
#CLS Pooling - Take output from first tokendef cls_pooling(model_output): return model_output.last_hidden_state[:,0]
#Encode textdef encode(texts): # Tokenize sentences encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
# Compute token embeddings with torch.no_grad(): model_output = model(**encoded_input, return_dict=True)
# Perform pooling embeddings = cls_pooling(model_output)
return embeddings
# Sentences we want sentence embeddings forquery = "How many people live in London?"docs = ["Around 9 Million people live in London", "London is known for its financial district"]
# Load model from HuggingFace Hubtokenizer = AutoTokenizer.from_pretrained("sentence-transformers/msmarco-distilbert-base-tas-b")model = AutoModel.from_pretrained("sentence-transformers/msmarco-distilbert-base-tas-b")
#Encode query and docsquery_emb = encode(query)doc_emb = encode(docs)
#Compute dot score between query and all document embeddingsscores = torch.mm(query_emb, doc_emb.transpose(0, 1))[0].cpu().tolist()
#Combine docs & scoresdoc_score_pairs = list(zip(docs, scores))
#Sort by decreasing scoredoc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
#Output passages & scoresfor doc, score in doc_score_pairs: print(score, doc)