Local inference · Retrieval engineering

Run OmniEVIE-4B Locally and Compare Multi-Vector Retrieval

Запускаем OmniEVIE-4B локально и сравниваем многовекторный поиск
Temporary fallback cover; replace in editorial pass.

A reproducible way to evaluate a multimodal embedding model on your own machine, compare launch paths, and measure the practical cost of keeping several vectors per document.

45 minute read Advanced

The hard part of deploying OmniEVIE-4B locally is not downloading weights. It is deciding what the model should emit, preserving that representation in an index, and measuring whether the extra vectors improve retrieval enough to justify their storage and integration cost.

This guide treats OmniEVIE-4B as a multimodal encoder whose output may contain multiple token-level or patch-level vectors rather than one pooled vector. The article does not claim benchmark scores, hardware measurements, package names, or model-release details that have not been verified here. Replace the model identifier and processor import with the identifiers published by the model release you are using.

The concrete problem

Suppose a support team stores screenshots, scanned documents, and short text descriptions. A user asks, “Which screenshot shows the failed export after changing the date range?” A single pooled embedding may blur the error message, the date control, and the surrounding interface. A multi-vector representation can preserve more local evidence, but it increases index size and makes the retriever responsible for a late-interaction score.

The decision is therefore three-dimensional:

Before you start

Record the exact model revision, runtime version, operating system, accelerator, numerical precision, and preprocessing settings. These are part of the experiment, not incidental details.

python -VV
python -m pip freeze
uname -a
nvidia-smi  # NVIDIA systems only

Keep a clean environment for each launch path. Do not mix cached processors or tokenizers from different revisions. Keep credentials out of shell history and source files; if the model repository is gated, authenticate through the supported local credential mechanism.

Path one: sentence-transformers

Sentence-Transformers is a convenient first path when the model release provides a compatible model card, pooling configuration, and processor integration. It gives you a familiar batching interface, but compatibility must be verified rather than assumed: a multimodal model may require custom code or an output field that a default pooling pipeline does not understand.

Start by creating an isolated environment:

python -m venv .venv-st
. .venv-st/bin/activate
python -m pip install -U pip
python -m pip install sentence-transformers pillow torch

Set the identifier from the official model release:

export MODEL_ID='<official-OmniEVIE-4B-model-id>'

The following smoke-test pattern is intentionally explicit. It fails loudly if the model does not expose the expected high-level interface.

from pathlib import Path
import os
from PIL import Image
from sentence_transformers import SentenceTransformer

model_id = os.environ["MODEL_ID"]
model = SentenceTransformer(model_id)

text = "a screenshot showing an export failure after changing a date range"
image = Image.open(Path("example.png")).convert("RGB")

text_embedding = model.encode(
    [text],
    convert_to_numpy=True,
    normalize_embeddings=False,
    show_progress_bar=False,
)
image_embedding = model.encode(
    [image],
    convert_to_numpy=True,
    normalize_embeddings=False,
    show_progress_bar=False,
)

print("text shape:", getattr(text_embedding, "shape", None))
print("image shape:", getattr(image_embedding, "shape", None))

If the model returns one two-dimensional array per input, this path is producing pooled embeddings. That is useful as a baseline, but it is not proof that multi-vector retrieval is being preserved. Inspect the model-specific output contract before applying pooling.

Verification checklist

Path two: the official package

The official package is usually the best path for validating the model’s intended behavior, especially when it exposes separate text, image, and token-level outputs. Its trade-off is operational: the API may be less standardized, and its dependencies may be more tightly coupled to the release.

Install the package name and version specified by the release documentation. Do not substitute a guessed package name:

python -m venv .venv-official
. .venv-official/bin/activate
python -m pip install -U pip
python -m pip install '<official-package>==<verified-version>'

A minimal adapter should isolate package-specific code from the rest of your evaluation:

from dataclasses import dataclass
from typing import Any
import numpy as np

@dataclass
class EmbeddingBatch:
    pooled: np.ndarray | None
    vectors: list[np.ndarray] | None
    raw: Any

