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:
opencode committed 2026-09-28 13:54:20 +07:00
commit 1c533f98f0
8 files changed
+562

No files matched your search

+168
View File
@@ -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`.