The failing deploy on a fresh host is almost always the vLLM image pull (~31 GB unpacked) hitting Portainer's stack deploy timeout. Documented pre-pulling on the target host plus docker save|load alternative, and replaced the :latest default with the exact tag this stack was tested on.
317 lines
13 KiB
YAML
317 lines
13 KiB
YAML
services:
|
|
vllm-bge-sparse:
|
|
image: ${VLLM_IMAGE:-vllm/vllm-openai:v0.30.0}
|
|
container_name: ${CONTAINER_NAME:-vllm-bge-sparse-backend}
|
|
restart: unless-stopped
|
|
ipc: host
|
|
ports:
|
|
- "${HOST_PORT:-8083}:8000"
|
|
volumes:
|
|
- ${HF_CACHE:-/root/.cache/huggingface}:/root/.cache/huggingface
|
|
environment:
|
|
MODEL: ${MODEL:-BAAI/bge-m3}
|
|
MAX_MODEL_LEN: ${MAX_MODEL_LEN:-8192}
|
|
GPU_MEMORY_UTILIZATION: ${GPU_MEMORY_UTILIZATION:-0.15}
|
|
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]
|
|
# not a login shell on purpose: /root/.profile in the vllm image dumps the
|
|
# whole environment before running anything
|
|
entrypoint: ["/bin/bash", "-c"]
|
|
# Self-contained on purpose: this stack must work when the YAML is pasted
|
|
# into the Portainer web editor, where nothing but the compose file exists
|
|
# on the host. The plugin is written to a temp dir and pip-installed, because
|
|
# vLLM only discovers IO processors through entry points of an installed
|
|
# python distribution (group vllm.io_processor_plugins).
|
|
command:
|
|
- |
|
|
set -euo pipefail
|
|
PLUGIN_DIR=/tmp/bge-m3-sparse-plugin
|
|
rm -rf "$$PLUGIN_DIR"
|
|
mkdir -p "$$PLUGIN_DIR/bge_m3_sparse"
|
|
|
|
cat > "$$PLUGIN_DIR/pyproject.toml" <<'TOML'
|
|
[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"
|
|
requires-python = ">=3.10"
|
|
dependencies = []
|
|
|
|
[project.entry-points."vllm.io_processor_plugins"]
|
|
bge_m3_sparse_plugin = "bge_m3_sparse:register"
|
|
|
|
[tool.setuptools]
|
|
packages = ["bge_m3_sparse"]
|
|
TOML
|
|
|
|
cat > "$$PLUGIN_DIR/bge_m3_sparse/__init__.py" <<'PY'
|
|
def register() -> str:
|
|
return "bge_m3_sparse.io_processor.BgeM3SparseIOProcessor"
|
|
PY
|
|
|
|
cat > "$$PLUGIN_DIR/bge_m3_sparse/io_processor.py" <<'PY'
|
|
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 = 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):
|
|
"""Serves BGE-M3 learned sparse vectors over POST /pooling."""
|
|
|
|
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] = {}
|
|
|
|
def parse_data(self, data: object) -> dict[str, Any]:
|
|
if isinstance(data, str):
|
|
return {"texts": [data], "mode": MODE_SPARSE, "threshold": 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 {"texts": payload, "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,
|
|
)
|
|
|
|
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}, "
|
|
f"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:
|
|
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:
|
|
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)]
|
|
PY
|
|
|
|
python3 -m pip install --no-deps --no-build-isolation --no-cache-dir \
|
|
--disable-pip-version-check --quiet "$$PLUGIN_DIR"
|
|
|
|
python3 -c "from importlib.metadata import entry_points as e; print('[bge-m3-sparse] io processor plugins:', [f'{x.name} -> {x.value}' for x in e(group='vllm.io_processor_plugins')], flush=True)"
|
|
|
|
exec 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}"
|