πŸ†• Haystack 3.5 is here! OpenAI Decisions routers and classifiers, structured output for Agents, and multivector embeddings with MaxSimRanker

Multivector Retrieval and Reranking with Haystack


Dense retrieval is a technique in information retrieval where dense vectors are used to represent and compare queries and documents. In traditional dense retrieval, embedding models produce a single vector for each query and each document.

While being widespread and well supported by several databases, this approach has some limitations: by using a single summary vector for each text, it struggles to capture specific aspects and does not allow for fine-grained interaction between the query and the documents.

In this notebook we’ll explore an alternative approach where each text is represented by multiple vectors, discuss its pros and cons and see how to build retrieval pipelines using Haystack, Sentence Transformers and Qdrant.

Install dependencies

! uv pip install sentence-transformers-haystack qdrant-haystack

Intro to Late Interaction models

Late Interaction models like ColBERT represent queries and documents using multiple vectors, one for each token.

It’s called late interaction because the query and document are encoded independently and their token vectors are compared only at scoring time. Document vectors can therefore be computed during indexing. At retrieval time, the multivector representations of the query and documents are compared using a MaxSim operation. The score of a document is computed as follows:

  • For each token of the query, the most similar token of the document is found.
  • The similarity between the two tokens is added to the score.
  • This process is repeated for all query tokens.

This allows individual tokens of the query and documents to interact, potentially achieving better retrieval quality compared to single-vector approaches.

This improvement comes at a cost:

  • Having more vectors for each document requires more storage and more memory.
  • The MaxSim operation is more expensive than single-vector similarity and cannot benefit from conventional Approximate Nearest Neighbor algorithms in the same way. As a result, it can require more compute and lead to higher retrieval latency.

All in all, direct late interaction retrieval can be worthwhile if you need that extra boost in retrieval quality and your collection is not massive. Another common approach is to perform a single-vector search first to get N candidates and then use precomputed multivector representations to rerank the results.

Follow along with this notebook to see all of this in practice.

Let’s start by looking at what a multivector representation looks like. We’ll be using SentenceTransformersMultivectorTextEmbedder to compute it with a small ColBERT model.

from haystack_integrations.components.embedders.sentence_transformers import SentenceTransformersMultivectorTextEmbedder

colbert_model = "answerdotai/answerai-colbert-small-v1"
query_embedder = SentenceTransformersMultivectorTextEmbedder(model=colbert_model)
query_embedding = query_embedder.run(text="Where do penguins live")["multivector_embedding"]

print(f"The question is represented by {len(query_embedding)} vectors of {len(query_embedding[0])} numbers each.")
print("First 3 vectors, first 5 values of each:")
for vector in query_embedding[:3]:
    print([round(value, 3) for value in vector[:5]])
The question is represented by 32 vectors of 96 numbers each.
First 3 vectors, first 5 values of each:
[-0.083, 0.043, -0.04, -0.0, -0.078]
[-0.098, 0.014, -0.034, 0.011, -0.058]
[-0.102, 0.024, 0.011, -0.075, -0.133]

Build a multivector retrieval pipeline

Time to see multivector retrieval in action.

First, we create some documents about aquatic animals.

from haystack import Document

