BGE-M3 sparse embeddings for vLLM: IO processor plugin + Portainer stack
Adds a vllm.io_processor_plugins entry point (bge_m3_sparse_plugin) that serves learned sparse vectors of BAAI/bge-m3 over POST /pooling, on top of the BgeM3EmbeddingModel architecture that already ships with vLLM. - plugin/: python package, sparse (token_classify) and dense (embed) modes, batch support, per-request weight threshold - entrypoint.sh: pip install the plugin from a read-only mount at container start - docker-compose.yml: stack ready for Portainer (git repository deployment) Verified against vLLM 0.30.0 on an RTX 5070: single/batch/parallel requests, validation errors, and weights matching the FlagEmbedding reference formula.
This commit is contained in:
commit
1c533f98f0
8 files changed
+562
No files matched your search
@@ -0,0 +1,15 @@
|
||||
"""IO processor plugin that serves BAAI/bge-m3 sparse (learned sparse) vectors.
|
||||
|
||||
Registered under the ``vllm.io_processor_plugins`` entry point group; the entry
|
||||
point value is the fully qualified name of the IOProcessor class, so vLLM can
|
||||
import it lazily without pulling vllm into this package's import path.
|
||||
"""
|
||||
|
||||
__all__ = ["register"]
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
|
||||
def register() -> str:
|
||||
# resolved by vllm.utils.import_utils.resolve_obj_by_qualname -> dotted path
|
||||
return "bge_m3_sparse.io_processor.BgeM3SparseIOProcessor"
|
||||
@@ -0,0 +1,256 @@
|
||||
"""BGE-M3 IO processor: learned-sparse (and dense) embeddings over /pooling.
|
||||
|
||||
The ``BgeM3EmbeddingModel`` that ships with vLLM (``--hf-overrides
|
||||
'{"architectures": ["BgeM3EmbeddingModel"]}'``) already produces everything
|
||||
needed on the engine side:
|
||||
|
||||
* ``token_classify`` -> one ReLU'd ``sparse_linear`` weight per token, with the
|
||||
BOS/EOS positions already stripped by ``BOSEOSFilter``;
|
||||
* ``embed`` -> normalized dense CLS vector.
|
||||
|
||||
This plugin only turns those tensors into the usual sparse-vector format
|
||||
(``token_id -> weight``) that Milvus/pyserini style sparse search consumes, and
|
||||
takes care of the request/response shape.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Sequence
|
||||
from contextvars import ContextVar
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import PoolingRequestOutput
|
||||
from vllm.plugins.io_processors.interface import IOProcessor
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.renderers import BaseRenderer
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
MODE_SPARSE = "sparse"
|
||||
MODE_DENSE = "dense"
|
||||
SUPPORTED_MODES = (MODE_SPARSE, MODE_DENSE)
|
||||
|
||||
TASK_BY_MODE = {MODE_SPARSE: "token_classify", MODE_DENSE: "embed"}
|
||||
|
||||
DEFAULT_MODE = os.environ.get("BGE_M3_SPARSE_MODE", MODE_SPARSE).lower()
|
||||
DEFAULT_THRESHOLD = float(os.environ.get("BGE_M3_SPARSE_THRESHOLD", "0.0"))
|
||||
|
||||
_CURRENT: ContextVar["_Options | None"] = ContextVar("bge_m3_sparse_options", default=None)
|
||||
|
||||
|
||||
class _Options:
|
||||
__slots__ = ("mode", "threshold")
|
||||
|
||||
def __init__(self, mode: str, threshold: float) -> None:
|
||||
self.mode = mode
|
||||
self.threshold = threshold
|
||||
|
||||
|
||||
class BgeM3SparseIOProcessor(IOProcessor[dict[str, Any], list[dict[str, Any]]]):
|
||||
def __init__(self, vllm_config: VllmConfig, renderer: BaseRenderer) -> None:
|
||||
super().__init__(vllm_config, renderer)
|
||||
|
||||
hf_config = vllm_config.model_config.hf_config
|
||||
self.bos_token_id = _token_id_or(getattr(hf_config, "bos_token_id", None))
|
||||
self.eos_token_id = _token_id_or(getattr(hf_config, "eos_token_id", None))
|
||||
|
||||
self._tokenizer = renderer.get_tokenizer()
|
||||
self._options: dict[str, _Options] = {}
|
||||
self._token_cache: dict[int, str] = {}
|
||||
|
||||
# ------------------------------------------------------------------ input
|
||||
def parse_data(self, data: object) -> dict[str, Any]:
|
||||
if isinstance(data, str):
|
||||
return self._payload([data], MODE_SPARSE, DEFAULT_THRESHOLD)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError(
|
||||
f"`data` must be a string or an object, got {type(data).__name__}"
|
||||
)
|
||||
|
||||
mode = str(data.get("mode", MODE_SPARSE)).lower()
|
||||
if mode not in SUPPORTED_MODES:
|
||||
raise ValueError(
|
||||
f"unsupported mode {mode!r}, expected one of {SUPPORTED_MODES}"
|
||||
)
|
||||
|
||||
threshold = float(data.get("threshold", DEFAULT_THRESHOLD))
|
||||
|
||||
if "texts" in data:
|
||||
texts = data["texts"]
|
||||
if not isinstance(texts, (list, tuple)) or not texts:
|
||||
raise ValueError("`texts` must be a non-empty list of strings")
|
||||
payload = [str(text) for text in texts]
|
||||
elif "text" in data:
|
||||
payload = [str(data["text"])]
|
||||
else:
|
||||
raise ValueError("`data` must contain `text` or `texts`")
|
||||
|
||||
return self._payload(payload, mode, threshold)
|
||||
|
||||
@staticmethod
|
||||
def _payload(
|
||||
texts: list[str], mode: str, threshold: float
|
||||
) -> dict[str, Any]:
|
||||
return {"texts": texts, "mode": mode, "threshold": threshold}
|
||||
|
||||
def pre_process(
|
||||
self,
|
||||
prompt: dict[str, Any],
|
||||
request_id: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> list[str]:
|
||||
options = _Options(prompt["mode"], float(prompt["threshold"]))
|
||||
_CURRENT.set(options)
|
||||
if request_id is not None:
|
||||
self._options[request_id] = options
|
||||
return list(prompt["texts"])
|
||||
|
||||
def merge_pooling_params(
|
||||
self, params: PoolingParams | None = None
|
||||
) -> PoolingParams:
|
||||
options = self._current_options()
|
||||
task = TASK_BY_MODE.get(options.mode)
|
||||
if task is None:
|
||||
raise ValueError(
|
||||
f"unsupported mode {options.mode!r}, expected one of {SUPPORTED_MODES}"
|
||||
)
|
||||
return PoolingParams(
|
||||
use_activation=params.use_activation if params is not None else None,
|
||||
task=task,
|
||||
)
|
||||
|
||||
# ----------------------------------------------------------------- output
|
||||
def post_process(
|
||||
self,
|
||||
model_output: Sequence[PoolingRequestOutput],
|
||||
request_id: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> list[dict[str, Any]]:
|
||||
options = self._options.pop(request_id, None) or self._current_options()
|
||||
results: list[dict[str, Any]] = []
|
||||
for index, res in enumerate(model_output):
|
||||
if options.mode == MODE_DENSE:
|
||||
embedding = _to_floats(res.outputs.data)
|
||||
results.append(
|
||||
{
|
||||
"index": index,
|
||||
"mode": MODE_DENSE,
|
||||
"dimension": len(embedding),
|
||||
"embedding": embedding,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
weights = _to_floats(res.outputs.data)
|
||||
token_ids = self._align_token_ids(
|
||||
list(res.prompt_token_ids or []), len(weights)
|
||||
)
|
||||
results.append(self._build_sparse(index, token_ids, weights, options))
|
||||
return results
|
||||
|
||||
def _build_sparse(
|
||||
self,
|
||||
index: int,
|
||||
token_ids: list[int],
|
||||
weights: list[float],
|
||||
options: _Options,
|
||||
) -> dict[str, Any]:
|
||||
best: dict[int, float] = {}
|
||||
for token_id, weight in zip(token_ids, weights):
|
||||
if token_id in (self.bos_token_id, self.eos_token_id):
|
||||
continue
|
||||
if weight <= options.threshold:
|
||||
continue
|
||||
if weight > best.get(token_id, 0.0):
|
||||
best[token_id] = weight
|
||||
|
||||
tokens = [
|
||||
{"token": self._decode(token_id), "id": token_id, "weight": round(weight, 6)}
|
||||
for token_id, weight in best.items()
|
||||
]
|
||||
return {
|
||||
"index": index,
|
||||
"mode": MODE_SPARSE,
|
||||
"length": len(tokens),
|
||||
"tokens": tokens,
|
||||
"sparse": {str(token_id): round(weight, 6) for token_id, weight in best.items()},
|
||||
"sparse_str": " ".join(f"{t}:{w:.6f}" for t, w in best.items()),
|
||||
}
|
||||
|
||||
def _align_token_ids(self, token_ids: list[int], count: int) -> list[int]:
|
||||
if token_ids and token_ids[0] == self.bos_token_id:
|
||||
token_ids = token_ids[1:]
|
||||
if token_ids and token_ids[-1] == self.eos_token_id:
|
||||
token_ids = token_ids[:-1]
|
||||
if len(token_ids) < count:
|
||||
logger.warning(
|
||||
"prompt has %d token(s) but the model returned %d score(s)",
|
||||
len(token_ids),
|
||||
count,
|
||||
)
|
||||
token_ids = token_ids + [self.bos_token_id] * (count - len(token_ids))
|
||||
return token_ids[:count]
|
||||
|
||||
def _current_options(self) -> _Options:
|
||||
options = _CURRENT.get()
|
||||
if options is not None:
|
||||
return options
|
||||
if DEFAULT_MODE not in SUPPORTED_MODES:
|
||||
raise ValueError(
|
||||
f"BGE_M3_SPARSE_MODE must be one of {SUPPORTED_MODES}, got {DEFAULT_MODE!r}"
|
||||
)
|
||||
return _Options(DEFAULT_MODE, DEFAULT_THRESHOLD)
|
||||
|
||||
def _decode(self, token_id: int) -> str:
|
||||
cached = self._token_cache.get(token_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
text = ""
|
||||
try:
|
||||
text = self._tokenizer.decode([token_id])
|
||||
except Exception: # pragma: no cover - tokenizer specific
|
||||
logger.debug("tokenizer.decode failed for id %s", token_id, exc_info=True)
|
||||
if not text:
|
||||
try:
|
||||
text = self._tokenizer.convert_ids_to_tokens([token_id])[0]
|
||||
except Exception: # pragma: no cover - tokenizer specific
|
||||
logger.debug(
|
||||
"convert_ids_to_tokens failed for id %s", token_id, exc_info=True
|
||||
)
|
||||
if not text:
|
||||
text = f"tok{token_id}"
|
||||
|
||||
self._token_cache[token_id] = text
|
||||
return text
|
||||
|
||||
|
||||
def _token_id_or(value: Any, default: int = -1) -> int:
|
||||
if value is None:
|
||||
return default
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _to_floats(data: Any) -> list[float]:
|
||||
if isinstance(data, torch.Tensor):
|
||||
return data.detach().to(torch.float32).flatten().cpu().tolist()
|
||||
if isinstance(data, (list, tuple)):
|
||||
if data and isinstance(data[0], torch.Tensor):
|
||||
return torch.cat([d.flatten() for d in data]).to(torch.float32).tolist()
|
||||
flat: list[float] = []
|
||||
for item in data:
|
||||
if isinstance(item, (list, tuple)):
|
||||
flat.extend(float(value) for value in item)
|
||||
else:
|
||||
flat.append(float(item))
|
||||
return flat
|
||||
return [float(data)]
|
||||
@@ -0,0 +1,18 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "bge-m3-sparse-plugin"
|
||||
version = "0.1.0"
|
||||
description = "vLLM IO processor plugin: BAAI/bge-m3 learned sparse (and dense) embeddings"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = { text = "Apache-2.0" }
|
||||
dependencies = []
|
||||
|
||||
[project.entry-points."vllm.io_processor_plugins"]
|
||||
bge_m3_sparse_plugin = "bge_m3_sparse:register"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["bge_m3_sparse"]
|
||||
Reference in new issue
Block a user