aisop/tools/benchmark_d3_lite.py

97 lines
5.8 KiB
Python

"""Compare a D3 service on the existing real camera controls, using ordinary short questions."""
import argparse
import base64
import hashlib
import io
import json
import math
from pathlib import Path
import statistics
import time
import urllib.request
def post(endpoint, image, question, choices=None, state=""):
field = {"type": "choice" if choices else "noul", "instructions": question}
if choices:
field["criteria"] = choices
payload = {"state": state, "questions": {"q": field}}
if image is not None:
payload["images"] = ["data:image/jpeg;base64," + base64.b64encode(image).decode()]
request = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={"Content-Type": "application/json; charset=utf-8"})
started = time.perf_counter()
with urllib.request.urlopen(request, timeout=120) as response:
content = response.read()
elapsed = round((time.perf_counter() - started) * 1000, 2)
result = json.loads(content)
expected_hashes = [] if image is None else [hashlib.sha256(image).hexdigest()]
assert result["usage"]["image_sha256"] == expected_hashes
answer = result["answers"]["q"]
if "error" in answer:
raise RuntimeError(answer)
actual = answer["choice"] if choices else answer["noul"] > .5
return {"http_ms": elapsed, "actual": actual, "response": result}
def stats(runs):
values = sorted(row["http_ms"] for row in runs)
return {"count": len(runs), "mean_ms": round(statistics.mean(values), 2), "p95_ms": values[math.ceil(.95 * len(values)) - 1], "max_ms": max(values), "under_200ms": sum(value < 200 for value in values), "under_500ms": sum(value < 500 for value in values)}
def main():
from PIL import Image
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--endpoint", default="http://127.0.0.1:8766/v1/systemone")
parser.add_argument("--count", type=int, default=5)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
repo = Path(__file__).resolve().parents[1]
images = repo / "artifacts/imajev-benchmark"
colors = {"黄": "黄色", "绿": "绿色", "有红有蓝": "红色和蓝色都有"}
english_colors = {"yellow": "yellow", "green": "green", "red_and_blue": "both red and blue"}
cases = [
("非空盒_中文", "nonempty_crop-input.jpg", "盒子空了没?", None, False),
("非空盒_英文", "nonempty_crop-input.jpg", "Is the box empty?", None, False),
("空盒_中文", "empty_crop-input.jpg", "盒子空了没?", None, True),
("空盒_英文", "empty_crop-input.jpg", "Is the box empty?", None, True),
("无手_中文", "no_hand-input.jpg", "手里拿着东西吗?", None, False),
("无手_英文", "no_hand-input.jpg", "Is there a hand holding an object?", None, False),
("持物_中文", "hikvision-imajev-holding-20261112-194959-input.jpg", "手里拿着东西吗?", None, True),
("持物_英文", "hikvision-imajev-holding-20261112-194959-input.jpg", "Is there a hand holding an object?", None, True),
("颜色_中文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "手里这东西是黄的、绿的,还是红蓝都有?", colors, "有红有蓝"),
("颜色_英文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "What color is the object held in the hand?", english_colors, "red_and_blue"),
]
health_url = args.endpoint.rsplit("/v1/systemone", 1)[0] + "/health"
with urllib.request.urlopen(health_url, timeout=10) as response:
health = json.load(response)
report = {"model": health["model"], "endpoint": args.endpoint, "health": health, "scope": "Same real camera images as Imajev, maximum edge 512; one question per request; first call per case recorded separately as warmup", "note": "The upstream D3 response has no automatic abstention/unknown field; confidence is not a correctness guarantee", "cases": []}
args.output.parent.mkdir(parents=True, exist_ok=True)
for name, filename, question, choices, expected in cases:
source = images / filename
# Reuse the exact prepared JPEG bytes from the Imajev test, without recompression.
data = source.read_bytes()
with Image.open(io.BytesIO(data)) as image:
size = image.size
row = {"case": name, "input": str(source), "image_size": size, "image_sha256": hashlib.sha256(data).hexdigest(),
"question": question, "choices": choices, "expected": expected, "runs": []}
row["warmup"] = post(args.endpoint, data, question, choices)
assert row["warmup"]["response"]["model"] == report["model"], "Served model changed during benchmark"
report["cases"].append(row)
for _ in range(args.count):
run = post(args.endpoint, data, question, choices)
assert run["response"]["model"] == report["model"], "Served model changed during benchmark"
run["correct"] = run["actual"] == expected
row["runs"].append(run)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
row["summary"] = {**stats(row["runs"]), "correct": sum(run["correct"] for run in row["runs"])}
print(json.dumps({"case": name, "actual": row["runs"][0]["actual"], "answer": row["runs"][0]["response"]["answers"]["q"], **row["summary"]}, ensure_ascii=False), flush=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
all_runs = [run for case in report["cases"] for run in case["runs"]]
report["summary"] = {**stats(all_runs), "correct": sum(run["correct"] for run in all_runs)}
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(report["summary"]), flush=True)
if __name__ == "__main__":
main()