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:
1 parent
c2b71ba08c
commit
51fe7873c5
5 files changed
+727
-67
No files matched your search
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate docker-compose.cpu.yml from docker-compose.yml.
|
||||
|
||||
Both stacks embed the same plugin sources as heredocs, because Portainer only
|
||||
deploys a single compose file and the web editor has no repo checkout on the
|
||||
host. That duplication is easy to break by hand, so the CPU file is generated:
|
||||
the plugin block is copied verbatim from docker-compose.yml, while the header
|
||||
(CPU image, seccomp/SYS_NICE, no GPU reservation) and the tail (CPU vLLM flags)
|
||||
live here.
|
||||
|
||||
python3 sync_cpu_compose.py # rewrite docker-compose.cpu.yml
|
||||
python3 sync_cpu_compose.py --check # exit 1 if it is out of date
|
||||
"""
|
||||
|
||||
import difflib
|
||||
import sys
|
||||
|
||||
MARKER = " command:\n"
|
||||
|
||||
CPU_HEADER = '''# CPU-вариант стека: тот же плагин и тот же API, но образ vllm/vllm-openai-cpu
|
||||
# и без резервирования GPU. Нужен на серверах без NVIDIA GPU.
|
||||
#
|
||||
# ФАЙЛ СГЕНЕРИРОВАН: 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.
|
||||
|
||||
services:
|
||||
vllm-bge-sparse-cpu:
|
||||
image: ${VLLM_IMAGE_CPU:-vllm/vllm-openai-cpu:v0.30.0-x86_64}
|
||||
container_name: ${CONTAINER_NAME_CPU:-vllm-bge-sparse-cpu-backend}
|
||||
restart: unless-stopped
|
||||
ipc: host
|
||||
# рекомендации vLLM для CPU-бэкенда: снять seccomp-фильтр и дать SYS_NICE
|
||||
security_opt:
|
||||
- seccomp=unconfined
|
||||
cap_add:
|
||||
- SYS_NICE
|
||||
ports:
|
||||
- "${HOST_PORT_CPU:-8084}:8000"
|
||||
volumes:
|
||||
- ${HF_CACHE:-/root/.cache/huggingface}:/root/.cache/huggingface
|
||||
environment:
|
||||
MODEL: ${MODEL:-BAAI/bge-m3}
|
||||
MAX_MODEL_LEN: ${MAX_MODEL_LEN_CPU:-2048}
|
||||
MAX_NUM_BATCHED_TOKENS_CPU: ${MAX_NUM_BATCHED_TOKENS_CPU:-2048}
|
||||
ENFORCE_EAGER: ${ENFORCE_EAGER:-1}
|
||||
BGE_M3_SPARSE_MODE: ${BGE_M3_SPARSE_MODE:-sparse}
|
||||
BGE_M3_SPARSE_THRESHOLD: ${BGE_M3_SPARSE_THRESHOLD:-0.0}
|
||||
VLLM_CPU_KVCACHE_SPACE: ${VLLM_CPU_KVCACHE_SPACE:-8}
|
||||
VLLM_CPU_NUM_OF_RESERVED_CPU: ${VLLM_CPU_NUM_OF_RESERVED_CPU:-0}
|
||||
# not a login shell on purpose: /root/.profile in the vllm image dumps the
|
||||
# whole environment before running anything
|
||||
entrypoint: ["/bin/bash", "-c"]
|
||||
'''
|
||||
|
||||
GPU_ARGS = ''' --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}"'''
|
||||
|
||||
CPU_ARGS = ''' --hf-overrides '{"architectures": ["BgeM3EmbeddingModel"], "head_dtype": "float32"}' \\
|
||||
--pooler-config.task token_classify \\
|
||||
--io-processor-plugin bge_m3_sparse_plugin \\
|
||||
--max-model-len "$${MAX_MODEL_LEN:-2048}" \\
|
||||
--max-num-batched-tokens "$${MAX_NUM_BATCHED_TOKENS_CPU:-2048}" \\
|
||||
$${ENFORCE_EAGER:+--enforce-eager} \\
|
||||
--port 8000 \\
|
||||
--dtype "$${DTYPE_CPU:-bfloat16}"'''
|
||||
|
||||
SOURCE = "docker-compose.yml"
|
||||
TARGET = "docker-compose.cpu.yml"
|
||||
|
||||
|
||||
def build() -> str:
|
||||
gpu = open(SOURCE, encoding="utf-8").read()
|
||||
if MARKER not in gpu:
|
||||
raise SystemExit(f"{SOURCE}: не найден блок command")
|
||||
command = gpu[gpu.index(MARKER) :]
|
||||
|
||||
if GPU_ARGS not in command:
|
||||
raise SystemExit(
|
||||
f"{SOURCE}: не найдены GPU-аргументы vLLM.\n"
|
||||
"Обновите GPU_ARGS в sync_cpu_compose.py под текущий хвост команды."
|
||||
)
|
||||
command = command.replace(GPU_ARGS, CPU_ARGS)
|
||||
return CPU_HEADER + command
|
||||
|
||||
|
||||
def main() -> int:
|
||||
target = build()
|
||||
if "--check" in sys.argv:
|
||||
current = open(TARGET, encoding="utf-8").read()
|
||||
if current != target:
|
||||
print(f"{TARGET} устарел, запустите: python3 sync_cpu_compose.py")
|
||||
sys.stdout.writelines(
|
||||
difflib.unified_diff(
|
||||
current.splitlines(keepends=True),
|
||||
target.splitlines(keepends=True),
|
||||
fromfile=TARGET,
|
||||
tofile=TARGET + " (сгенерированный)",
|
||||
)
|
||||
)
|
||||
return 1
|
||||
print(f"{TARGET} актуален")
|
||||
return 0
|
||||
|
||||
open(TARGET, "w", encoding="utf-8").write(target)
|
||||
print(f"{TARGET} перезаписан")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user