def encode_with_official_package(model, processor, *, text=None, image=None):
    inputs = processor(text=text, images=image, return_tensors="pt")
    raw = model(**inputs)

    pooled = getattr(raw, "pooler_output", None)
    vectors = getattr(raw, "last_hidden_state", None)

    if pooled is not None:
        pooled = pooled.detach().float().cpu().numpy()

    if vectors is not None:
        vectors = [
            row.detach().float().cpu().numpy()
            for row in vectors
        ]

    return EmbeddingBatch(pooled=pooled, vectors=vectors, raw=raw)

The attribute names above are an adapter example, not a claim about OmniEVIE-4B’s actual output schema. Read the release’s model card or source and change the adapter to the documented fields. Preserve the unmodified output for one inspection run so that a later pooling step is auditable.

Path three: GGUF and llama.cpp

GGUF is a file format used by several local inference tools. llama.cpp is attractive when CPU execution, broad hardware support, or a compact deployment footprint matters. It is not automatically a drop-in route for every embedding architecture. The model must have a compatible conversion, architecture implementation, and embedding API.

First establish whether the release provides a verified GGUF conversion. If it does not, stop at this path rather than converting an unfamiliar architecture and treating the result as equivalent.

git clone <verified-llama.cpp-repository-url>
cd llama.cpp
cmake -B build
cmake --build build --config Release -j

For a compatible embedding build, the command shape is commonly similar to:

./build/bin/llama-embedding \
  -m /path/to/verified-model.gguf \
  -p "a screenshot showing an export failure" \
  --embd-normalize

Flags differ across versions. Run the local help output and record it with the experiment:

./build/bin/llama-embedding --help

Validate the output dimension and modality behavior separately. A text embedding executable accepting a prompt does not establish that image inputs, patch vectors, or multi-vector outputs are supported.

Path four: MLX

MLX is a useful path on Apple silicon when the model release provides an MLX-compatible conversion. It can simplify local experimentation, but conversion quality and operator support are release-specific.

python -m venv .venv-mlx
. .venv-mlx/bin/activate
python -m pip install -U pip
python -m pip install mlx mlx-lm pillow

Use the MLX repository and loader specified by the model release. Keep the conversion separate from evaluation:

export MLX_MODEL_DIR='/path/to/verified-mlx-conversion'
python -m '<verified-mlx-loader>' \
  --model "$MLX_MODEL_DIR" \
  --text "a screenshot showing an export failure"

Do not compare an MLX conversion against another runtime until you have checked the same preprocessing, output normalization, dimensionality, and model revision. A faster conversion that emits a different representation is a different experiment.

Preserve multi-vector output

For a multi-vector representation, let a query produce vectors Q = {q₁, …, qₘ} and a document produce vectors D = {d₁, …, dₙ}. Normalize each vector if the model’s documented scoring procedure calls for cosine similarity. Then compute a late-interaction score.

The common MaxSim form is:

score(Q, D) = sum over i of max over j cosine(q_i, d_j)

In NumPy:

import numpy as np

def l2_normalize(x):
    x = np.asarray(x, dtype=np.float32)
    denom = np.linalg.norm(x, axis=-1, keepdims=True)
    return x / np.maximum(denom, 1e-12)

def maxsim(query_vectors, document_vectors):
    q = l2_normalize(query_vectors)
    d = l2_normalize(document_vectors)
    similarities = q @ d.T
    return float(similarities.max(axis=1).sum())

This implementation assumes arrays shaped [tokens, dimensions]. If the model returns [batch, tokens, dimensions], remove the batch dimension before calling it. If special tokens are included, evaluate both policies: keep them, or remove them according to the model documentation. Report the policy because it changes the score.

Build a reproducible evaluation set

Use a small, versioned dataset before scaling up. Each query should have at least one known relevant item and several hard negatives. For the screenshot case, hard negatives might share the same application, toolbar, or date-range control while showing a different failure.

data/
  queries.jsonl
  documents/
    doc-001.png
    doc-002.png
  judgments.jsonl

A practical JSON Lines schema is:

{"query_id":"q-001","text":"export failed after changing the date range","image":null}
{"doc_id":"doc-001","path":"documents/doc-001.png","kind":"image"}
{"query_id":"q-001","doc_id":"doc-001","relevance":2}
{"query_id":"q-001","doc_id":"doc-002","relevance":0}

