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.
This commit is contained in:
opencode committed 2026-10-07 09:15:41 +07:00
1 parent c2b71ba08c
commit 51fe7873c5
5 files changed
+727 -67

No files matched your search

+256 -34
View File
@@ -1,8 +1,9 @@
# CPU-вариант стека: тот же плагин и тот же API, но образ vllm/vllm-openai-cpu
# и без резервирования GPU. Нужен на серверах без NVIDIA GPU.
#
# ВНИМАНИЕ: блок command ниже должен быть идентичен блоку в docker-compose.yml
# (там heredoc-ами создаётся плагин). Меняете плагин — синхронизируйте оба файла.
# ФАЙЛ СГЕНЕРИРОВАН: docker-compose.cpu.yml = заголовок ниже + блок command
# из docker-compose.yml (см. https://github.com/.../sync_cpu_compose.py).
# Правьте плагин в docker-compose.yml, потом запустите python3 sync_cpu_compose.py.
#
# fp16 на CPU нестабилен, поэтому head_dtype=float32 и --dtype bfloat16.
@@ -86,6 +87,17 @@ services:
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"))
@@ -93,15 +105,35 @@ services:
class _Options:
__slots__ = ("mode", "threshold")
"""Per request settings, kept between pre_process and post_process."""
def __init__(self, mode: str, threshold: float) -> None:
__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 vectors over POST /pooling."""
"""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)
@@ -109,14 +141,17 @@ services:
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 {"texts": [data], "mode": MODE_SPARSE, "threshold": DEFAULT_THRESHOLD}
return self._payload([data], MODE_SPARSE, DEFAULT_THRESHOLD, {}, [])
if not isinstance(data, dict):
raise TypeError(
@@ -128,7 +163,25 @@ services:
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"]
@@ -140,7 +193,34 @@ services:
else:
raise ValueError("`data` must contain `text` or `texts`")
return {"texts": payload, "mode": mode, "threshold": threshold}
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,
@@ -148,11 +228,83 @@ services:
request_id: str | None = None,
**kwargs: Any,
) -> list[str]:
options = _Options(prompt["mode"], float(prompt["threshold"]))
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 list(prompt["texts"])
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
@@ -168,6 +320,7 @@ services:
task=task,
)
# ----------------------------------------------------------------- output
def post_process(
self,
model_output: Sequence[PoolingRequestOutput],
@@ -175,34 +328,34 @@ services:
**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
outputs = list(model_output)
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))
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 _build_sparse(
def _merge_group(
self,
index: int,
token_ids: list[int],
weights: list[float],
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):
@@ -211,7 +364,11 @@ services:
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),
@@ -224,13 +381,35 @@ services:
"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(token_id): round(weight, 6) for token_id, weight in best.items()
},
"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:]
@@ -254,7 +433,14 @@ services:
f"BGE_M3_SPARSE_MODE must be one of {SUPPORTED_MODES}, "
f"got {DEFAULT_MODE!r}"
)
return _Options(DEFAULT_MODE, DEFAULT_THRESHOLD)
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)
@@ -280,6 +466,42 @@ services:
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