ANIMAL_DESCRIPTIONS = {
    "AdΓ©lie penguin": "This Antarctic penguin forages among the pack ice. When it is time to raise chicks, "
    "the parents build a pebble nest on exposed rock along the coast.",
    "American oystercatcher": "This shorebird opens shellfish on tidal flats. It uses its long orange "
    "bill to cut the muscle holding the two halves of an oyster together.",
    "Bat ray": "Bat rays search sandy bays for buried shellfish. Broad, flat teeth crush the shells "
    "of clams and the hard coverings of crabs gathered from the seabed.",
    "Bearded seal": "This Arctic seal uses its whiskers to find clams and crabs on the sea floor. "
    "It rests on drifting sea ice between feeding dives.",
    "Beaver": "Beavers are semiaquatic rodents with broad flat tails. They cut trees with their incisors "
    "and build dams from branches and mud.",
    "Bottlenose dolphin": "The bottlenose dolphin is a marine mammal that breathes air through a blowhole. It "
    "uses echolocation to locate fish and navigate underwater.",
    "Capybara": "The capybara is a large South American rodent that lives near water. It swims well "
    "and grazes on grasses and aquatic plants.",
    "Common eider": "This sea duck dives to the bottom of shallow coastal waters for mussels and crabs. "
    "The female lines her nest on land with down from her breast.",
    "Common murre": "The common murre is a black-and-white seabird that catches fish by swimming "
    "underwater with its wings. It also flies to feeding areas and nests on crowded sea "
    "cliffs.",
    "Dugong": "The dugong is a warm-water marine mammal that grazes on seagrass. It is related to "
    "manatees but has a fluked tail rather than a rounded paddle-shaped tail.",
    "Emperor penguin": "The emperor penguin is a flightless bird that breeds on Antarctic sea ice. It dives "
    "into cold ocean water to catch fish and other marine prey.",
    "Eurasian water shrew": "The water shrew dives into freshwater streams to hunt aquatic insects. "
    "A fringe of stiff hairs helps its feet propel it along the streambed.",
    "European water vole": "This swimming rodent grazes on grasses and reeds beside slow streams. "
    "It digs burrows into the riverbank, leaving cropped grass around the entrances.",
    "GalΓ‘pagos penguin": "This penguin dives for small fish around equatorial islands. It shelters its "
    "eggs and chicks from the sun in cracks and hollows in coastal lava.",
    "Green sea turtle": "The green sea turtle is a marine reptile with flippers and a shell. Adults feed "
    "mainly on seagrasses and algae, and females lay eggs on beaches.",
    "Harbor seal": "The harbor seal is a marine mammal found along temperate and cold coasts. It "
    "catches fish underwater and rests on rocks or beaches.",
    "Hawksbill turtle": "The hawksbill is a sea turtle whose diet is dominated by sea sponges. It also eats "
    "other foods, including squid, shrimp, and algae.",
    "King penguin": "The king penguin is a flightless seabird that dives for fish. It breeds in colonies "
    "on ice-free beaches and other open ground on sub-Antarctic islands.",
    "Leatherback turtle": "The leatherback is a marine turtle specialized in eating jellyfish and other "
    "soft-bodied animals. Females come ashore to lay eggs on sandy beaches.",
    "Loggerhead turtle": "The loggerhead is a sea turtle whose powerful jaws crush hard-shelled prey. "
    "Juveniles and adults in coastal waters eat mostly bottom-dwelling invertebrates "
    "such as mollusks and crustaceans.",
    "Manatee": "Manatees are herbivorous aquatic mammals with rounded paddle-shaped tails. They "
    "graze on aquatic vegetation in warm coastal waters and rivers.",
    "Marine iguana": "This GalΓ‘pagos reptile grazes on marine algae on coastal rocks. Large adults "
    "swim offshore and dive to feed before returning to warm themselves on land.",
    "Muskrat": "The muskrat is a semiaquatic rodent with a tail flattened from side to side. It builds lodges "
    "from aquatic plants in marshes and ponds, including ponds created by beaver dams.",
    "Nutria": "Nutria are semiaquatic rodents with large orange front teeth and long, rounded tails. "
    "They live in marshes and rivers and eat aquatic roots and other vegetation.",
    "Ocean sunfish": "This large marine fish eats jellyfish and other drifting prey. It sometimes "
    "lies on its side at the sea surface with a tall fin breaking the water.",
    "Platypus": "The platypus is an Australian mammal that lays eggs. It swims in freshwater "
    "and uses its sensitive bill to find aquatic invertebrates underwater.",
    "Puffin": "The Atlantic puffin is a seabird that can both fly and swim. It nests in burrows on "
    "North Atlantic islands and dives to catch small fish.",
    "Rakali": "The rakali is an Australian water rat with webbed hind feet and a white-tipped tail. "
    "It swims for freshwater prey and leaves piles of discarded shells at its feeding places.",
    "Razorbill": "The razorbill is a North Atlantic seabird that dives for small schooling fish. "
    "A pair raises a single chick on a narrow rock ledge or in a crevice.",
    "Ringed seal": "Ringed seals swim under Arctic sea ice and keep breathing holes open with their claws. "
    "Females nurse their pups in snow lairs above the ice.",
    "River otter": "River otters are semiaquatic mammals with long bodies and muscular tails. "
    "They swim in rivers and lakes and feed on fish and other aquatic animals.",
    "Sea otter": "The sea otter is a marine mammal that often floats on its back. It can use rocks to "
    "break open hard-shelled prey such as mussels.",
    "Walrus": "The walrus is a large Arctic marine mammal with long tusks and sensitive whiskers. "
    "It feeds mainly on bottom-dwelling invertebrates such as clams.",
}

