Files
vllm-sparce/docker-compose.yml
opencode 51fe7873c5 Plugin: chunk long documents and return one merged vector
Previously a document longer than --max-model-len got HTTP 400. Now pre_process
splits text into overlapping token windows (offsets from the fast tokenizer,
recursively halved if a piece still does not fit) and post_process merges the
per chunk results, so the client always receives one vector per input text.

- new request fields: chunk_tokens (default: only chunk what does not fit,
  window = max_model_len - 8), chunk_overlap (128), merge (max/sum/mean,
  sparse defaults to max, dense to mean + renormalise)
- response gains chunks, merge, chunk_tokens, chunk_overlap
- dense chunked output stays L2 normalised (norm 1.0000)
- regression: texts that fit are still processed as a single chunk with the
  same weights as before (verified against the FlagEmbedding reference)

Measured on the GPU stand: 100k characters -> 3 chunks in 0.8 s, 0.6 s with
chunk_tokens=1024 (48 chunks); chunking a 1.1k token text into 400-token
windows keeps 92% of the whole-document tokens (dot 0.481).

Adds sync_cpu_compose.py: docker-compose.cpu.yml is now generated from
docker-compose.yml, so the two embedded copies of the plugin cannot drift
(--check mode for CI). smoke_test.py covers chunking, merge modes and grouping.
2026-10-07 09:15:41 +07:00

