Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): SMVE sparse multi-vector encoding, with smve profiles for TopK models (#518)

Filip Makraduli9eeff51a9074
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index af1e938db..61554efae 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -1246,7 +1246,7 @@ class SIEClient:
is_query: Whether this is a query embedding (vs document). Affects some models
that use asymmetric encoding (e.g., BGE, E5). Default: None (model default).
options: Runtime options dict. Can include "profile" to select a named profile,
- or individual options like "muvera", "normalize", etc.
+ or individual options like "muvera", "smve", "normalize", etc.
gpu: Target GPU type (e.g., "l4", "a100-80gb"). Routes request to workers
with matching GPU. Required when using the gateway with multiple GPU pools.
wait_for_capacity: When True (default), auto-retry transient "not
diff --git a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
index f3413f5c9..e3181f030 100644
--- a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
+++ b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
@@ -30,6 +30,11 @@ profiles:
doc_prefix: '[D] '
doc_punctuation_skiplist: true
cuda_graphs: bucketed
+ # Sparse Multi-Vector Encoding for the smve profile, with TopK's published
+ # settings for this checkpoint (its model card: width 65536, k=32).
+ smve_config:
+ width: 65536
+ k: 32
runtime:
# The checkpoint's PyLate recipe (config_sentence_transformers.json).
query_max_length: 32
@@ -61,6 +66,17 @@ profiles:
output_similarity:
dense: dot
muvera: {}
+ smve:
+ extends: default
+ adapter_options:
+ runtime:
+ query_max_length: 32
+ max_seq_length: 300
+ output_types:
+ - sparse
+ output_similarity:
+ sparse: dot
+ smve: {}
long_context:
extends: default
adapter_options:
diff --git a/packages/sie_server/models/topk-io__topk-embed-v1-small.yaml b/packages/sie_server/models/topk-io__topk-embed-v1-small.yaml
index 58675296e..36a5ae5c3 100644
--- a/packages/sie_server/models/topk-io__topk-embed-v1-small.yaml
+++ b/packages/sie_server/models/topk-io__topk-embed-v1-small.yaml
@@ -39,6 +39,14 @@ profiles:
num_simhash_projections: 6
projection_dim: null
final_projection_dim: 10240
+ # Sparse Multi-Vector Encoding for the smve profile: TopK's width and k
+ # (SMVE runs on the model's GPU). Pages and long documents keep their 8192
+ # largest values, which bounds their size and, on a page benchmark,
+ # surfaced more of the exact MaxSim top 10 than keeping every value.
+ smve_config:
+ width: 65536
+ k: 32
+ max_nonzeros: 8192
runtime:
normalize: true
# The model computes in bf16, so float16 loses nothing and halves the
@@ -54,3 +62,13 @@ profiles:
output_similarity:
dense: dot
muvera: {}
+ smve:
+ extends: default
+ adapter_options:
+ runtime:
+ normalize: true
+ output_types:
+ - sparse
+ output_similarity:
+ sparse: dot
+ smve: {}
diff --git a/packages/sie_server/models/topk-io__topk-embed-v1-xsmall.yaml b/packages/sie_server/models/topk-io__topk-embed-v1-xsmall.yaml
index 1872dfa66..41b5df709 100644
--- a/packages/sie_server/models/topk-io__topk-embed-v1-xsmall.yaml
+++ b/packages/sie_server/models/topk-io__topk-embed-v1-xsmall.yaml
@@ -41,6 +41,14 @@ profiles:
num_simhash_projections: 6
projection_dim: null
final_projection_dim: 10240
+ # Sparse Multi-Vector Encoding for the smve profile: TopK's width and k
+ # (SMVE runs on the model's GPU). Pages and long documents keep their 8192
+ # largest values, which bounds their size and, on a page benchmark,
+ # surfaced more of the exact MaxSim top 10 than keeping every value.
+ smve_config:
+ width: 65536
+ k: 32
+ max_nonzeros: 8192
runtime:
normalize: true
# The model computes in bf16, so float16 loses nothing and halves the
@@ -56,3 +64,13 @@ profiles:
output_similarity:
dense: dot
muvera: {}
+ smve:
+ extends: default
+ adapter_options:
+ runtime:
+ normalize: true
+ output_types:
+ - sparse
+ output_similarity:
+ sparse: dot
+ smve: {}
diff --git a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
index b573ce808..575ad4ed5 100644
--- a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
@@ -115,6 +115,7 @@ class ColBERTAdapter(BaseAdapter):
query_expansion: bool = True,
doc_punctuation_skiplist: bool = True,
muvera_config: dict[str, Any] | None = None,
+ smve_config: dict[str, Any] | None = None,
revision: str | None = None,
code_revision: str | None = None,
require_standalone_projection: bool = False,
@@ -147,6 +148,8 @@ class ColBERTAdapter(BaseAdapter):
not). Default: True.
muvera_config: MUVERA configuration dict with keys like num_repetitions,
num_simhash_projections, normalize. Used for FDE postprocessing.
+ smve_config: SMVE configuration dict with keys like width and k. Used for
+ sparse (SMVE) postprocessing.
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading the tokenizer, config, model, and Dense-chain/projection
artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
@@ -177,6 +180,7 @@ class ColBERTAdapter(BaseAdapter):
self._query_expansion = query_expansion
self._doc_punctuation_skiplist = doc_punctuation_skiplist
self._muvera_config = muvera_config
+ self._smve_config = smve_config
self._model: PreTrainedModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -1232,20 +1236,28 @@ class ColBERTAdapter(BaseAdapter):
return texts
def get_postprocessors(self) -> dict[str, Any] | None:
- """Return MUVERA postprocessor for converting multivector to dense.
+ """Return the MUVERA (multivector to dense) and SMVE (multivector to sparse) postprocessors.
MUVERA enables using ColBERT embeddings with standard HNSW search
by converting variable-length per-token embeddings to fixed-dimension
- dense vectors.
+ dense vectors. SMVE converts them to one sparse vector for an inverted
+ index instead.
Returns:
- Dict with "muvera" key mapping to MuveraPostprocessor instance.
+ Dict with "muvera" and "smve" keys mapping to the postprocessor instances.
"""
- from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor
+ from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor, SmveConfig, SmvePostprocessor
# Build MuveraConfig from loadtime options or use defaults
if self._muvera_config:
config = MuveraConfig(**self._muvera_config)
else:
config = MuveraConfig()
- return {"muvera": MuveraPostprocessor(token_dim=self._token_dim, config=config)}
+ smve = SmveConfig(**self._smve_config) if self._smve_config else SmveConfig()
+ return {
+ "muvera": MuveraPostprocessor(token_dim=self._token_dim, config=config),
+ # SMVE's anchors must match the vectors this checkpoint actually emits.
+ "smve": SmvePostprocessor(
+ token_dim=self._actual_token_dim or self._token_dim, config=smve, device=self._device
+ ),
+ }
diff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py
index d8e10350e..f9a421418 100644
--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py
@@ -89,6 +89,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_prefix: str = "",
doc_prefix: str = "",
muvera_config: dict[str, Any] | None = None,
+ smve_config: dict[str, Any] | None = None,
revision: str | None = None,
cuda_graphs: str | bool = "off",
fused_rope: bool = False,
@@ -110,6 +111,8 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
doc_prefix: Prefix to prepend to documents.
muvera_config: MUVERA configuration dict with keys like num_repetitions,
num_simhash_projections, normalize. Used for FDE postprocessing.
+ smve_config: SMVE configuration dict with keys like width and k. Used for
+ sparse (SMVE) postprocessing.
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading the tokenizer, model, and Dense-chain artifacts.
Forwarded to ``from_pretrained(..., revision=...)``.
@@ -144,6 +147,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_prefix = query_prefix
self._doc_prefix = doc_prefix
self._muvera_config = muvera_config
+ self._smve_config = smve_config
self._model: Any = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -738,16 +742,20 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
return texts
def get_postprocessors(self) -> dict[str, Any] | None:
- """Return MUVERA postprocessor for converting multivector to dense.
+ """Return the MUVERA (multivector to dense) and SMVE (multivector to sparse) postprocessors.
Returns:
- Dict with "muvera" key mapping to MuveraPostprocessor instance.
+ Dict with "muvera" and "smve" keys mapping to the postprocessor instances.
"""
- from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor
+ from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor, SmveConfig, SmvePostprocessor
- # Build MuveraConfig from loadtime options or use defaults
+ # Build both configs from loadtime options or use defaults
if self._muvera_config:
config = MuveraConfig(**self._muvera_config)
else:
config = MuveraConfig()
- return {"muvera": MuveraPostprocessor(token_dim=self._token_dim, config=config)}
+ smve = SmveConfig(**self._smve_config) if self._smve_config else SmveConfig()
+ return {
+ "muvera": MuveraPostprocessor(token_dim=self._token_dim, config=config),
+ "smve": SmvePostprocessor(token_dim=self._token_dim, config=smve, device=self._device),
+ }
diff --git a/packages/sie_server/src/sie_server/adapters/topk_embed/adapter.py b/packages/sie_server/src/sie_server/adapters/topk_embed/adapter.py
index f557df1e0..b355e498f 100644
--- a/packages/sie_server/src/sie_server/adapters/topk_embed/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/topk_embed/adapter.py
@@ -60,7 +60,7 @@ from sie_server.adapters.topk_embed.graphs import GRAPH_MODES, GraphMode, GraphR
from sie_server.adapters.topk_embed.packed import PackedTextModel, Packing, resolve_kernels, to_device
from sie_server.core.inference_output import EncodeOutput
from sie_server.core.oom import is_oom_error
-from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor
+from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor, SmveConfig, SmvePostprocessor
from sie_server.types.inputs import ImageInput, InvalidInputError, Item, decode_image
if TYPE_CHECKING:
@@ -165,6 +165,7 @@ class TopkEmbedAdapter(BaseAdapter):
text_batch_tokens: int = 16384,
image_batch_size: int = 4,
muvera_config: dict[str, Any] | None = None,
+ smve_config: dict[str, Any] | None = None,
attn_implementation: str | None = None,
packed: bool | None = None,
cuda_graphs: str | bool = "off",
@@ -187,6 +188,7 @@ class TopkEmbedAdapter(BaseAdapter):
text_batch_tokens: Padded tokens per text forward pass.
image_batch_size: Images per vision forward pass.
muvera_config: Optional MUVERA configuration (passed to postprocessor).
+ smve_config: Optional SMVE configuration (passed to postprocessor).
attn_implementation: Attention kernel for the full-attention layers of
the row-per-input path (``sdpa`` when unset).
packed: Run each batch as one packed sequence with variable-length
@@ -211,6 +213,7 @@ class TopkEmbedAdapter(BaseAdapter):
self._text_batch_tokens = max(1, int(text_batch_tokens))
self._image_batch_size = max(1, int(image_batch_size))
self._muvera_config = muvera_config
+ self._smve_config = smve_config
self._attn_implementation = attn_implementation
self._packed = packed
self._packed_text: PackedTextModel | None = None
@@ -492,8 +495,8 @@ class TopkEmbedAdapter(BaseAdapter):
opts = options or {}
normalize = bool(opts.get("normalize", self._normalize))
# Vectors cross to the host in 16 bits when the response is 16-bit anyway and nothing
- # after the adapter reads them at full precision (the MUVERA postprocessor does).
- half = opts.get("output_dtype") == "float16" and opts.get("muvera") is None
+ # after the adapter reads them at full precision (the MUVERA and SMVE postprocessors do).
+ half = opts.get("output_dtype") == "float16" and opts.get("muvera") is None and opts.get("smve") is None
dtype = torch.float16 if half else torch.float32
# Items route by modality: a batch of the reference model carries one modality,
@@ -989,9 +992,15 @@ class TopkEmbedAdapter(BaseAdapter):
super().unload()
def get_postprocessors(self) -> dict[str, Any]:
- """Return the configured MUVERA multivector-to-dense postprocessor."""
- config = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()
- return {"muvera": MuveraPostprocessor(token_dim=self._multivector_dim or 1024, config=config)}
+ """Return the MUVERA (multivector to dense) and SMVE (multivector to sparse) postprocessors."""
+ token_dim = self._multivector_dim or 1024
+ muvera = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()
+ smve = SmveConfig(**self._smve_config) if self._smve_config else SmveConfig()
+ return {
+ "muvera": MuveraPostprocessor(token_dim=token_dim, config=muvera),
+ # SMVE projects on the model's device: its matrix multiply is far too large for the CPU here.
+ "smve": SmvePostprocessor(token_dim=token_dim, config=smve, device=self._device),
+ }
def get_preprocessor(self) -> Any:
# The adapter owns tokenization and image preprocessing. The base
diff --git a/packages/sie_server/src/sie_server/core/encode_pipeline.py b/packages/sie_server/src/sie_server/core/encode_pipeline.py
index acdcae231..4bcce07c5 100644
--- a/packages/sie_server/src/sie_server/core/encode_pipeline.py
+++ b/packages/sie_server/src/sie_server/core/encode_pipeline.py
@@ -33,6 +33,11 @@ def _validated_encode_output_types(value: object) -> list[str]:
return validated_output_types
+# Response types a postprocessor builds from multivectors, by option key: the
+# adapter emits multivectors and the postprocessor adds the response type.
+_MULTIVECTOR_POSTPROCESSED_OUTPUTS = {"muvera": "dense", "smve": "sparse"}
+
+
def resolve_encode_output_types(
config: ModelConfig,
request_output_types: list[str] | None,
@@ -43,7 +48,8 @@ def resolve_encode_output_types(
Profiles may expose a postprocessed output that the adapter does not emit
directly. MuVERA is the canonical example: the public response is dense,
- while the adapter must first produce multivectors. Keeping capability
+ while the adapter must first produce multivectors. SMVE does the same for a
+ sparse response. Keeping capability
validation and that translation here prevents the HTTP and managed queue
paths from drifting apart.
@@ -74,10 +80,13 @@ def resolve_encode_output_types(
raise InvalidInputError(msg)
adapter_output_types = list(response_output_types)
- if effective_options.get("muvera") is not None and "dense" in response_output_types:
- adapter_output_types = [output_type for output_type in response_output_types if output_type != "dense"]
- if "multivector" not in adapter_output_types:
- adapter_output_types.append("multivector")
+ for option_key, postprocessed_type in _MULTIVECTOR_POSTPROCESSED_OUTPUTS.items():
+ if effective_options.get(option_key) is not None and postprocessed_type in adapter_output_types:
+ adapter_output_types = [
+ output_type for output_type in adapter_output_types if output_type != postprocessed_type
+ ]
+ if "multivector" not in adapter_output_types:
+ adapter_output_types.append("multivector")
return adapter_output_types, response_output_types
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 5a91150d0..25d4fb45c 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -642,11 +642,12 @@ class ModelLoader:
"""
resolved = config.resolve_profile("default")
postprocessors = adapter.get_postprocessors() or {}
- if resolved.runtime.get("muvera") is not None and "muvera" not in postprocessors:
- raise ValueError(
- f"model profile {name!r} requests MUVERA but adapter "
- f"{type(adapter).__name__!r} did not register a 'muvera' postprocessor"
- )
+ for option_key, label in (("muvera", "MUVERA"), ("smve", "SMVE")):
+ if resolved.runtime.get(option_key) is not None and option_key not in postprocessors:
+ raise ValueError(
+ f"model profile {name!r} requests {label} but adapter "
+ f"{type(adapter).__name__!r} did not register a {option_key!r} postprocessor"
+ )
# Get preprocessor(s) from adapter - all adapters implement get_preprocessor().
# Most return a single preprocessor; multi-modal adapters (e.g. NemoColEmbed v1,
diff --git a/packages/sie_server/src/sie_server/core/postprocessor.py b/packages/sie_server/src/sie_server/core/postprocessor.py
index daa7389d6..f9491dc66 100644
--- a/packages/sie_server/src/sie_server/core/postprocessor.py
+++ b/packages/sie_server/src/sie_server/core/postprocessor.py
@@ -2,6 +2,7 @@
Postprocessors transform EncodeOutput in-place to add/convert output types:
- MuveraPostprocessor: multivector -> dense (for ColBERT/ColPali)
+- SmvePostprocessor: multivector -> sparse (Sparse Multi-Vector Encoding)
- Future: Int8Postprocessor, BinaryPostprocessor for quantization
Design principles:
@@ -19,11 +20,15 @@ from __future__ import annotations
import logging
import threading
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Literal, Protocol
+from typing import TYPE_CHECKING, Any, Literal, Protocol
import numpy as np
+from sie_server.core.inference_output import SparseVector
+
if TYPE_CHECKING:
+ from collections.abc import Sequence
+
from sie_server.core.inference_output import EncodeOutput
logger = logging.getLogger(__name__)
@@ -609,6 +614,225 @@ class MuveraPostprocessor:
return sums.ravel()
+# =============================================================================
+# SMVE: Sparse Multi-Vector Encoding
+# =============================================================================
+
+# Upper bound on one chunk of token projections ([tokens, width] float32) and on
+# one group's accumulators ([items, output_dim] float32, two of them for
+# documents), so long pages and large batches stay within a fixed memory budget.
+_SMVE_PROJECTION_CHUNK_BYTES = 64 * 1024 * 1024
+_SMVE_ACCUMULATOR_BYTES = 256 * 1024 * 1024
+
+
+@dataclass
+class SmveConfig:
+ """Configuration for the SMVE postprocessor.
+
+ SMVE (Sparse Multi-Vector Encoding) turns a multivector into one sparse
+ vector whose dot product with another approximates MaxSim, so a sparse
+ (inverted) index can serve as the first retrieval stage, with MaxSim over
+ the stored token vectors re-ranking the candidates:
+
+ 1. Project every token onto ``width`` random unit vectors (anchors).
+ 2. Keep each token's ``k`` largest projections.
+ 3. Pool the tokens: a query sums them; a document averages the non-zero
+ contributions in each dimension.
+
+ ``num_repetitions`` runs the three steps with independent anchors and
+ concatenates the results. Storage and compute scale with ``k``, not with
+ ``width``: an item of ``n`` tokens has at most ``k * n * num_repetitions``
+ non-zeros. ``max_nonzeros`` optionally keeps only the largest values of
+ each item, which bounds long documents.
+
+ Queries and documents must use the same settings: the anchors come from
+ the seed, so width, seed and repetitions are part of the index.
+
+ Reference: M. Spisak and M. Galovic, "SMVE: Multi-Vector Retrieval That
+ Just Works", TopK blog, March 2026,
+ https://www.topk.io/blog/20260311-smve-multi-vector-retrieval
+
+ Attributes:
+ width: Number of anchors per repetition (dimensions per repetition).
+ k: Projections kept per token.
+ num_repetitions: Independent anchor sets, concatenated.
+ seed: Seed of the first anchor set; repetition ``r`` uses ``seed + r``.
+ max_nonzeros: If set, keep only this many largest values per item.
+ """
+
+ width: int = 65536
+ k: int = 32
+ num_repetitions: int = 1
+ seed: int = 42
+ max_nonzeros: int | None = None
+
+ def __post_init__(self) -> None:
+ """Reject settings that cannot produce a valid encoding."""
+ if self.width < 1:
+ msg = f"SMVE width must be at least 1, got {self.width}"
+ raise ValueError(msg)
+ if not 1 <= self.k <= self.width:
+ msg = f"SMVE k must be in 1..width ({self.width}), got {self.k}"
+ raise ValueError(msg)
+ if self.num_repetitions < 1:
+ msg = f"SMVE num_repetitions must be at least 1, got {self.num_repetitions}"
+ raise ValueError(msg)
+ if self.max_nonzeros is not None and self.max_nonzeros < 1:
+ msg = f"SMVE max_nonzeros must be at least 1 when set, got {self.max_nonzeros}"
+ raise ValueError(msg)
+
+ @property
+ def output_dim(self) -> int:
+ """Dimension of the sparse output: ``width * num_repetitions``."""
+ return self.width * self.num_repetitions
+
+
+class SmvePostprocessor:
+ """SMVE postprocessor: converts multivector to sparse.
+
+ The projection is one large matrix multiply (for 2,048-number tokens and a
+ 65,536 width, a 1,230-token page is about 330 GFLOP), so it runs in torch on
+ ``device``, normally the model's own device, with CPU as the fallback.
+ Items of a batch are projected together, in chunks of tokens.
+
+ The anchors are drawn with numpy from the seed and normalized to unit
+ length, so every process and device builds the same ones. Projections on a
+ GPU follow its matmul precision (SIE enables TF32), so values can differ
+ from a CPU encoding in the last bits; that is far below what retrieval
+ resolves.
+ """
+
+ source_field: Literal["dense", "sparse", "multivector"] = "multivector"
+ target_field: Literal["dense", "sparse", "multivector"] = "sparse"
+
+ def __init__(self, token_dim: int, config: SmveConfig | None = None, *, device: str | None = None) -> None:
+ """Initialize the SMVE postprocessor.
+
+ Args:
+ token_dim: Dimension of the per-token embeddings.
+ config: SMVE configuration. Uses defaults if not provided.
+ device: Torch device for the projections (default ``"cpu"``).
+ """
+ if token_dim < 1:
+ msg = f"SMVE token_dim must be at least 1, got {token_dim}"
+ raise ValueError(msg)
+ self.token_dim = token_dim
+ self.config = config or SmveConfig()
+ self.target_dim = self.config.output_dim
+ self.device = device or "cpu"
+ # Built lazily on first use: a 2,048 x 65,536 anchor set is 512 MiB.
+ self._anchors: tuple[Any, ...] | None = None
+ self._anchors_lock = threading.Lock()
+
+ def _get_anchors(self) -> tuple[Any, ...]:
+ """Return the anchor matrices, building them once."""
+ anchors = self._anchors
+ if anchors is None:
+ with self._anchors_lock:
+ anchors = self._anchors
+ if anchors is None:
+ anchors = tuple(self._build_anchors(rep) for rep in range(self.config.num_repetitions))
+ self._anchors = anchors
+ return anchors
+
+ def _build_anchors(self, rep: int) -> Any:
+ """One repetition's anchors: ``[token_dim, width]`` unit columns on the device."""
+ import torch
+
+ rng = np.random.default_rng(self.config.seed + rep)
+ anchors = rng.standard_normal((self.token_dim, self.config.width), dtype=np.float32)
+ anchors /= np.linalg.norm(anchors, axis=0, keepdims=True)
+ return torch.from_numpy(anchors).to(self.device)
+
+ def transform(self, output: EncodeOutput, *, is_query: bool = False) -> None:
+ """Add the SMVE encoding of every item as ``output.sparse``.
+
+ Args:
+ output: EncodeOutput with the multivector field populated.
+ is_query: If True, sum the tokens. If False, average them.
+ """
+ if output.multivector is None:
+ msg = "SmvePostprocessor requires multivector field"
+ raise ValueError(msg)
+ output.sparse = self.encode(output.multivector, is_query=is_query)
+
+ def encode(self, multivectors: Sequence[np.ndarray], *, is_query: bool) -> list[SparseVector]:
+ """Encode each item's token vectors as one sparse vector.
+
+ Args:
+ multivectors: Per-item token embeddings, each ``[num_tokens, token_dim]``.
+ is_query: If True, sum the tokens. If False, average them.
+
+ Returns:
+ One sparse vector per item, indices sorted ascending.
+ """
+ for tokens in multivectors:
+ if tokens.ndim != 2 or (tokens.shape[0] and tokens.shape[1] != self.token_dim):
+ msg = f"SMVE expects [num_tokens, {self.token_dim}] token embeddings, got shape {tokens.shape}"
+ raise ValueError(msg)
+ items_per_group = max(1, _SMVE_ACCUMULATOR_BYTES // (8 * self.config.output_dim))
+ encoded: list[SparseVector] = []
+ for start in range(0, len(multivectors), items_per_group):
+ encoded.extend(self._encode_group(multivectors[start : start + items_per_group], is_query=is_query))
+ return encoded
+
+ def _encode_group(self, multivectors: Sequence[np.ndarray], *, is_query: bool) -> list[SparseVector]:
+ """Encode a group of items together: one projection per chunk of their tokens."""
+ import torch
+
+ config = self.config
+ lengths = [int(tokens.shape[0]) for tokens in multivectors]
+ nonempty = [tokens for tokens in multivectors if tokens.shape[0]]
+ if not nonempty:
+ return [_empty_sparse_vector() for _ in multivectors]
+
+ batch, output_dim, width = len(multivectors), config.output_dim, config.width
+ tokens = torch.from_numpy(np.ascontiguousarray(np.concatenate(nonempty), dtype=np.float32)).to(self.device)
+ owners = torch.repeat_interleave(torch.arange(batch), torch.tensor(lengths)).to(self.device)
+
+ # Accumulate per (item, dimension) in one flat buffer.
+ sums = torch.zeros(batch * output_dim, dtype=torch.float32, device=self.device)
+ counts = None if is_query else torch.zeros_like(sums)
+ chunk = max(1, _SMVE_PROJECTION_CHUNK_BYTES // (4 * width))
+ for rep, anchors in enumerate(self._get_anchors()):
+ for start in range(0, tokens.shape[0], chunk):
+ stop = start + chunk
+ values, indices = torch.topk(tokens[start:stop] @ anchors, config.k, dim=1)
+ flat = (owners[start:stop, None] * output_dim + rep * width + indices).reshape(-1)
+ sums.index_add_(0, flat, values.reshape(-1))
+ if counts is not None:
+ counts.index_add_(0, flat, (values != 0).to(torch.float32).reshape(-1))
+
+ pooled = (sums if counts is None else sums / counts.clamp_min(1.0)).view(batch, output_dim)
+ owner_ids, dims = torch.nonzero(pooled, as_tuple=True)
+ values = pooled[owner_ids, dims]
+ per_item = torch.bincount(owner_ids, minlength=batch).tolist()
+ dims_np = dims.cpu().numpy().astype(np.int32)
+ values_np = values.cpu().numpy().astype(np.float32)
+
+ encoded: list[SparseVector] = []
+ offset = 0
+ for count in per_item:
+ item_dims, item_values = dims_np[offset : offset + count], values_np[offset : offset + count]
+ offset += count
+ encoded.append(self._finish(item_dims, item_values))
+ return encoded
+
+ def _finish(self, dims: np.ndarray, values: np.ndarray) -> SparseVector:
+ """Apply ``max_nonzeros`` and return the item's vector with sorted indices."""
+ limit = self.config.max_nonzeros
+ if limit is not None and dims.size > limit:
+ keep = np.argpartition(-np.abs(values), limit - 1)[:limit]
+ dims, values = dims[keep], values[keep]
+ order = np.argsort(dims, kind="stable")
+ return SparseVector(indices=dims[order], values=values[order])
+
+
+def _empty_sparse_vector() -> SparseVector:
+ """Encoding of an item with no tokens."""
+ return SparseVector(indices=np.zeros(0, dtype=np.int32), values=np.zeros(0, dtype=np.float32))
+
+
# =============================================================================
# Quantization Postprocessor
# =============================================================================
diff --git a/packages/sie_server/src/sie_server/core/postprocessor_registry.py b/packages/sie_server/src/sie_server/core/postprocessor_registry.py
index fe52a0fed..0e901fafc 100644
--- a/packages/sie_server/src/sie_server/core/postprocessor_registry.py
+++ b/packages/sie_server/src/sie_server/core/postprocessor_registry.py
@@ -35,7 +35,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
# Known postprocessor option keys
-POSTPROCESSOR_OPTION_KEYS = frozenset({"muvera", "output_dtype"})
+POSTPROCESSOR_OPTION_KEYS = frozenset({"muvera", "smve", "output_dtype"})
# Global quantize postprocessor (stateless, shared across all models)
_QUANTIZE_POSTPROCESSOR = QuantizePostprocessor()
diff --git a/packages/sie_server/tests/adapters/test_topk_embed.py b/packages/sie_server/tests/adapters/test_topk_embed.py
index 11d5edafe..ca1120ef1 100644
--- a/packages/sie_server/tests/adapters/test_topk_embed.py
+++ b/packages/sie_server/tests/adapters/test_topk_embed.py
@@ -387,10 +387,26 @@ class TestMetering:
items = [Item(text="one two"), Item(images=[_png()], text="ignored caption"), Item(text="three")]
assert adapter.count_input_tokens(items) == [2, 0, 1]
- def test_postprocessor_uses_the_token_dim(self, adapter: TopkEmbedAdapter) -> None:
+ def test_postprocessors_use_the_token_dim(self, adapter: TopkEmbedAdapter) -> None:
postprocessors = adapter.get_postprocessors()
- assert set(postprocessors) == {"muvera"}
+ assert set(postprocessors) == {"muvera", "smve"}
assert postprocessors["muvera"].token_dim == HEAD_WIDTH
+ assert postprocessors["smve"].token_dim == HEAD_WIDTH
+ # SMVE projects on the model's own device.
+ assert postprocessors["smve"].device == "cpu"
+
+ def test_smve_config_comes_from_the_loadtime_options(self) -> None:
+ smve = make_adapter(smve_config={"width": 512, "k": 8, "max_nonzeros": 64}).get_postprocessors()["smve"]
+ assert (smve.config.width, smve.config.k, smve.config.max_nonzeros) == (512, 8, 64)
+
+ def test_smve_turns_the_token_vectors_into_one_sparse_vector(self, adapter: TopkEmbedAdapter) -> None:
+ output = adapter.encode([Item(text="alpha beta gamma")], ["multivector"], is_query=True, options={"smve": {}})
+ smve = adapter.get_postprocessors()["smve"]
+ smve.transform(output, is_query=True)
+ assert output.sparse is not None
+ (vector,) = output.sparse
+ assert 0 < vector.indices.size <= output.multivector[0].shape[0] * smve.config.k
+ assert int(vector.indices.max()) < smve.target_dim
# On the cluster path one item's serialized result is chunked only up to 16 MiB (the sidecar's
diff --git a/packages/sie_server/tests/adapters/test_topk_embed_overlap.py b/packages/sie_server/tests/adapters/test_topk_embed_overlap.py
index 5dd6806a4..19a244b57 100644
--- a/packages/sie_server/tests/adapters/test_topk_embed_overlap.py
+++ b/packages/sie_server/tests/adapters/test_topk_embed_overlap.py
@@ -41,10 +41,16 @@ class TestTransferDtype:
@pytest.mark.parametrize(
"options",
- [{}, {"output_dtype": "float32"}, {"output_dtype": "int8"}, {"output_dtype": "float16", "muvera": {}}],
+ [
+ {},
+ {"output_dtype": "float32"},
+ {"output_dtype": "int8"},
+ {"output_dtype": "float16", "muvera": {}},
+ {"output_dtype": "float16", "smve": {}},
+ ],
)
def test_everything_else_stays_float32(self, adapter: TopkEmbedAdapter, options: dict[str, Any]) -> None:
- # MUVERA reads the multi-vectors after the adapter, so they stay at full precision.
+ # MUVERA and SMVE read the multi-vectors after the adapter, so they stay at full precision.
output = adapter.encode(TEXTS, ["multivector"], options=options)
assert output.multivector is not None
assert all(vector.dtype == np.float32 for vector in output.multivector)
diff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.py
index 8205ceef0..e04a546fa 100644
--- a/packages/sie_server/tests/api/test_encode_endpoint.py
+++ b/packages/sie_server/tests/api/test_encode_endpoint.py
@@ -17,6 +17,7 @@ from sie_server.config.model import (
ProfileConfig,
Tasks,
)
+from sie_server.core.inference_output import SparseVector
from sie_server.core.load_errors import LoadErrorClass, LoadFailure
from sie_server.core.registry import ModelRegistry
@@ -364,6 +365,46 @@ class TestEncodeEndpoint:
assert "multivector" not in item
muvera.transform.assert_called_once()
+ def test_routed_smve_profile_returns_sparse_from_multivectors(
+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock
+ ) -> None:
+ """An SMVE route asks the adapter for multivectors and returns the postprocessor's sparse vectors."""
+ mock_registry.get_config.return_value = ModelConfig(
+ sie_id="test-model:smve",
+ hf_id="org/test",
+ tasks=Tasks(encode=EncodeTask(multivector=EmbeddingDim(dim=128))),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="test:TestAdapter",
+ max_batch_tokens=8192,
+ adapter_options=AdapterOptions(runtime={"smve": {}, "output_types": ["sparse"]}),
+ )
+ },
+ )
+ smve = MagicMock()
+
+ def _postprocess(output: Any, *, is_query: bool) -> None:
+ del is_query
+ output.sparse = [
+ SparseVector(indices=np.array([3, 9], dtype=np.int32), values=np.array([0.5, 0.25], dtype=np.float32))
+ ]
+
+ smve.transform.side_effect = _postprocess
+ mock_registry.postprocessor_registry.register("test-model:smve", {"smve": smve})
+
+ response = client.post(
+ "/v1/encode/test-model:smve",
+ json={"items": [{"text": "Hello"}], "params": {"output_types": ["sparse"]}},
+ headers=JSON_HEADERS,
+ )
+
+ assert response.status_code == 200
+ assert mock_adapter.encode.call_args.args[1] == ["multivector"]
+ item = response.json()["items"][0]
+ assert item["sparse"] is not None
+ assert "multivector" not in item
+ smve.transform.assert_called_once()
+
def test_default_profile_can_enable_dense_via_muvera(
self,
client: TestClient,
diff --git a/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py b/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py
index 2fa443bab..31aa36795 100644
--- a/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py
+++ b/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py
@@ -52,3 +52,15 @@ def test_candle_profile_keeps_its_own_options() -> None:
assert "doc_prefix" not in candle.loadtime
assert "doc_punctuation_skiplist" not in candle.loadtime
assert candle.loadtime["max_seq_length"] == 8192
+
+
+def test_smve_profile_uses_topk_published_settings() -> None:
+ """The model card evaluates SMVE at width 65536 and k=32; the smve profile returns that encoding."""
+ config = _config()
+ smve = config.resolve_profile("smve")
+
+ assert smve.loadtime["smve_config"] == {"width": 65536, "k": 32}
+ assert smve.runtime["output_types"] == ["sparse"]
+ assert smve.runtime["output_similarity"] == {"sparse": "dot"}
+ assert smve.runtime["max_seq_length"] == 300
+ assert "smve_config" not in config.resolve_profile("candle").loadtime
diff --git a/packages/sie_server/tests/config/test_smve_profile_postprocessors.py b/packages/sie_server/tests/config/test_smve_profile_postprocessors.py
new file mode 100644
index 000000000..95a9b8e2a
--- /dev/null
+++ b/packages/sie_server/tests/config/test_smve_profile_postprocessors.py
@@ -0,0 +1,47 @@
+"""Every model that declares an ``smve`` profile builds its SMVE postprocessor from its own config."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+from sie_server.config.model import ModelConfig
+from sie_server.core.loader import load_adapter
+from sie_server.core.postprocessor import SmveConfig, SmvePostprocessor
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+
+
+def _config(model_file: str) -> ModelConfig:
+ return ModelConfig.model_validate(yaml.safe_load((_MODELS_DIR / model_file).read_text()))
+
+
+_SMVE_MODELS = tuple(path.name for path in sorted(_MODELS_DIR.glob("*.yaml")) if "smve" in _config(path.name).profiles)
+
+
+def test_model_catalog_contains_smve_profiles() -> None:
+ assert _SMVE_MODELS
+
+
[email protected]("model_file", _SMVE_MODELS)
+def test_smve_profile_returns_dot_scored_sparse_vectors(model_file: str) -> None:
+ profile = _config(model_file).resolve_profile("smve")
+
+ assert profile.runtime["output_types"] == ["sparse"]
+ assert profile.runtime["output_similarity"] == {"sparse": "dot"}
+ assert profile.runtime["smve"] == {}
+
+
[email protected]("model_file", _SMVE_MODELS)
+def test_smve_profile_builds_the_configured_postprocessor(model_file: str) -> None:
+ config = _config(model_file)
+ default, smve_profile = config.resolve_profile("default"), config.resolve_profile("smve")
+ # The profile shares the default profile's loaded adapter, which reads smve_config.
+ assert smve_profile.loadtime == default.loadtime
+ assert "smve_config" in default.loadtime
+
+ smve = load_adapter(config, _MODELS_DIR, device="cpu").get_postprocessors()["smve"]
+
+ assert isinstance(smve, SmvePostprocessor)
+ assert smve.config == SmveConfig(**default.loadtime["smve_config"])
diff --git a/packages/sie_server/tests/core/test_model_load_timeout.py b/packages/sie_server/tests/core/test_model_load_timeout.py
index dd48b01e9..e79b5595f 100644
--- a/packages/sie_server/tests/core/test_model_load_timeout.py
+++ b/packages/sie_server/tests/core/test_model_load_timeout.py
@@ -89,6 +89,27 @@ def test_muvera_runtime_requires_registered_postprocessor() -> None:
loader._finish_load("test/visual:muvera", "cpu", adapter, config)
+def test_smve_runtime_requires_registered_postprocessor() -> None:
+ loader = _make_loader()
+ config = ModelConfig(
+ sie_id="test/late:smve",
+ hf_id="test/late",
+ tasks=Tasks(encode=EncodeTask(multivector=EmbeddingDim(dim=8))),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.base:ModelAdapter",
+ max_batch_tokens=8,
+ adapter_options=AdapterOptions(runtime={"smve": {}, "output_types": ["sparse"]}),
+ )
+ },
+ )
+ adapter = MagicMock()
+ adapter.get_postprocessors.return_value = {"muvera": MagicMock()}
+
+ with pytest.raises(ValueError, match=r"requests SMVE.*did not register a 'smve' postprocessor"):
+ loader._finish_load("test/late:smve", "cpu", adapter, config)
+
+
class TestResolveLoadTimeout:
"""``_resolve_load_timeout`` precedence and parsing."""
diff --git a/packages/sie_server/tests/core/test_postprocessor_registry.py b/packages/sie_server/tests/core/test_postprocessor_registry.py
index fe4d1c1d0..29be983da 100644
--- a/packages/sie_server/tests/core/test_postprocessor_registry.py
+++ b/packages/sie_server/tests/core/test_postprocessor_registry.py
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock
import numpy as np
import pytest
from sie_server.core.inference_output import EncodeOutput
-from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor
+from sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor, SmveConfig, SmvePostprocessor
from sie_server.core.postprocessor_registry import PostprocessorRegistry
@@ -96,6 +96,25 @@ class TestPostprocessorTransform:
assert output.dense.shape[0] == 2 # Batch size
assert elapsed_ms > 0
+ def test_transform_sync_applies_smve_and_muvera_together(
+ self, registry: PostprocessorRegistry, muvera_postprocessor: MuveraPostprocessor
+ ) -> None:
+ """Both multivector postprocessors read the same multivectors and add their own output."""
+ smve = SmvePostprocessor(token_dim=8, config=SmveConfig(width=64, k=4))
+ registry.register("test-model", {"muvera": muvera_postprocessor, "smve": smve})
+ output = EncodeOutput(
+ multivector=[np.random.randn(5, 8).astype(np.float32) for _ in range(2)],
+ multivector_token_dim=8,
+ )
+
+ registry.transform_sync("test-model", output, {"muvera": {}, "smve": {}}, is_query=True)
+
+ assert output.dense is not None
+ assert output.dense.shape[0] == 2
+ assert output.sparse is not None
+ assert len(output.sparse) == 2
+ assert all(0 < v.indices.size <= 5 * 4 for v in output.sparse)
+
def test_transform_sync_skips_when_option_null(
self, registry: PostprocessorRegistry, muvera_postprocessor: MuveraPostprocessor
) -> None:
diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.py
index 2752a9d14..bdcd21e77 100644
--- a/packages/sie_server/tests/core/test_runtime_options.py
+++ b/packages/sie_server/tests/core/test_runtime_options.py
@@ -593,3 +593,81 @@ async def test_bound_generation_keeps_engine_timeout_errors() -> None:
await _drain(bound_generation(failing(), GenerationTimeouts(overall_s=5.0)))
assert not isinstance(raised.value, GenerationTimeoutError)
+
+
+def _late_interaction_config() -> ModelConfig:
+ """A multivector model whose profiles expose MUVERA (dense) and SMVE (sparse) outputs."""
+ return ModelConfig.model_validate(
+ {
+ "sie_id": "test/late-interaction",
+ "hf_id": "test/late-interaction",
+ "inputs": {"text": True},
+ "tasks": {"encode": {"dense": None, "sparse": None, "multivector": {"dim": 8}}},
+ "max_sequence_length": 512,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 8192,
+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",
+ "adapter_options": {"runtime": {"output_types": ["multivector"]}},
+ },
+ "smve": {
+ "extends": "default",
+ "adapter_options": {"runtime": {"output_types": ["sparse"], "smve": {}}},
+ },
+ "muvera_and_smve": {
+ "extends": "default",
+ "adapter_options": {
+ "runtime": {"output_types": ["dense", "sparse", "multivector"], "muvera": {}, "smve": {}}
+ },
+ },
+ },
+ }
+ )
+
+
+def test_smve_profile_asks_the_adapter_for_multivectors() -> None:
+ config = _late_interaction_config()
+ effective_options, selected_profile = merge_runtime_options_with_profile(config, {"profile": "smve"})
+
+ adapter_output_types, response_output_types = resolve_encode_output_types(
+ config, None, selected_profile, effective_options
+ )
+
+ assert adapter_output_types == ["multivector"]
+ assert response_output_types == ["sparse"]
+
+
+def test_muvera_and_smve_share_one_multivector_request() -> None:
+ config = _late_interaction_config()
+ effective_options, selected_profile = merge_runtime_options_with_profile(config, {"profile": "muvera_and_smve"})
+
+ adapter_output_types, response_output_types = resolve_encode_output_types(
+ config, ["dense", "sparse", "multivector"], selected_profile, effective_options
+ )
+
+ assert adapter_output_types == ["multivector"]
+ assert response_output_types == ["dense", "sparse", "multivector"]
+
+
+def test_sparse_without_smve_still_comes_from_the_adapter() -> None:
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "test/sparse",
+ "hf_id": "test/sparse",
+ "inputs": {"text": True},
+ "tasks": {"encode": {"sparse": {"dim": 32}}},
+ "max_sequence_length": 512,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 8192,
+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",
+ "adapter_options": {"runtime": {"output_types": ["sparse"]}},
+ },
+ },
+ }
+ )
+ effective_options, selected_profile = merge_runtime_options_with_profile(config, None)
+
+ adapter_output_types, _ = resolve_encode_output_types(config, ["sparse"], selected_profile, effective_options)
+
+ assert adapter_output_types == ["sparse"]
diff --git a/packages/sie_server/tests/core/test_smve_postprocessor.py b/packages/sie_server/tests/core/test_smve_postprocessor.py
new file mode 100644
index 000000000..2f09f04ab
--- /dev/null
+++ b/packages/sie_server/tests/core/test_smve_postprocessor.py
@@ -0,0 +1,206 @@
+"""SMVE (Sparse Multi-Vector Encoding) postprocessor: multivector to sparse."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+from sie_server.core import postprocessor as postprocessor_module
+from sie_server.core.inference_output import EncodeOutput, SparseVector
+from sie_server.core.postprocessor import SmveConfig, SmvePostprocessor
+
+TOKEN_DIM = 16
+
+
+def _tokens(rng: np.random.Generator, n: int, dim: int = TOKEN_DIM) -> np.ndarray:
+ tokens = rng.standard_normal((n, dim)).astype(np.float32)
+ return tokens / np.linalg.norm(tokens, axis=1, keepdims=True)
+
+
+def _anchors(config: SmveConfig, dim: int = TOKEN_DIM) -> list[np.ndarray]:
+ """The anchors as the method defines them: seeded Gaussian columns scaled to unit length."""
+ anchors = []
+ for rep in range(config.num_repetitions):
+ matrix = np.random.default_rng(config.seed + rep).standard_normal((dim, config.width), dtype=np.float32)
+ anchors.append(matrix / np.linalg.norm(matrix, axis=0, keepdims=True))
+ return anchors
+
+
+def _reference(tokens: np.ndarray, config: SmveConfig, *, is_query: bool) -> np.ndarray:
+ """SMVE written out per token: project, keep the top k, then sum (query) or average (document)."""
+ pooled = []
+ for anchors in _anchors(config, tokens.shape[1]):
+ projections = tokens.astype(np.float64) @ anchors.astype(np.float64)
+ sparse = np.zeros_like(projections)
+ top = np.argsort(-projections, axis=1)[:, : config.k]
+ np.put_along_axis(sparse, top, np.take_along_axis(projections, top, axis=1), axis=1)
+ total = sparse.sum(axis=0)
+ if not is_query:
+ total /= np.maximum((sparse != 0).sum(axis=0), 1)
+ pooled.append(total)
+ return np.concatenate(pooled)
+
+
+def _dense(vector: SparseVector, dim: int) -> np.ndarray:
+ out = np.zeros(dim, dtype=np.float64)
+ out[vector.indices] = vector.values
+ return out
+
+
[email protected]("is_query", [True, False])
[email protected]("num_repetitions", [1, 2])
+def test_matches_the_reference_definition(is_query: bool, num_repetitions: int) -> None:
+ rng = np.random.default_rng(0)
+ config = SmveConfig(width=256, k=8, num_repetitions=num_repetitions, seed=7)
+ items = [_tokens(rng, n) for n in (1, 5, 13)]
+
+ encoded = SmvePostprocessor(TOKEN_DIM, config).encode(items, is_query=is_query)
+
+ for tokens, vector in zip(items, encoded, strict=True):
+ np.testing.assert_allclose(
+ _dense(vector, config.output_dim), _reference(tokens, config, is_query=is_query), rtol=1e-5, atol=1e-6
+ )
+
+
+def test_a_batch_encodes_each_item_as_if_alone() -> None:
+ rng = np.random.default_rng(1)
+ items = [_tokens(rng, n) for n in (3, 1, 9, 4)]
+ smve = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=128, k=4))
+
+ together = smve.encode(items, is_query=False)
+ alone = [smve.encode([tokens], is_query=False)[0] for tokens in items]
+
+ for a, b in zip(together, alone, strict=True):
+ np.testing.assert_array_equal(a.indices, b.indices)
+ np.testing.assert_allclose(a.values, b.values, rtol=1e-6)
+
+
+def test_chunks_and_groups_do_not_change_the_result(monkeypatch: pytest.MonkeyPatch) -> None:
+ rng = np.random.default_rng(2)
+ items = [_tokens(rng, n) for n in (7, 2, 11)]
+ config = SmveConfig(width=64, k=4)
+ expected = SmvePostprocessor(TOKEN_DIM, config).encode(items, is_query=True)
+
+ # One token per projection chunk and one item per accumulator group.
+ monkeypatch.setattr(postprocessor_module, "_SMVE_PROJECTION_CHUNK_BYTES", 1)
+ monkeypatch.setattr(postprocessor_module, "_SMVE_ACCUMULATOR_BYTES", 1)
+ got = SmvePostprocessor(TOKEN_DIM, config).encode(items, is_query=True)
+
+ for a, b in zip(expected, got, strict=True):
+ np.testing.assert_array_equal(a.indices, b.indices)
+ np.testing.assert_allclose(a.values, b.values, rtol=1e-6)
+
+
+def test_anchors_come_from_the_seed() -> None:
+ config = SmveConfig(width=32, k=2, num_repetitions=2, seed=11)
+ built = [a.numpy() for a in SmvePostprocessor(TOKEN_DIM, config)._get_anchors()]
+
+ for got, expected in zip(built, _anchors(config), strict=True):
+ np.testing.assert_array_equal(got, expected)
+ np.testing.assert_allclose(np.linalg.norm(got, axis=0), 1.0, rtol=1e-6)
+ other = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=32, k=2, seed=12))._get_anchors()[0].numpy()
+ assert not np.array_equal(other, built[0])
+
+
+def test_queries_sum_and_documents_average() -> None:
+ token = _tokens(np.random.default_rng(3), 1)
+ smve = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=64, k=4))
+ single_query, double_query = smve.encode([token, np.vstack([token, token])], is_query=True)
+ single_doc, double_doc = smve.encode([token, np.vstack([token, token])], is_query=False)
+
+ np.testing.assert_array_equal(double_query.indices, single_query.indices)
+ np.testing.assert_allclose(double_query.values, 2 * single_query.values, rtol=1e-6)
+ np.testing.assert_array_equal(double_doc.indices, single_doc.indices)
+ np.testing.assert_allclose(double_doc.values, single_doc.values, rtol=1e-6)
+
+
+def test_output_layout() -> None:
+ rng = np.random.default_rng(4)
+ config = SmveConfig(width=100, k=5, num_repetitions=3)
+ smve = SmvePostprocessor(TOKEN_DIM, config)
+ (single,), (many,) = smve.encode([_tokens(rng, 1)], is_query=True), smve.encode([_tokens(rng, 40)], is_query=False)
+
+ assert smve.target_dim == config.output_dim == 300
+ # One token keeps exactly k projections per repetition.
+ assert single.indices.size == config.k * config.num_repetitions
+ for vector in (single, many):
+ assert vector.indices.dtype == np.int32
+ assert vector.values.dtype == np.float32
+ assert np.all(np.diff(vector.indices) > 0)
+ assert vector.indices.min() >= 0
+ assert vector.indices.max() < config.output_dim
+ assert many.indices.size <= 40 * config.k * config.num_repetitions
+
+
+def test_items_without_tokens_encode_as_empty_vectors() -> None:
+ rng = np.random.default_rng(5)
+ empty = np.zeros((0, TOKEN_DIM), dtype=np.float32)
+ smve = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=32, k=2))
+
+ assert all(v.indices.size == 0 for v in smve.encode([empty, empty], is_query=True))
+ first, middle, last = smve.encode([empty, _tokens(rng, 3), empty], is_query=False)
+ assert first.indices.size == 0
+ assert middle.indices.size > 0
+ assert last.indices.size == 0
+
+
+def test_max_nonzeros_keeps_the_largest_values() -> None:
+ tokens = _tokens(np.random.default_rng(6), 30)
+ full = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=128, k=8)).encode([tokens], is_query=False)[0]
+ pruned = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=128, k=8, max_nonzeros=10)).encode([tokens], is_query=False)[
+ 0
+ ]
+
+ largest = np.sort(np.argsort(-np.abs(full.values))[:10])
+ np.testing.assert_array_equal(pruned.indices, full.indices[largest])
+ np.testing.assert_allclose(pruned.values, full.values[largest], rtol=1e-6)
+
+
+def test_dot_product_ranks_a_matching_document_first() -> None:
+ rng = np.random.default_rng(7)
+ query = _tokens(rng, 6)
+ matching = query + 0.05 * rng.standard_normal(query.shape).astype(np.float32)
+ documents = [_tokens(rng, 6) for _ in range(9)]
+ documents.insert(4, matching / np.linalg.norm(matching, axis=1, keepdims=True))
+ smve = SmvePostprocessor(TOKEN_DIM, SmveConfig(width=2048, k=16))
+
+ (encoded_query,) = smve.encode([query], is_query=True)
+ scores = [_dense(encoded_query, 2048) @ _dense(d, 2048) for d in smve.encode(documents, is_query=False)]
+
+ assert int(np.argmax(scores)) == 4
+
+
+def test_transform_adds_sparse_output() -> None:
+ rng = np.random.default_rng(8)
+ output = EncodeOutput(multivector=[_tokens(rng, 3), _tokens(rng, 2)])
+ SmvePostprocessor(TOKEN_DIM, SmveConfig(width=32, k=2)).transform(output, is_query=True)
+
+ assert output.sparse is not None
+ assert len(output.sparse) == 2
+ assert output.multivector is not None
+
+
+def test_transform_requires_multivectors() -> None:
+ with pytest.raises(ValueError, match="requires multivector"):
+ SmvePostprocessor(TOKEN_DIM).transform(EncodeOutput(dense=np.zeros((1, 4), dtype=np.float32)))
+
+
+def test_rejects_tokens_of_another_width() -> None:
+ with pytest.raises(ValueError, match="token embeddings"):
+ SmvePostprocessor(TOKEN_DIM, SmveConfig(width=32, k=2)).encode(
+ [np.zeros((2, TOKEN_DIM + 1), dtype=np.float32)], is_query=True
+ )
+
+
+ "kwargs",
+ [
+ {"width": 0},
+ {"width": 8, "k": 0},
+ {"width": 8, "k": 9},
+ {"num_repetitions": 0},
+ {"max_nonzeros": 0},
+ ],
+)
+def test_config_rejects_invalid_settings(kwargs: dict[str, int]) -> None:
+ with pytest.raises(ValueError, match="SMVE"):
+ SmveConfig(**kwargs)
diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.py
index 8c4dd910a..45964b84e 100644
--- a/packages/sie_server/tests/test_queue_executor.py
+++ b/packages/sie_server/tests/test_queue_executor.py
@@ -900,6 +900,40 @@ class TestProcessEncodeBatch:
assert outcome.outcomes[0].result_msgpack is not None
assert msgpack.unpackb(outcome.outcomes[0].result_msgpack, raw=False) == {"dense": [0.1, 0.2]}
+ @pytest.mark.parametrize(
+ ("model_file", "route"),
+ [
+ ("topk-io__Iso-ModernColBERT.yaml", "topk-io/Iso-ModernColBERT:smve"),
+ ("topk-io__topk-embed-v1-small.yaml", "topk-io/topk-embed-v1-small:smve"),
+ ("topk-io__topk-embed-v1-xsmall.yaml", "topk-io/topk-embed-v1-xsmall:smve"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_smve_route_translates_managed_adapter_output(self, model_file: str, route: str) -> None:
+ """SMVE routes authorize sparse while adapters emit multivectors."""
+ config = _load_profile_variant(model_file, route)
+ assert config.synthetic_profile_variant_source is not None
+ reg = _make_registry()
+ reg.get_config.return_value = config
+ ex = QueueExecutor(reg)
+ sparse = {"sparse": {"indices": [3, 9], "values": [0.5, 0.25]}}
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([sparse], RequestTiming()),
+ ) as mock_encode:
+ outcome = await ex.process_encode_batch(ProcessEncodeBatchRequest(model_id=route, items=[_encode_item()]))
+
+ call = mock_encode.await_args.kwargs
+ assert call["model"] == route
+ assert call["output_types"] == ["multivector"]
+ assert call["response_output_types"] == ["sparse"]
+ assert outcome.outcomes[0].disposition == "publish_and_ack"
+ assert outcome.outcomes[0].result_msgpack is not None
+ # The queue path re-encodes the sparse vector in its wire format.
+ assert set(msgpack.unpackb(outcome.outcomes[0].result_msgpack, raw=False)) == {"sparse"}
+
@pytest.mark.asyncio
async def test_request_options_cannot_self_authorize_managed_output(self) -> None:
"""Caller options cannot expand the managed route's output allowlist."""