documents = [Document(content=text, meta={"species": name}) for name, text in ANIMAL_DESCRIPTIONS.items()]

We create an in-memory QdrantDocumentStore instance, enrich the documents with their multivector representations using SentenceTransformersMultivectorDocumentEmbedder and store them in Qdrant.

Small note here. Since we will later reuse the same instance to also store dense embeddings using all-MiniLM-L6-v2 for a comparison, we also specify embedding_dim=384 when initializing the document store.

from haystack_integrations.components.embedders.sentence_transformers import (
    SentenceTransformersMultivectorDocumentEmbedder,
)
from haystack_integrations.document_stores.qdrant import QdrantDocumentStore

store = QdrantDocumentStore(location=":memory:", multivector_embedding_dim=96, embedding_dim=384)
document_embedder = SentenceTransformersMultivectorDocumentEmbedder(model=colbert_model)
documents = document_embedder.run(documents=documents)["documents"]
store.write_documents(documents=documents)
Encoding documents: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 2/2 [00:01<00:00,  1.92it/s]
100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 33/33 [00:00<00:00, 954.35it/s]





33

We then create a multivector retrieval pipeline combining SentenceTransformersMultivectorTextEmbedder and QdrantMultivectorEmbeddingRetriever.

from haystack import Pipeline
from haystack_integrations.components.retrievers.qdrant import QdrantMultivectorEmbeddingRetriever

multivector_search = Pipeline()
multivector_search.add_component("embedder", SentenceTransformersMultivectorTextEmbedder(model=colbert_model))
multivector_search.add_component("retriever", QdrantMultivectorEmbeddingRetriever(document_store=store, top_k=3))
multivector_search.connect("embedder.multivector_embedding", "retriever.query_multivector_embedding")
<haystack.core.pipeline.pipeline.Pipeline object at 0x7a4103dcdfd0>
πŸš… Components
  - embedder: SentenceTransformersMultivectorTextEmbedder
  - retriever: QdrantMultivectorEmbeddingRetriever
πŸ›€οΈ Connections
  - embedder.multivector_embedding -> retriever.query_multivector_embedding (list[list[float]])

Let’s try a difficult question.

result = multivector_search.run(data={"embedder": {"text": "Which flightless diving bird raises its young on sea ice?"}})
for doc in result["retriever"]["documents"]:
    print(doc.meta["species"], "-", doc.content)
Emperor penguin - The emperor penguin is a flightless bird that breeds on Antarctic sea ice. It dives into cold ocean water to catch fish and other marine prey.
King penguin - The king penguin is a flightless seabird that dives for fish. It breeds in colonies on ice-free beaches and other open ground on sub-Antarctic islands.
Razorbill - The razorbill is a North Atlantic seabird that dives for small schooling fish. A pair raises a single chick on a narrow rock ledge or in a crevice.

Nice!

Comparing multivector retrieval with dense retrieval

As mentioned earlier, multivector retrieval can require more memory, storage and compute compared to dense retrieval, so before adopting this technique it’s always a good idea to check if it provides an improvement in retrieval quality.

In this simple collection, we’ll try to understand if multivector retrieval is more effective at retrieving the relevant document as the first hit compared to dense retrieval.

Since our documents already contain the multivectors we computed earlier, we just use all-MiniLM-L6-v2 to add the dense embeddings. We then write the documents back to Qdrant with DuplicatePolicy.OVERWRITE, replacing each existing document with one that contains both representations.

