This is a PyLate model finetuned from colbert-ir/colbertv2.0. It maps sentences & paragraphs to sequences of 128-dimensional dense vectors and can be used for semantic textual similarity using the MaxSim operator.
PyLate provides a streamlined interface to index and retrieve documents using ColBERT models. The index leverages the Voyager HNSW index to efficiently handle document embeddings and enable fast retrieval.
Indexing documents
First, load the ColBERT model and initialize the Voyager index, then encode and index your documents:
python
1from pylate import indexes, models, retrieve
23# Step 1: Load the ColBERT model4model = models.ColBERT(5 model_name_or_path=NohTow/colbertv2.0,6)78# Step 2: Initialize the Voyager index9index = indexes.Voyager(10 index_folder="pylate-index",11 index_name="index",12 override=True,# This overwrites the existing index if any13)1415# Step 3: Encode the documents16documents_ids =["1","2","3"]17documents =["document 1 text","document 2 text","document 3 text"]1819documents_embeddings = model.encode(20 documents,21 batch_size=32,22 is_query=False,# Ensure that it is set to False to indicate that these are documents, not queries23 show_progress_bar=True,24)2526# Step 4: Add document embeddings to the index by providing embeddings and corresponding ids27index.add_documents(28 documents_ids=documents_ids,29 documents_embeddings=documents_embeddings,30)
Note that you do not have to recreate the index and encode the documents every time. Once you have created an index and added the documents, you can re-use the index later by loading it:
python
1# To load an index, simply instantiate it with the correct folder/name and without overriding it2index = indexes.Voyager(3 index_folder="pylate-index",4 index_name="index",5)
Retrieving top-k documents for queries
Once the documents are indexed, you can retrieve the top-k most relevant documents for a given set of queries.
To do so, initialize the ColBERT retriever with the index you want to search in, encode the queries and then retrieve the top-k documents to get the top matches ids and relevance scores:
python
1# Step 1: Initialize the ColBERT retriever2retriever = retrieve.ColBERT(index=index)34# Step 2: Encode the queries5queries_embeddings = model.encode(6["query for document 3","query for document 1"],7 batch_size=32,8 is_query=True,# # Ensure that it is set to False to indicate that these are queries9 show_progress_bar=True,10)1112# Step 3: Retrieve top-k documents13scores = retriever.retrieve(14 queries_embeddings=queries_embeddings,15 k=10,# Retrieve the top 10 matches for each query16)
Reranking
If you only want to use the ColBERT model to perform reranking on top of your first-stage retrieval pipeline without building an index, you can simply use rank function and pass the queries and documents to rerank: