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

+42 -1
View File
@@ -92,6 +92,8 @@ counts = [
]
check("threshold filters weights", counts[0] > counts[1] >= counts[2], f"nnz={counts}")
doc = "Спутниковая связь обеспечивает передачу данных между удалёнными объектами. " * 70
query = sparse("машинное обучение")
near = sparse("машинное обучение и нейросети")
far = sparse("рецепт приготовления борща")
@@ -99,7 +101,46 @@ near_dot = sum(query[t] * near[t] for t in set(query) & set(near))
far_dot = sum(query[t] * far[t] for t in set(query) & set(far))
check("similar texts overlap", near_dot > 0 and far_dot == 0, f"near={near_dot:.4f} far={far_dot:.4f}")
for bad in ({"foo": 1}, {"text": "x", "mode": "lexical"}, {"texts": []}, 42):
# long document: auto chunking, explicit chunking, merge modes, batch grouping
long_unit = "Спутниковая связь обеспечивает передачу данных между удалёнными объектами. "
long_text = long_unit * 1400 # ~100k символов, заведомо больше max_model_len
auto = pooling({"text": long_text, "threshold": 0.1})["data"][0]
check("long text is chunked", auto["chunks"] > 1 and auto["length"] > 0, f"chunks={auto['chunks']} nnz={auto['length']}")
explicit = pooling(
{"text": long_text, "threshold": 0.1, "chunk_tokens": 1024, "chunk_overlap": 128}
)["data"][0]
check(
"explicit chunk_tokens",
explicit["chunks"] > auto["chunks"] and explicit["chunk_tokens"] == 1024,
f"chunks={explicit['chunks']}",
)
for merge in ("max", "sum", "mean"):
merged = pooling(
{"text": doc, "threshold": 0.1, "chunk_tokens": 400, "chunk_overlap": 64, "merge": merge}
)["data"][0]
check(f"merge={merge}", merged["merge"] == merge and merged["chunks"] > 1, f"nnz={merged['length']}")
chunked_dense = pooling({"text": long_text, "mode": "dense"})["data"][0]
chunked_norm = sum(x * x for x in chunked_dense["embedding"]) ** 0.5
check(
"dense chunking",
chunked_dense["chunks"] > 1 and abs(chunked_norm - 1) < 0.01,
f"chunks={chunked_dense['chunks']} norm={chunked_norm:.4f}",
)
mixed = pooling({"texts": [long_text, "короткий текст"], "threshold": 0.1,
"chunk_tokens": 2048, "chunk_overlap": 128})["data"]
check(
"chunk grouping in batch",
mixed[0]["chunks"] > 1 and mixed[1]["chunks"] == 1,
f"chunks={[m['chunks'] for m in mixed]}",
)
for bad in ({"foo": 1}, {"text": "x", "mode": "lexical"}, {"texts": []}, 42,
{"text": "x", "merge": "median"}, {"text": "x", "chunk_tokens": 4},
{"text": "x", "chunk_overlap": -1}):
try:
pooling(bad)
check(f"rejects {str(bad)[:20]}", False, "expected 400")