from haystack.document_stores.types import DuplicatePolicy
from haystack_integrations.components.embedders.sentence_transformers import (
    SentenceTransformersDocumentEmbedder,
    SentenceTransformersTextEmbedder,
)
from haystack_integrations.components.retrievers.qdrant import QdrantEmbeddingRetriever

dense_model = "sentence-transformers/all-MiniLM-L6-v2"
dense_embedder = SentenceTransformersDocumentEmbedder(model=dense_model)
# Start from the documents with ColBERT vectors so both representations are stored.
documents = dense_embedder.run(documents=documents)["documents"]
store.write_documents(documents=documents, policy=DuplicatePolicy.OVERWRITE)

dense_search = Pipeline()
dense_search.add_component("embedder", SentenceTransformersTextEmbedder(model=dense_model, progress_bar=False))
dense_search.add_component("retriever", QdrantEmbeddingRetriever(document_store=store, top_k=3))
dense_search.connect("embedder.embedding", "retriever.query_embedding")
Batches:   0%|          | 0/2 [00:00<?, ?it/s]


100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 33/33 [00:00<00:00, 736.28it/s]

Let’s do a quick vibe check with two queries and compare the first result from each pipeline.

def first_hit(pipeline, question):
    result = pipeline.run(data={"embedder": {"text": question}})
    return result["retriever"]["documents"][0]

def compare_first_hits(question):
    for name, pipeline in [("MiniLM", dense_search), ("ColBERT", multivector_search)]:
        hit = first_hit(pipeline, question)
        print(f"{name} retrieved {hit.meta['species']}: {hit.content}")


compare_first_hits("Which flightless diving bird raises its young on sea ice?")
MiniLM retrieved King penguin: The king penguin is a flightless seabird that dives for fish. It breeds in colonies on ice-free beaches and other open ground on sub-Antarctic islands.
ColBERT retrieved Emperor penguin: The emperor penguin is a flightless bird that breeds on Antarctic sea ice. It dives into cold ocean water to catch fish and other marine prey.
compare_first_hits("I saw a mammal eating shellfish. Which one floats belly-up and cracks the shells with a stone?")
MiniLM retrieved Ocean sunfish: This large marine fish eats jellyfish and other drifting prey. It sometimes lies on its side at the sea surface with a tall fin breaking the water.
ColBERT retrieved Sea otter: The sea otter is a marine mammal that often floats on its back. It can use rocks to break open hard-shelled prey such as mussels.

We now run a retrieval evaluation with 13 queries, measuring how often the relevant document is retrieved in the first position (Hit@1).

Keep in mind that this is a small, illustrative evaluation. Differences in quality cannot be attributed solely to multivector representation.

OBSERVATIONS = [
    (
        "Which swimming rodent cuts trees and uses branches and mud to dam streams?",
        "Beaver",
    ),
    (
        "I saw a rodent swimming by a dam. Which one builds its own lodge from reeds and has a tail flattened sideways?",
        "Muskrat",
    ),
    (
        "A grazing rodent surfaced in the marsh. I could see orange incisors and a round tail. What was it?",
        "Nutria",
    ),
    (
        "Which mammal searches the riverbed with its bill and lays eggs?",
        "Platypus",
    ),
    (
        "I saw a mammal eating shellfish. Which one floats belly-up and cracks the shells with a stone?",
        "Sea otter",
    ),
    (
        "Two marine mammals graze in shallow water. Which one has a rounded paddle for a tail?",
        "Manatee",
    ),
    (
        "Which seagrass eater has a whale-like fluke at the end of its tail?",
        "Dugong",
    ),
    (
        "Which flightless diving bird raises its young on sea ice?",
        "Emperor penguin",
    ),
    (
        "Which penguin dives for fish but breeds on bare beaches on sub-Antarctic islands?",
        "King penguin",
    ),
    (
        "Which diving seabird flies out to fish and raises its chick in a burrow?",
        "Puffin",
    ),
    (
        "Which turtle comes ashore to nest but spends its time at sea hunting jellyfish?",
        "Leatherback turtle",
    ),
    (
        "Which sea turtle uses powerful jaws to break open crabs and shellfish on the seabed?",
        "Loggerhead turtle",
    ),
    (
        "Which sea turtle grazes on seagrass as an adult and lays eggs on the beach?",
        "Green sea turtle",
    ),
]

