File size: 3,055 Bytes
6534c46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
"""Benchmark image requests through the llama-server chat endpoint."""

import argparse
import base64
import json
import mimetypes
import statistics
import time
import urllib.request
from pathlib import Path


def post(port: int, image: Path, prompt: str, max_tokens: int) -> dict:
    mime = mimetypes.guess_type(image.name)[0] or "image/png"
    uri = f"data:{mime};base64," + base64.b64encode(image.read_bytes()).decode()
    body = {
        "model": "minicpm-ocr",
        "messages": [{"role": "user", "content": [
            {"type": "image_url", "image_url": {"url": uri}},
            {"type": "text", "text": prompt},
        ]}],
        "max_tokens": max_tokens,
        "temperature": 0,
        "top_k": 1,
        "seed": 1,
        "cache_prompt": False,
        "chat_template_kwargs": {"enable_thinking": False},
    }
    req = urllib.request.Request(
        f"http://127.0.0.1:{port}/v1/chat/completions",
        json.dumps(body).encode(),
        {"Content-Type": "application/json"},
    )
    start = time.time()
    with urllib.request.urlopen(req, timeout=900) as resp:
        result = json.load(resp)
    result["_wall_ms"] = (time.time() - start) * 1000
    return result


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, required=True)
    ap.add_argument("--images", type=Path, required=True)
    ap.add_argument("--out", type=Path)
    ap.add_argument("--reps", type=int, default=2)
    ap.add_argument("--max-tokens", type=int, default=128)
    ap.add_argument("--warmup", action="store_true")
    args = ap.parse_args()
    images = sorted(args.images.glob("*.png"))
    if not images:
        raise SystemExit(f"no PNG images under {args.images}")
    rows = []
    if args.warmup:
        post(args.port, images[0], "Text Recognition:", 8)
        return
    if args.out is None:
        raise SystemExit("--out is required unless --warmup is used")
    for image in images:
        for _ in range(args.reps):
            result = post(args.port, image, "Text Recognition:", args.max_tokens)
            timing = result.get("timings", {})
            rows.append({
                "image": image.name,
                "wall_ms": result["_wall_ms"],
                "prompt_n": timing.get("prompt_n"),
                "prompt_ms": timing.get("prompt_ms"),
                "predicted_n": timing.get("predicted_n"),
                "predicted_ms": timing.get("predicted_ms"),
                "predicted_per_second": timing.get("predicted_per_second"),
            })
            print("IMAGE_ROW " + json.dumps(rows[-1]), flush=True)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(rows, indent=2) + "\n")
    print("IMAGE_MEDIAN wall_ms=%.1f prompt_ms=%.1f decode_tok_s=%.2f" % (
        statistics.median(r["wall_ms"] for r in rows),
        statistics.median(r["prompt_ms"] for r in rows),
        statistics.median(r["predicted_per_second"] for r in rows),
    ))


if __name__ == "__main__":
    main()