---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://mixpeek.com/.well-known/search?q={query}"
  method: GET
  documentation: "https://mixpeek.com/llms.txt"
---

Embeddings

18 min read

Updated 2026-05-29

# Instruction-Tuned Embeddings: How Task Prompts Transform Retrieval Quality

Modern embedding models like Jina v5, Qwen3-Embedding, and zEmbed-1 use task-specific prompts and LoRA adapters to specialize a single model for retrieval, classification, clustering, and code search. This guide explains the algorithms behind instruction tuning, query-document asymmetry, and task-specific adapters: with benchmarks showing 5-15% gains over unprompted baselines.

![Ethan Steininger](/people/ethan.webp)

By [Ethan Steininger](/blog/authors/ethan), Founder & CEO, Mixpeek

Embeddings

Instruction Tuning

LoRA

Retrieval

Task Prompts

Search

[Run this on your own data. Try it as you read.Search your own archive →](https://studio.mixpeek.com/namespaces/create?mode=managed&utm_source=homepage&utm_medium=guide_cta&utm_campaign=mvs_onramp)

[One-click templatesStart from a templateEach template deploys a working search app on your own files.Browse templates](/templates)

## The Problem with Generic Embeddings

  
  
A generic embedding model maps every input to the same vector space using the same weights, regardless of downstream task. A sentence like "The bank approved the loan" gets the same embedding whether you are:  
  
*   **Retrieving** documents that answer a question about loan approval processes
*   **Classifying** the sentence as belonging to the "Finance" category
*   **Clustering** it with other banking-related sentences
*   **Matching** it against a near-duplicate in another language
  
  
These are fundamentally different tasks. Retrieval needs to distinguish relevant from irrelevant documents across a large corpus. Classification needs to separate categories in embedding space. Clustering needs tight, well-separated groups. Matching needs fine-grained similarity detection.  
  
A single set of weights cannot be optimal for all four simultaneously. The model compromises: and the compromise costs 5-15% accuracy on every individual task compared to a specialist.  
  

## How Instruction Tuning Solves This

  
  
Instruction-tuned embeddings prepend a natural-language instruction to the input before encoding:

\# Retrieval task
input = "Represent this document for retrieval: The bank approved the loan after reviewing the applicant's credit history."

# Classification task
input = "Classify the following text: The bank approved the loan after reviewing the applicant's credit history."

# Clustering task
input = "Identify the topic of this text: The bank approved the loan after reviewing the applicant's credit history."

The same model produces different embeddings for the same text depending on the instruction. This works because the instruction shifts the model's attention patterns: in retrieval mode, it emphasizes discriminative content words; in classification mode, it emphasizes categorical signals.  
  

### Why This Works: Attention Redistribution

  
  
Consider a transformer encoder processing the input tokens. Without an instruction prefix, the self-attention layers distribute attention across all tokens based on position biases and learned patterns. With an instruction prefix like "Represent this document for retrieval:", the prefix tokens create new attention pathways:  
  
1\. **Prefix tokens attend to content tokens**, identifying which content is relevant to the stated task 2. **Content tokens attend to prefix tokens**, receiving task-conditioning signals 3. **The pooled output** (typically the last token or mean pool) integrates both task signal and content  
  
The result: the model learns that "retrieval" means "emphasize distinguishing content" while "classification" means "emphasize category-indicative features." The underlying knowledge about language semantics is shared; only the emphasis changes.  
  

## Architecture Patterns in 2026

  
  
Three distinct architectural approaches have emerged for instruction-tuned embeddings:  
  

### Pattern 1: Prompt-Only (E5, GTE, zEmbed-1)

  
  
The simplest approach: prepend different text prompts for different tasks, with all model weights shared.

from sentence\_transformers import SentenceTransformer

model = SentenceTransformer("zeroentropy/zembed-1-embedding")

# Retrieval: separate encode functions apply the right prompt automatically
query\_embedding = model.encode\_query("loan approval criteria")
doc\_embedding = model.encode\_document("The bank approved the loan...")

# The model internally prepends different instruction prefixes:
# query -> "Instruct: Retrieve relevant passages\\nQuery: loan approval criteria"
# document -> "Represent this document: The bank approved the loan..."

**Advantage:** No architectural changes. Any instruction-tuned language model can become an embedding model.  
  
**Limitation:** All tasks share the same weights. The prompt provides a soft steering signal, but the model cannot truly specialize its attention patterns for each task.  
  

### Pattern 2: Task-Specific LoRA Adapters (Jina v5)

  
  
Jina Embeddings v5 trains four independent LoRA (Low-Rank Adaptation) adapters on a frozen backbone:

+-----------------------------+
|      Frozen Backbone        |
|   (Qwen3-0.6B / EuroBERT)  |
+-----------------------------+
|  LoRA: retrieval  (rank 16) | <- active for retrieval tasks
|  LoRA: similarity (rank 16) | <- active for similarity tasks
|  LoRA: clustering (rank 16) | <- active for clustering tasks
|  LoRA: classification (r16) | <- active for classification tasks
+-----------------------------+

Each LoRA adapter adds a low-rank decomposition to the attention weight matrices:

W\_adapted = W\_frozen + B x A

where:
  W\_frozen: original frozen weight matrix (d x d)
  A: down-projection (d x r), r << d
  B: up-projection (r x d)
  Total additional params per adapter: 2 x d x r

With rank 16 and hidden dimension 1024, each adapter adds only 2 x 1024 x 16 = 32,768 parameters: 0.005% of the backbone. Four adapters together add 0.02% overhead.

from sentence\_transformers import SentenceTransformer

model = SentenceTransformer("jinaai/jina-embeddings-v5-text-small",
                            trust\_remote\_code=True)

# Task-specific encoding: the model loads the appropriate LoRA adapter
retrieval\_emb = model.encode("loan approval criteria",
                              task="retrieval",
                              prompt\_name="retrieval.query")

similarity\_emb = model.encode("loan approval criteria",
                               task="text-matching")

**Advantage:** True parameter specialization. Each adapter learns task-specific attention modifications that prompts alone cannot achieve. Benchmarks show 2-4% improvement over prompt-only approaches.  
  
**Limitation:** Requires loading different adapters at inference time. Slightly more complex deployment.  
  

### Pattern 3: Distillation from Cross-Encoders (zEmbed-1)

  
  
Cross-encoders (rerankers) jointly process query-document pairs and produce relevance scores. They are slow, O(n) forward passes for n candidates, but very accurate because they see both inputs simultaneously.  
  
zEmbed-1 uses an ELO-inspired training methodology to distill a cross-encoder's ranking knowledge into a bi-encoder:

Training Pipeline:
1. zerank-2 reranker scores (query, document) pairs -> relevance scores
2. Convert scores to adjusted Elo ratings per document
3. Train bi-encoder to produce embeddings whose cosine similarities
   reproduce the Elo ranking order

The key insight: instead of training on binary relevance labels (relevant/not relevant), the distillation preserves the full ranking order from the teacher. A document rated 1800 Elo should have higher cosine similarity to the query than a document rated 1600, which should be higher than 1400.  
  
**Result:** Domain-specific retrieval quality that exceeds models trained on generic contrastive losses. zEmbed-1 outperforms Cohere Embed v4 and OpenAI text-embedding-3-large on finance (+8%), healthcare (+15%), legal (+8%), and STEM (+11%) benchmarks.  
  

## Query-Document Asymmetry

  
  
A subtle but important aspect of instruction-tuned embeddings: queries and documents should be encoded differently.  
  

### Why Asymmetry Matters

  
  
Consider a user query: "What is backpropagation?"  
  
And a relevant document: "Backpropagation is a fundamental algorithm for training neural networks by computing gradients of the loss function with respect to model parameters using the chain rule."  
  
The query is short, vague, and intent-bearing. The document is long, specific, and content-bearing. Encoding them with the same prompt produces suboptimal embeddings because:  
  
1\. **Query encoding** should expand the sparse query signal: "backpropagation" should activate related concepts like "gradient," "chain rule," "neural network training" 2. **Document encoding** should compress the dense content signal: the embedding should capture the key information without diluting it across all mentioned concepts  
  

### How Models Implement Asymmetry

\# E5-style prompt asymmetry
query\_input = "query: What is backpropagation?"
doc\_input = "passage: Backpropagation is a fundamental algorithm..."

# zEmbed-1 style with explicit functions
query\_emb = model.encode\_query("What is backpropagation?")
doc\_emb = model.encode\_document("Backpropagation is a fundamental algorithm...")

# Jina v5 style with prompt names
query\_emb = model.encode("What is backpropagation?",
                          prompt\_name="retrieval.query")
doc\_emb = model.encode("Backpropagation is a fundamental algorithm...",
                        prompt\_name="retrieval.passage")

The asymmetry is not just cosmetic. Ablation studies show that using the same prompt for queries and documents reduces nDCG@10 by 3-7% across standard retrieval benchmarks.  
  

## Impact on Retrieval Quality

  
  
How much do instruction-tuned embeddings actually improve results? Here are benchmark comparisons from published model cards:  
  

### Jina v5 Text Small: Task Prompt Ablation

  
  

Configuration

MTEB Retrieval

MTEB Classification

MTEB Clustering

No prompt (raw text)

53.2

78.4

42.1

Generic prompt

54.8

79.1

43.6

Task-specific prompt

55.9

80.3

45.8

Task-specific LoRA

**56.7**

**81.2**

**47.3**

  
  
The progression is clear: no prompt, generic prompt, task prompt, task LoRA, each step adds 1-2% accuracy.  
  

### zEmbed-1: Distillation vs Contrastive Training

  
  

Training Method

Finance

Healthcare

Legal

Code

STEM

Contrastive (baseline)

0.361

0.502

0.565

0.608

0.442

Distillation from reranker

**0.448**

**0.626**

**0.672**

**0.645**

**0.528**

Improvement

+24%

+25%

+19%

+6%

+19%

  
  
Distillation shows its largest gains on specialized domains where the reranker's fine-grained understanding of relevance is hardest to learn from binary labels alone.  
  

## When to Use Which Approach

  
  

Scenario

Recommended Approach

Why

General-purpose search

Prompt-only (E5, BGE)

Simplest deployment, good baseline

Multi-task system

LoRA adapters (Jina v5)

One model serves retrieval, classification, and clustering

Domain-specific retrieval

Distilled (zEmbed-1)

Highest accuracy on specialized content

Edge/mobile deployment

Smallest prompt-only (Jina v5 Nano)

239M params, minimal overhead

Multilingual retrieval

LoRA + multilingual backbone

Granite R2 or Qwen3-Embedding

  
  

## How Agents Should Use This

  
  
An AI agent with access to a multimodal search tool should select the embedding strategy based on the task at hand:

\# Agent tool: adaptive search with task-aware embedding
def search(query: str, task: str = "retrieval", collection: str = "default"):
    """
    task options:
      - "retrieval": find documents that answer the query
      - "similarity": find documents similar to the input
      - "classification": find the category this text belongs to
      - "clustering": group with related documents
    """
    # The instruction goes in the QUERY, not in a task argument: no Mixpeek
    # stage takes one. text\_extractor@v1 runs E5-large-instruct, which expects
    # the task description inline on the query side and nothing on the passage
    # side, so this is where the prompt belongs.
    results = mixpeek.retrievers.execute(
        retriever\_id=retriever\_id,
        inputs={"query": f"Instruct: {TASK\_PROMPTS\[task\]}\\nQuery: {query}"},
    )
    return results

The agent selects the task parameter based on its current objective. A retrieval-augmented generation flow uses `task="retrieval"`. A deduplication step uses `task="similarity"`. A routing decision uses `task="classification"`.  
  

## Practical Considerations

  
  

### Indexing with the Right Task

  
  
Documents must be encoded with the correct task at index time. If you index documents with `task="retrieval"` but query with `task="classification"`, the embeddings live in misaligned subspaces and similarity scores become meaningless.  
  
For retrieval use cases, index with the document/passage prompt and query with the query prompt. This is the most common pattern and the one all models optimize for.  
  

### Backward Compatibility

  
  
Instruction-tuned models are typically backward-compatible with non-instruction inputs. If you pass raw text without a prompt, the model falls back to a default behavior (usually the retrieval task). But you leave accuracy on the table: always use the recommended prompts.  
  

### Mixing Models in a Pipeline

  
  
Instruction-tuned embeddings compose naturally with rerankers in a multi-stage pipeline. The embedding model handles first-stage retrieval with task-optimized recall, and the reranker handles second-stage precision:

from mixpeek import Mixpeek

mixpeek = Mixpeek(api\_key="YOUR\_API\_KEY", namespace="my-namespace")

mixpeek.retrievers.create(
    retriever\_name="legal-search",
    collection\_identifiers=\["legal\_documents"\],
    input\_schema={"query": {"type": "string"}},
    stages=\[
        {
            "stage\_name": "semantic",
            "stage\_id": "feature\_search",
            "parameters": {
                "searches": \[{
                    "feature\_uri": "mixpeek://text\_extractor@v1/multilingual\_e5\_large\_instruct\_v1",
                    "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},
                    "top\_k": 50,
                }\],
            },
        },
        {
            # A reranker is not a feature\_uri: it is an inference service the
            # rerank stage names. The shipped default is BAAI/bge-reranker-v2-m3;
            # a model of your own goes in feature\_uri as a custom plugin.
            "stage\_name": "rerank\_results",
            "stage\_id": "rerank",
            "parameters": {
                "inference\_name": "BAAI\_\_bge\_reranker\_v2\_m3",
                "query": "{{INPUT.query}}",
                "top\_k": 10,
            },
        },
    \],
)

results = mixpeek.retrievers.execute(
    retriever\_id="legal-search",
    inputs={"query": "force majeure clause pandemic exception"},
)

The zEmbed-1 bi-encoder retrieves 50 candidates using its distilled legal-domain knowledge. The zerank-2 cross-encoder then rescores the top 50 with full query-document cross-attention, returning the 10 most relevant results. Each stage contributes what it does best.  
  

## Further Reading

  
  
*   [Do E5 and BGE Embeddings Need Query and Passage Prefixes?](/guides/do-e5-and-bge-embeddings-need-query-and-passage-prefixes): what leaving the prefixes off, or using the wrong one, did to nDCG@10 on SciFact, NFCorpus and FiQA
*   [Contrastive Learning: How CLIP, SigLIP, and CLAP Work](/guides/contrastive-learning-how-clip-siglip-and-clap-work): the pretraining method that produces the base models instruction tuning builds on
*   [Cross-Encoder Reranking](/guides/cross-encoder-reranking): the teacher models used in distillation-based training
*   [Embedding Quantization & Compression](/guides/embedding-quantization-compression): how to make instruction-tuned embeddings practical at scale with Matryoshka, BQ, and PQ
*   [Multi-Stage Retrieval](/guides/multi-stage-retrieval-how-agents-search-unstructured-data): how agents chain coarse and fine retrieval stages
*   [Late Interaction Retrieval](/guides/late-interaction-retrieval): ColBERT-style multi-vector search as an alternative to single-vector instruction tuning

## Run this on your own data

Point Mixpeek at the storage you already have and search your video, images, audio, and documents the way this guide describes. Build starts at $25/mo for up to 1M vectors.

[Search your own archive](https://studio.mixpeek.com/namespaces/create?mode=managed&utm_source=homepage&utm_medium=guide_cta&utm_campaign=mvs_onramp)[Read Docs](/docs)

[Explore MVS](/mvs)[See pricing](/pricing)

## Related guides

[

Embeddings

### Embedding Space Geometry: Why Cosine Similarity Doesn't Always Mean What You Think

A deep dive into the geometry of embedding spaces: why cosine similarity scores cluster in narrow ranges, how the hubness problem distorts retrieval, when to use cosine vs. L2 vs. dot product, and practical techniques for threshold setting, score calibration, and cross-model comparison.

Read guide →](/guides/embedding-space-geometry)[

Embeddings

### How Do You Convert Text Into Vector Embeddings?

Run the text through an embedding model: chunk it under the model's token limit, embed each chunk, normalize, and embed queries with the same model. Hosted APIs do it in one call (OpenAI's text-embedding-3-small: 1,536 dimensions, 8,192 tokens, $0.02 per million tokens). Open models run free on a CPU: 1,000 paragraphs took 19 s with all-MiniLM-L6-v2 in our test.

Read guide →](/guides/how-to-convert-text-into-vector-embeddings)[

Embeddings

### Does Combining Two Embedding Models Improve Image Search? Measured on COCO and Flickr30k

Fusing SigLIP 2 with DFN5B per image raised COCO text-to-image recall@1 from 55.81% to 58.10%, above the best published single open models we could run. Rank fusion by document id leaves the top result unchanged, and lowercasing SigLIP queries gains more than a second model. Measured results, code and costs.

Read guide →](/guides/does-combining-two-embedding-models-improve-image-search)