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.
194 lines
8.0 KiB
Python
194 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Smoke test for the vllm-bge-sparse stack.
|
|
|
|
python3 smoke_test.py # http://localhost:8083
|
|
python3 smoke_test.py http://10.0.0.5:8083
|
|
python3 smoke_test.py --reference
|
|
|
|
`--reference` additionally compares the served weights with the FlagEmbedding
|
|
formula `relu(sparse_linear(h))` computed locally; it needs torch, transformers
|
|
and the BAAI/bge-m3 snapshot, so run it inside the container (note: the port
|
|
inside the container is 8000, not the published one):
|
|
|
|
docker cp smoke_test.py vllm-bge-sparse-backend:/tmp/
|
|
docker exec -e HF_HUB_OFFLINE=1 vllm-bge-sparse-backend \\
|
|
python3 /tmp/smoke_test.py http://localhost:8000 --reference
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
ARGS = [a for a in sys.argv[1:] if a != "--reference"]
|
|
BASE = (ARGS[0] if ARGS else "http://localhost:8083").rstrip("/")
|
|
REFERENCE = "--reference" in sys.argv[1:]
|
|
MODEL = "BAAI/bge-m3"
|
|
TOLERANCE = 5e-3
|
|
|
|
failures = []
|
|
|
|
|
|
def check(name, ok, detail=""):
|
|
print(f" {'OK ' if ok else 'FAIL'} {name}{(' ' + detail) if detail else ''}")
|
|
if not ok:
|
|
failures.append(name)
|
|
|
|
|
|
def pooling(data):
|
|
body = json.dumps({"model": MODEL, "data": data}).encode()
|
|
request = urllib.request.Request(
|
|
f"{BASE}/pooling", body, {"Content-Type": "application/json"}
|
|
)
|
|
with urllib.request.urlopen(request, timeout=120) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def sparse(text, threshold=0.05):
|
|
return pooling({"text": text, "threshold": threshold})["data"][0]["sparse"]
|
|
|
|
|
|
print(f"=== {BASE} ===")
|
|
with urllib.request.urlopen(f"{BASE}/health", timeout=30) as response:
|
|
check("health", response.status == 200)
|
|
|
|
item = pooling({"text": "Конечные вычислительные ресурсы растут", "threshold": 0.05})["data"][0]
|
|
check(
|
|
"sparse vector",
|
|
item["mode"] == "sparse" and item["length"] > 0 and bool(item["sparse_str"]),
|
|
f"nnz={item['length']}, first={item['sparse_str'].split()[0] if item['sparse_str'] else '-'}",
|
|
)
|
|
check(
|
|
"tokens decoded",
|
|
all(isinstance(t["token"], str) and t["token"] for t in item["tokens"]),
|
|
" ".join(t["token"] for t in item["tokens"][:5]),
|
|
)
|
|
check("sparse matches tokens", {int(k) for k in item["sparse"]} == {t["id"] for t in item["tokens"]})
|
|
|
|
texts = ["растение", "дерево", "автомобиль", "век вычислительных ресурсов"]
|
|
batch = pooling({"texts": texts, "threshold": 0.1})["data"]
|
|
check(
|
|
"batch keeps order",
|
|
len(batch) == len(texts) and [b["index"] for b in batch] == list(range(len(texts))),
|
|
f"{len(batch)} items",
|
|
)
|
|
|
|
dense = pooling({"text": "растение", "mode": "dense"})["data"][0]
|
|
norm = sum(x * x for x in dense["embedding"]) ** 0.5
|
|
check(
|
|
"dense vector",
|
|
dense["dimension"] == len(dense["embedding"]) == 1024 and abs(norm - 1) < 0.01,
|
|
f"dim={dense['dimension']} norm={norm:.4f}",
|
|
)
|
|
|
|
check("data as plain string", bool(pooling("короткий текст")["data"][0]["sparse"]))
|
|
|
|
runs = [sparse("проверка детерминизма") for _ in range(3)]
|
|
check("deterministic", runs[0] == runs[1] == runs[2])
|
|
|
|
counts = [
|
|
len(sparse("информационные технологии и искусственный интеллект", threshold))
|
|
for threshold in (0.0, 0.1, 0.25, 0.3)
|
|
]
|
|
check("threshold filters weights", counts[0] > counts[1] >= counts[2], f"nnz={counts}")
|
|
|
|
doc = "Спутниковая связь обеспечивает передачу данных между удалёнными объектами. " * 70
|
|
|
|
query = sparse("машинное обучение")
|
|
near = sparse("машинное обучение и нейросети")
|
|
far = sparse("рецепт приготовления борща")
|
|
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}")
|
|
|
|
# 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")
|
|
except urllib.error.HTTPError as e:
|
|
message = json.loads(e.read())["error"]["message"]
|
|
check(f"rejects {str(bad)[:20]}", e.code == 400, message)
|
|
|
|
if REFERENCE:
|
|
print("=== reference check: FlagEmbedding formula, fp32 ===")
|
|
import torch
|
|
from huggingface_hub import hf_hub_download
|
|
from transformers import AutoModel, AutoTokenizer
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
|
encoder = AutoModel.from_pretrained(MODEL, torch_dtype=torch.float32).eval()
|
|
state = torch.load(hf_hub_download(MODEL, "sparse_linear.pt"), map_location="cpu")
|
|
head = torch.nn.Linear(encoder.config.hidden_size, 1)
|
|
head.load_state_dict(
|
|
{"weight": state["weight"].float(), "bias": state["bias"].float()}
|
|
)
|
|
|
|
for text in (
|
|
"Конечные вычислительные ресурсы растут",
|
|
"век вычислительных ресурсов",
|
|
"машинное обучение и нейросети",
|
|
):
|
|
encoded = tokenizer(text, return_tensors="pt")
|
|
with torch.no_grad():
|
|
scores = torch.relu(head(encoder(**encoded).last_hidden_state))[0, :, 0]
|
|
# BOSEOSFilter on the engine side drops the leading BOS and trailing EOS
|
|
token_ids = encoded["input_ids"][0].tolist()[1:-1]
|
|
expected = {
|
|
str(token): round(float(weight), 6)
|
|
for token, weight in zip(token_ids, scores[1:-1].tolist())
|
|
if weight > 0
|
|
}
|
|
served = sparse(text, threshold=0.0)
|
|
if set(expected) != set(served):
|
|
check(f"reference: {text[:28]}", False, f"token set differs by {set(expected) ^ set(served)}")
|
|
else:
|
|
worst = max(abs(served[token] - expected[token]) for token in expected)
|
|
check(f"reference: {text[:28]}", worst < TOLERANCE, f"max|delta|={worst:.6f} over {len(expected)} tokens")
|
|
else:
|
|
print("=== reference check skipped (rerun with --reference) ===")
|
|
|
|
print()
|
|
if failures:
|
|
print(f"ПРОВАЛЕНО ({len(failures)}): " + ", ".join(failures))
|
|
sys.exit(1)
|
|
print("ВСЕ ПРОВЕРКИ ПРОЙДЕНЫ")
|