Keep judgments independent from the runtime. The same judgments must be used for pooled, multi-vector, quantized, and cross-runtime comparisons.

Compare pooled and multi-vector retrieval

At minimum, evaluate three indexes:

  1. A pooled baseline using one vector per item.
  2. A full multi-vector index using all retained vectors.
  3. A reduced multi-vector index using a documented token or patch selection rule.

For each index, record:

Raw storage can be estimated as:

bytes_per_item = vectors_per_item * dimensions * bytes_per_value
total_raw_bytes = item_count * bytes_per_item

For example, if an item has n vectors of dimension d stored as 32-bit floats, the raw payload is n × d × 4 bytes per item, before metadata, offsets, compression, and index overhead. Treat this as an estimate, not a measured index size.

Quantization and compression

Quantization can reduce memory and improve cache behavior, but it may change ranking. Compare it only after establishing a full-precision reference.

Use an explicit experiment matrix:

representation,precision,normalization,score,recall_at_10,bytes_per_item
pooled,float32,cosine,cosine,, 
multi,float32,cosine,maxsim,,
multi,int8,cosine,maxsim,,

Do not fill blank measurements with expected values. A missing result is preferable to an invented result.

Verification procedure

Run these checks for every launch path:

  1. Load the model and processor from a clean environment.
  2. Encode the same text twice and compare the outputs.
  3. Encode the same image twice and compare the outputs.
  4. Check shape, dtype, finite values, and normalization.
  5. Confirm that text and image inputs do not accidentally share a preprocessing branch.
  6. Persist one raw output and the exact configuration used to create it.
  7. Run the pooled and MaxSim scorers on a hand-constructed pair where the expected ordering is obvious.
def validate_vectors(name, vectors):
    import numpy as np
    x = np.asarray(vectors)
    assert x.ndim in (1, 2), f"{name}: unexpected rank {x.ndim}"
    assert x.size > 0, f"{name}: empty output"
    assert np.isfinite(x).all(), f"{name}: non-finite value"
    print(name, "shape=", x.shape, "dtype=", x.dtype)

Common failure cases

“The model loads, but retrieval is poor.”

Check modality preprocessing, normalization, special-token handling, and whether the evaluator is scoring pooled output when the model expects token-level late interaction. Also check that query and document encoders are paired as documented.

“The output has one vector, but the paper or release mentions many.”

You may be using a convenience method that pools by default. Inspect the raw forward output and the model-specific API. Do not infer multi-vector support from the model name alone.

“GGUF runs text but not images.”

This usually indicates that the conversion or executable supports only a text path. Treat it as a text-only baseline unless image support is explicitly verified.

“MLX and PyTorch scores differ.”

Compare model revisions, preprocessing, dtype, normalization, truncation, and output selection. Small numerical differences can be acceptable; a changed shape or changed token count is a representation mismatch.

“MaxSim is too slow.”

Measure where time goes. Candidate generation can use a pooled index, followed by MaxSim reranking over a small top-k set. This hybrid architecture preserves a more expressive score without requiring every candidate comparison to be exhaustive.

What the comparison can and cannot prove

A local comparison can establish which representation and runtime work better for your dataset, hardware, and operational constraints. It cannot establish universal model quality. A small judged set can miss failure modes; a different image mix can reverse rankings; and a conversion can alter behavior even when its dimensions match.

Keep the final report narrow and reproducible. State the exact model revision, runtime, command, preprocessing, output type, score, dataset split, and measurements. If a path was not tested, label it as an unverified launch path and provide the condition required to verify it.

Practical decision rule

Use the official package first when representation fidelity matters most. Use sentence-transformers when its compatibility layer exposes the required outputs and you value a conventional integration surface. Use GGUF/llama.cpp when a verified conversion and embedding implementation exist and deployment footprint matters. Use MLX when you are on Apple silicon and a verified conversion is available.

Choose multi-vector retrieval only when its measured ranking improvement survives your storage and latency budget. Otherwise, use pooled retrieval for candidate generation and reserve MaxSim for reranking. That gives you a concrete quality-versus-complexity decision instead of treating multi-vector output as automatically superior.

We publish what works for us—and implement the same solutions for your business. We design AI automation, Telegram bots, chats, and AI agents for real-world processes. Discuss your project →