From 1c533f98f08929e3127994f8190be574398be47f Mon Sep 17 00:00:00 2001 From: opencode Date: Mon, 28 Sep 2026 13:54:20 +0700 Subject: [PATCH] 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. --- .env.example | 21 +++ .gitignore | 8 + README.md | 168 ++++++++++++++++++ docker-compose.yml | 44 +++++ entrypoint.sh | 32 ++++ plugin/bge_m3_sparse/__init__.py | 15 ++ plugin/bge_m3_sparse/io_processor.py | 256 +++++++++++++++++++++++++++ plugin/pyproject.toml | 18 ++ 8 files changed, 562 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 entrypoint.sh create mode 100644 plugin/bge_m3_sparse/__init__.py create mode 100644 plugin/bge_m3_sparse/io_processor.py create mode 100644 plugin/pyproject.toml diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0fab50f --- /dev/null +++ b/.env.example @@ -0,0 +1,21 @@ +# Values used by docker-compose.yml. Every variable has a default, +# so the stack starts even without this file. + +# port on the host +HOST_PORT=8083 + +# share of VRAM vLLM may use (raise it if the model does not fit) +GPU_MEMORY_UTILIZATION=0.15 + +MAX_MODEL_LEN=8192 +MODEL=BAAI/bge-m3 + +# pin a version instead of latest, the plugin is tied to the vLLM API +VLLM_IMAGE=vllm/vllm-openai:latest + +# model cache on the host +HF_CACHE=/root/.cache/huggingface + +# defaults for the /pooling "data" object +BGE_M3_SPARSE_MODE=sparse +BGE_M3_SPARSE_THRESHOLD=0.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c61175c --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.env +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +.venv/ +venv/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..241e4ab --- /dev/null +++ b/README.md @@ -0,0 +1,168 @@ +# vllm-bge-sparse + +Плагин для [vLLM](https://github.com/vllm-project/vllm), который поднимает +`BAAI/bge-m3` в режиме **learned sparse retrieval** (sparse-векторы вида +`token_id -> вес`) на одном порту `8000`, без пересборки образа `vllm/vllm-openai`. + +Что уже умеет сам vLLM: архитектура `BgeM3EmbeddingModel` уже есть в реестре +моделей, для задачи `token_classify` пул отдаёт один ReLU-вес на токен +(веса `sparse_linear`, BOS/EOS вырезаны). Плагин добавляет только удобный +вход/выход поверх `POST /pooling`: + +* на входе `{"text" | "texts", "mode": "sparse" | "dense", "threshold": 0.05}`; +* на выходе — либо `{"tokens": [{"token": "ресурсы", "id": 183276, "weight": 0.22}]}`, + либо `"sparse_str": "12386:0.170654 103:0.171021 ..."` в формате pyserini/Milvus. + +Веса сверены с эталоном (FlagEmbedding-формула `relu(sparse_linear(h))`, fp32, CPU): +совпадение до 4-го знака. + +## Быстрый старт в Portainer + +1. **Stacks → Add stack → Git repository** +2. Repository URL: `https://git.hub.ains-pro.ru/AINS/vllm-sparce` + (для приватного репозитория — Credentials: repository access token) +3. Compose path: `docker-compose.yml` +4. Environment variables (не обязательно, есть значения по умолчанию): + + | Переменная | По умолчанию | Назначение | + |---------------------------|---------------------------|-----------------------------------------------| + | `HOST_PORT` | `8083` | порт на хосте | + | `GPU_MEMORY_UTILIZATION` | `0.15` | доля VRAM под vLLM | + | `MAX_MODEL_LEN` | `8192` | контекст BGE-M3 | + | `MODEL` | `BAAI/bge-m3` | модель | + | `VLLM_IMAGE` | `vllm/vllm-openai:latest` | образ (лучше зафиксировать тег версии) | + | `HF_CACHE` | `/root/.cache/huggingface`| кэш моделей на хосте | + | `BGE_M3_SPARSE_MODE` | `sparse` | режим по умолчанию, если поле `mode` не задано | + | `BGE_M3_SPARSE_THRESHOLD` | `0.0` | порог отсечения весов по умолчанию | + +5. **Deploy the stack** + +Стек поднимает `vllm/vllm-openai`, при старте `entrypoint.sh` ставит плагин из +примонтированной папки `./plugin` (`pip install --no-deps --no-build-isolation`, +интернет для этого не нужен) и передаёт управление API-серверу vLLM. +Модель весит ~2.3 ГБ и скачивается при первом запуске в `HF_CACHE`. + +## Запросы + +Плагин подключается на `POST /pooling` (не `/v1/embeddings` — этот endpoint +отключён, потому что у модели task `token_classify`). + +```bash +# один текст, sparse +curl -s localhost:8083/pooling -H 'Content-Type: application/json' -d '{ + "model": "BAAI/bge-m3", + "data": {"text": "Конечные вычислительные ресурсы растут", "threshold": 0.05} +}' +``` +```json +{ + "request_id": "pooling-89315ce71434b2cd", + "created_at": 1790578068, + "data": [{ + "index": 0, + "mode": "sparse", + "length": 10, + "tokens": [ + {"token": "Кон", "id": 12386, "weight": 0.170654}, + {"token": "ресурсы", "id": 183276, "weight": 0.222046} + ], + "sparse": {"12386": 0.170654, "183276": 0.222046}, + "sparse_str": "12386:0.170654 103:0.171021 77892:0.085632 ..." + }] +} +``` + +```bash +# батч +curl -s localhost:8083/pooling -H 'Content-Type: application/json' -d '{ + "model": "BAAI/bge-m3", + "data": {"texts": ["растение", "растения", "дерево"], "threshold": 0.1} +}' + +# dense-вектор (нормированный CLS, 1024 dims) — гибридный поиск +curl -s localhost:8083/pooling -H 'Content-Type: application/json' -d '{ + "model": "BAAI/bge-m3", + "data": {"text": "растение", "mode": "dense"} +}' + +# просто строка +curl -s localhost:8083/pooling -H 'Content-Type: application/json' \ + -d '{"model": "BAAI/bge-m3", "data": "короткий текст"}' +``` + +Поля `data`: + +| Поле | Тип | По умолчанию | Смысл | +|-------------|----------------------|--------------|---------------------------------------------------| +| `text` | `str` | — | один текст | +| `texts` | `list[str]` | — | батч (в ответе `data` — массив, `index` = порядок) | +| `mode` | `sparse` \| `dense` | `sparse` | `sparse` → `token_classify`, `dense` → `embed` | +| `threshold` | `float` | `0.0` | веса `<= threshold` выбрасываются | + +## Локальный запуск + +```bash +docker compose up -d +docker compose logs -f +curl -s localhost:8083/health +``` + +Тот же стек вручную: + +```bash +docker run -d --name vllm-bge-sparse --gpus all --ipc host -p 8083:8000 \ + -v /root/.cache/huggingface:/root/.cache/huggingface \ + -v "$PWD/plugin:/opt/plugin:ro" \ + -v "$PWD/entrypoint.sh:/opt/entrypoint.sh:ro" \ + --entrypoint /bin/bash vllm/vllm-openai:latest /opt/entrypoint.sh \ + python3 -m vllm.entrypoints.openai.api_server \ + --model BAAI/bge-m3 \ + --hf-overrides '{"architectures": ["BgeM3EmbeddingModel"], "head_dtype": "float16"}' \ + --pooler-config.task token_classify \ + --io-processor-plugin bge_m3_sparse_plugin \ + --max-model-len 8192 --port 8000 --gpu-memory-utilization 0.15 +``` + +## Как это устроено + +``` +plugin/pyproject.toml # entry point vllm.io_processor_plugins + # bge_m3_sparse_plugin = bge_m3_sparse:register +plugin/bge_m3_sparse/__init__.py # register() -> qualname класса IOProcessor +plugin/bge_m3_sparse/io_processor.py # parse_data / pre_process / merge_pooling_params / post_process +entrypoint.sh # pip install ./plugin -> exec vllm +docker-compose.yml # стек для Portainer +``` + +Важно: vLLM находит IO processor только через **entry point** установленного +python-пакета, поэтому просто прокинуть папку в `PYTHONPATH` нельзя — нужен +`pip install`. `entrypoint.sh` ставит пакет из read-only монтирования, копируя +исходники во временную папку. + +Плагин протестирован на `vllm/vllm-openai:latest` (vLLM 0.30.0, RTX 5070 8 ГБ, +`--gpu-memory-utilization 0.4`). На 8 ГБ с `0.15` может не хватить памяти под +модель — тогда поднимите `GPU_MEMORY_UTILIZATION` до `0.3`-`0.4`. + +Проверено: одиночный запрос, батч, `mode: dense`, параллельные запросы с разными +режимами, ошибки валидации (`text`/`texts`, `mode`), совпадение весов с +FlagEmbedding-эталоном. + +## Обновление + +Плагин ставится при каждом старте контейнера, поэтому достаточно сделать +**Update the stack** в Portainer после `git pull` — образ пересобирать не нужно. + +## Диагностика + +| Сообщение | Причина | +|------------------------------------------------------------------|------------------------------------------------------------------| +| `No IOProcessor plugins installed but one is required (...)` | плагин не установился: смотрите первые строки логов контейнера | +| `The model requires the 'bge_m3_sparse_plugin' ... plugins: []` | имя entry point в `plugin/pyproject.toml` отличается от указанного | +| `module 'bge_m3_sparse' has no attribute 'io_processor.X'` | `register()` должен возвращать путь через точку, а не через `:` | +| `architectures ['BgeM3EmbeddingModel'] are not supported` | образ старее, чем версия vLLM с этой архитектурой | +| `The model does not support Embeddings API` | так и задумано, dense-вектор доступен через `/pooling` c `mode` | +| OOM при старте | увеличьте `GPU_MEMORY_UTILIZATION` | + +В логах при старте должна быть строка +`[bge-m3-sparse] io processor plugins: ['bge_m3_sparse_plugin -> bge_m3_sparse:register']`, +а в логах vLLM — `Available plugins for group vllm.io_processor_plugins`. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..7c58b11 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,44 @@ +services: + vllm-bge-sparse: + image: ${VLLM_IMAGE:-vllm/vllm-openai:latest} + container_name: vllm-bge-sparse-backend + restart: unless-stopped + entrypoint: + - /bin/bash + - /opt/entrypoint.sh + command: + - python3 + - -m + - vllm.entrypoints.openai.api_server + - --model + - ${MODEL:-BAAI/bge-m3} + - --hf-overrides + - '{"architectures": ["BgeM3EmbeddingModel"], "head_dtype": "float16"}' + - --pooler-config.task + - token_classify + - --io-processor-plugin + - bge_m3_sparse_plugin + - --max-model-len + - ${MAX_MODEL_LEN:-8192} + - --port + - "8000" + - --gpu-memory-utilization + - ${GPU_MEMORY_UTILIZATION:-0.15} + ports: + - "${HOST_PORT:-8083}:8000" + ipc: host + volumes: + - ${HF_CACHE:-/root/.cache/huggingface}:/root/.cache/huggingface + - ./plugin:/opt/plugin:ro + - ./entrypoint.sh:/opt/entrypoint.sh:ro + environment: + - HF_HUB_ENABLE_HF_TRANSFER=0 + - BGE_M3_SPARSE_MODE=${BGE_M3_SPARSE_MODE:-sparse} + - BGE_M3_SPARSE_THRESHOLD=${BGE_M3_SPARSE_THRESHOLD:-0.0} + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..fb0e2c7 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Installs the BGE-M3 sparse IO processor plugin from /opt/plugin (or $PLUGIN_SRC) +# and then hands control over to the vLLM API server. +# +# The plugin lives in a python distribution, because vLLM discovers IO +# processors through entry points (group "vllm.io_processor_plugins"), so a +# plain PYTHONPATH mount is not enough. +set -euo pipefail + +PLUGIN_SRC="${PLUGIN_SRC:-/opt/plugin}" +PLUGIN_NAME="bge_m3_sparse_plugin" + +if [ -d "$PLUGIN_SRC" ]; then + # pip needs a writable copy to build the wheel, so the git mount stays read-only + rm -rf /tmp/bge-m3-sparse-plugin + cp -r "$PLUGIN_SRC" /tmp/bge-m3-sparse-plugin + python3 -m pip install \ + --no-deps \ + --no-build-isolation \ + --no-cache-dir \ + --disable-pip-version-check \ + --quiet \ + /tmp/bge-m3-sparse-plugin + python3 - <<'PY' +from importlib.metadata import entry_points + +found = [f"{ep.name} -> {ep.value}" for ep in entry_points(group="vllm.io_processor_plugins")] +print(f"[bge-m3-sparse] io processor plugins: {found}", flush=True) +PY +fi + +exec "$@" diff --git a/plugin/bge_m3_sparse/__init__.py b/plugin/bge_m3_sparse/__init__.py new file mode 100644 index 0000000..9cbdc98 --- /dev/null +++ b/plugin/bge_m3_sparse/__init__.py @@ -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" diff --git a/plugin/bge_m3_sparse/io_processor.py b/plugin/bge_m3_sparse/io_processor.py new file mode 100644 index 0000000..286eb10 --- /dev/null +++ b/plugin/bge_m3_sparse/io_processor.py @@ -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)] diff --git a/plugin/pyproject.toml b/plugin/pyproject.toml new file mode 100644 index 0000000..bf6f88c --- /dev/null +++ b/plugin/pyproject.toml @@ -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"]