538 lines
22 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"}
MERGE_MAX = "max"
MERGE_SUM = "sum"
MERGE_MEAN = "mean"
SUPPORTED_MERGES = (MERGE_MAX, MERGE_SUM, MERGE_MEAN)
DEFAULT_MERGE = {MODE_SPARSE: MERGE_MAX, MODE_DENSE: MERGE_MEAN}
# BOS + EOS are added by the tokenizer on top of the chunk window
HEADROOM_TOKENS = 8
DEFAULT_CHUNK_OVERLAP = 128
MAX_CHUNK_DEPTH = 2
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:
"""Per request settings, kept between pre_process and post_process."""
__slots__ = ("mode", "threshold", "merge", "chunk_tokens", "chunk_overlap", "chunk_counts")
def __init__(
self,
mode: str,
threshold: float,
merge: str,
chunk_tokens: int,
chunk_overlap: int,
chunk_counts: list[int],
) -> None:
self.mode = mode
self.threshold = threshold
self.merge = merge
self.chunk_tokens = chunk_tokens
self.chunk_overlap = chunk_overlap
self.chunk_counts = chunk_counts
class BgeM3SparseIOProcessor(IOProcessor):
"""Serves BGE-M3 learned sparse (and dense) vectors over POST /pooling.
Long documents are split into overlapping token windows inside
``pre_process`` and the per chunk results are merged back in
``post_process``, so the client always gets exactly one vector per input
text, even when the text does not fit into ``--max-model-len``.
"""
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.max_model_len = int(vllm_config.model_config.max_model_len)
self._tokenizer = renderer.get_tokenizer()
self._supports_offsets = bool(getattr(self._tokenizer, "is_fast", False))
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))
merge = str(data.get("merge", DEFAULT_MERGE[mode])).lower()
if merge not in SUPPORTED_MERGES:
raise ValueError(
f"unsupported merge {merge!r}, expected one of {SUPPORTED_MERGES}"
)
chunk_tokens = data.get("chunk_tokens")
if chunk_tokens is not None:
chunk_tokens = int(chunk_tokens)
if chunk_tokens <= HEADROOM_TOKENS:
raise ValueError(
f"`chunk_tokens` must be greater than {HEADROOM_TOKENS}"
)
chunk_overlap = int(data.get("chunk_overlap", DEFAULT_CHUNK_OVERLAP))
if chunk_overlap < 0:
raise ValueError("`chunk_overlap` must not be negative")
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,
{"merge": merge, "chunk_tokens": chunk_tokens, "chunk_overlap": chunk_overlap},
[],
)
@staticmethod
def _payload(
texts: list[str],
mode: str,
threshold: float,
extra: dict[str, Any],
chunk_counts: list[int],
) -> dict[str, Any]:
payload = {
"texts": texts,
"mode": mode,
"threshold": threshold,
"merge": extra.get("merge", DEFAULT_MERGE[mode]),
"chunk_overlap": extra.get("chunk_overlap", DEFAULT_CHUNK_OVERLAP),
"chunk_counts": chunk_counts,
}
chunk_tokens = extra.get("chunk_tokens")
if chunk_tokens is not None:
payload["chunk_tokens"] = int(chunk_tokens)
return payload
def pre_process(
self,
prompt: dict[str, Any],
request_id: str | None = None,
**kwargs: Any,
) -> list[str]:
limit = prompt.get("chunk_tokens")
if limit is None:
limit = self.max_model_len - HEADROOM_TOKENS
limit = min(int(limit), self.max_model_len - HEADROOM_TOKENS)
overlap = min(int(prompt["chunk_overlap"]), max(0, limit - 1))
chunked: list[str] = []
chunk_counts: list[int] = []
for text in prompt["texts"]:
pieces = self._split(text, limit, overlap, MAX_CHUNK_DEPTH)
chunk_counts.append(len(pieces))
chunked.extend(pieces)
options = _Options(
prompt["mode"],
float(prompt["threshold"]),
prompt["merge"],
limit,
overlap,
chunk_counts,
)
_CURRENT.set(options)
if request_id is not None:
self._options[request_id] = options
return chunked
def _split(self, text: str, chunk_tokens: int, overlap: int, depth: int) -> list[str]:
"""Split text into <= chunk_tokens windows, keeping `overlap` tokens."""
if not text.strip():
return [text]
if not self._supports_offsets:
if self._count_tokens(text) > chunk_tokens:
logger.warning(
"tokenizer without offsets: cannot chunk, the text may be truncated"
)
return [text]
if self._count_tokens(text) <= chunk_tokens:
return [text]
offsets = self._offsets(text)
step = max(1, chunk_tokens - overlap)
pieces: list[str] = []
start = 0
while start < len(offsets):
end = min(start + chunk_tokens, len(offsets))
piece = text[offsets[start][0] : offsets[end - 1][1]].strip()
if piece:
pieces.append(piece)
if end >= len(offsets):
break
start += step
if not pieces:
return [text]
if depth <= 0:
logger.warning("chunking depth limit reached, text may be rejected")
return pieces
safe: list[str] = []
for piece in pieces:
if self._count_tokens(piece) <= chunk_tokens:
safe.append(piece)
else:
safe.extend(
self._split(piece, max(1, chunk_tokens // 2), overlap // 2, depth - 1)
)
return safe
def _count_tokens(self, text: str) -> int:
return len(self._tokenizer(text, add_special_tokens=False)["input_ids"])
def _offsets(self, text: str) -> list[tuple[int, int]]:
return list(
self._tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)[
"offset_mapping"
]
)
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()
outputs = list(model_output)
results: list[dict[str, Any]] = []
cursor = 0
for index, count in enumerate(options.chunk_counts):
group = outputs[cursor : cursor + count]
cursor += count
results.append(self._merge_group(index, group, options))
return results
def _merge_group(
self,
index: int,
group: Sequence[PoolingRequestOutput],
options: _Options,
) -> dict[str, Any]:
if options.mode == MODE_DENSE:
return self._dense_result(index, group, options)
chunks = [self._chunk_weights(res, options) for res in group]
best = _merge_weight_maps(chunks, options.merge)
return self._sparse_result(index, best, options, len(group))
def _chunk_weights(
self, res: PoolingRequestOutput, options: _Options
) -> dict[int, float]:
weights = _to_floats(res.outputs.data)
token_ids = self._align_token_ids(list(res.prompt_token_ids or []), len(weights))
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
return best
def _sparse_result(
self, index: int, best: dict[int, float], options: _Options, chunks: int
) -> dict[str, Any]:
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),
"chunks": chunks,
"merge": options.merge,
"chunk_tokens": options.chunk_tokens,
"chunk_overlap": options.chunk_overlap,
"tokens": tokens,
"sparse": {str(t): round(w, 6) for t, w in best.items()},
"sparse_str": " ".join(f"{t}:{w:.6f}" for t, w in best.items()),
}
def _dense_result(
self, index: int, group: Sequence[PoolingRequestOutput], options: _Options
) -> dict[str, Any]:
vectors = [_to_floats(res.outputs.data) for res in group]
if len(vectors) == 1:
embedding = vectors[0]
else:
embedding = _merge_vectors(vectors, options.merge)
norm = sum(x * x for x in embedding) ** 0.5
if norm > 0:
embedding = [x / norm for x in embedding]
return {
"index": index,
"mode": MODE_DENSE,
"dimension": len(embedding),
"chunks": len(vectors),
"merge": options.merge,
"embedding": embedding,
}
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,
DEFAULT_MERGE[DEFAULT_MODE],
self.max_model_len - HEADROOM_TOKENS,
DEFAULT_CHUNK_OVERLAP,
[],
)
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 _merge_weight_maps(chunks: list[dict[int, float]], merge: str) -> dict[int, float]:
if len(chunks) == 1:
return chunks[0]
if merge == MERGE_SUM:
merged: dict[int, float] = {}
for best in chunks:
for token_id, weight in best.items():
merged[token_id] = merged.get(token_id, 0.0) + weight
return merged
if merge == MERGE_MEAN:
totals: dict[int, float] = {}
counts: dict[int, int] = {}
for best in chunks:
for token_id, weight in best.items():
totals[token_id] = totals.get(token_id, 0.0) + weight
counts[token_id] = counts.get(token_id, 0) + 1
return {t: totals[t] / len(chunks) for t in totals}
merged = {}
for best in chunks:
for token_id, weight in best.items():
if weight > merged.get(token_id, 0.0):
merged[token_id] = weight
return merged
def _merge_vectors(vectors: list[list[float]], merge: str) -> list[float]:
if merge == MERGE_MAX:
return [max(values) for values in zip(*vectors)]
if merge == MERGE_SUM:
return [sum(values) for values in zip(*vectors)]
return [sum(values) / len(vectors) for values in zip(*vectors)]
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}"