for name, pipeline in [("MiniLM", dense_search), ("ColBERT", multivector_search)]:
    hits = sum(first_hit(pipeline, question).meta["species"] == expected for question, expected in OBSERVATIONS)
    print(f"{name} Hit@1: {hits}/{len(OBSERVATIONS)} ({hits / len(OBSERVATIONS):.1%})")
MiniLM Hit@1: 6/13 (46.2%)
ColBERT Hit@1: 11/13 (84.6%)

Two-stage retrieval: use multivector representations for reranking

Direct multivector retrieval computes token-level similarity scores across all documents. As a collection grows, this can become expensive.

In such cases, a common approach is two-stage retrieval: use dense embeddings to retrieve a certain number of candidates, then use multivector representations to rerank them with finer-grained scoring.

In Haystack, you can use MaxSimRanker for this purpose.

Note that at this point we only compute the query multivector. Qdrant returns the multivectors we stored during indexing along with the candidate documents.

Here is the retrieval pipeline.

from haystack.components.rankers import MaxSimRanker

two_stage_search = Pipeline()
two_stage_search.add_component("dense_embedder", SentenceTransformersTextEmbedder(model=dense_model, progress_bar=False))
two_stage_search.add_component("multivector_embedder", SentenceTransformersMultivectorTextEmbedder(model=colbert_model))
two_stage_search.add_component("embedding_retriever", QdrantEmbeddingRetriever(document_store=store, top_k=5, return_embedding=True))
two_stage_search.add_component("ranker", MaxSimRanker(top_k=3))
two_stage_search.connect("dense_embedder.embedding", "embedding_retriever.query_embedding")
two_stage_search.connect("embedding_retriever.documents", "ranker.documents")
two_stage_search.connect("multivector_embedder.multivector_embedding", "ranker.query_multivector_embedding")
<haystack.core.pipeline.pipeline.Pipeline object at 0x7a4102136520>
πŸš… Components
  - dense_embedder: SentenceTransformersTextEmbedder
  - multivector_embedder: SentenceTransformersMultivectorTextEmbedder
  - embedding_retriever: QdrantEmbeddingRetriever
  - ranker: MaxSimRanker
πŸ›€οΈ Connections
  - dense_embedder.embedding -> embedding_retriever.query_embedding (list[float])
  - multivector_embedder.multivector_embedding -> ranker.query_multivector_embedding (list[list[float]])
  - embedding_retriever.documents -> ranker.documents (list[Document])

Let’s try a challenging question. We use include_outputs_from to also inspect the initial candidates.

beaver_question = "Which swimming rodent cuts trees and uses branches and mud to dam streams?"

result = two_stage_search.run(
    data={"dense_embedder": {"text": beaver_question}, "multivector_embedder": {"text": beaver_question}},
    include_outputs_from={"embedding_retriever"},
)
print("Dense shortlist:", [doc.meta["species"] for doc in result["embedding_retriever"]["documents"]])
print("After reranking:", [doc.meta["species"] for doc in result["ranker"]["documents"]])
Dense shortlist: ['European water vole', 'Eurasian water shrew', 'Capybara', 'Beaver', 'Muskrat']
After reranking: ['Beaver', 'European water vole', 'Muskrat']

Not bad! ColBERT did a good reranking.

Of course, the effectiveness of this approach also depends on the first retrieval stage: the ranker can only rerank the documents that have been retrieved as candidates.

Additional components

As an alternative to Sentence Transformers, you can compute multivector embeddings using vLLM with VLLMMultivectorTextEmbedder and VLLMMultivectorDocumentEmbedder.

In addition to Qdrant, Haystack’s multivector support extends to OpenSearch with OpenSearchMultivectorEmbeddingRetriever.

(Notebook by Stefano Fiorucci)