#!/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}") 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}") for bad in ({"foo": 1}, {"text": "x", "mode": "lexical"}, {"texts": []}, 42): 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("ВСЕ ПРОВЕРКИ ПРОЙДЕНЫ")