File size: 4,445 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""Measure end-to-end batch-one inference on a fixed CPU or one CUDA GPU."""

import argparse
import json
import platform
from pathlib import Path
import resource
import statistics
import sys
import time

import numpy as np
import torch

from .data import load_calls
from .inference import FactSetExtractor


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("checkpoint", type=Path)
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--device", default="cpu")
    parser.add_argument("--threads", type=int, default=4)
    parser.add_argument("--warmup", type=int, default=3)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--threshold", type=float, default=0.5)
    parser.add_argument("--value-catalog", type=Path)
    parser.add_argument("--ticket-states", action="store_true")
    parser.add_argument("--agreement-dates", action="store_true")
    args = parser.parse_args()
    if args.ticket_states and not args.value_catalog:
        parser.error("--ticket-states requires --value-catalog")
    if args.threads < 1 or args.warmup < 0 or (args.limit is not None and args.limit < 1):
        parser.error("Invalid threads, warmup or limit")
    if args.output.exists():
        raise FileExistsError(args.output)
    torch.set_num_threads(args.threads)
    calls = load_calls(args.input)
    if args.limit:
        calls = calls[:args.limit]
    for call in calls:
        call.pop("facts", None)
    cuda = args.device.startswith("cuda")
    started = time.perf_counter()
    extractor = FactSetExtractor(args.checkpoint, args.device, args.threshold,
                                 args.value_catalog, args.ticket_states,
                                 agreement_dates=args.agreement_dates)
    if cuda:
        torch.cuda.synchronize(args.device)
    load_seconds = time.perf_counter() - started
    for i in range(args.warmup):
        extractor(calls[i % len(calls)])
    if cuda:
        torch.cuda.synchronize(args.device)
        torch.cuda.reset_peak_memory_stats(args.device)
    latencies = []
    for call in calls:
        started = time.perf_counter()
        facts = extractor(call)
        json.dumps({"call_id": call["call_id"], "facts": facts}, ensure_ascii=False)
        if cuda:
            torch.cuda.synchronize(args.device)
        latencies.append(time.perf_counter() - started)
    elapsed = sum(latencies)
    rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    rss_bytes = rss if sys.platform == "darwin" else rss * 1024
    result = {
        "checkpoint": str(args.checkpoint), "calls": len(calls), "batch_size": 1,
        "device": args.device, "platform": platform.platform(),
        "processor": platform.processor(), "torch_threads": args.threads,
        "torch_version": str(torch.__version__), "dtype": str(next(extractor.model.parameters()).dtype),
        "parameters": sum(parameter.numel() for parameter in extractor.model.parameters()),
        "threshold": args.threshold, "load_seconds": load_seconds,
        "value_catalog": str(args.value_catalog) if args.value_catalog else None,
        "ticket_states": args.ticket_states,
        "agreement_dates": args.agreement_dates,
        "latency_mean_ms": statistics.mean(latencies) * 1000,
        "latency_p50_ms": float(np.percentile(latencies, 50)) * 1000,
        "latency_p95_ms": float(np.percentile(latencies, 95)) * 1000,
        "calls_per_hour_batch_one": len(calls) * 3600 / elapsed,
        "process_peak_ram_bytes": rss_bytes,
        "gpu_name": torch.cuda.get_device_name(args.device) if cuda else None,
        "gpu_peak_allocated_bytes": torch.cuda.max_memory_allocated(args.device) if cuda else None,
        "gpu_peak_reserved_bytes": torch.cuda.max_memory_reserved(args.device) if cuda else None,
        "dedicated_gpu_seconds_per_1000_calls": elapsed * 1000 / len(calls) if cuda else None,
        "timing_scope": "tokenization, model, decoding and JSON serialization; excludes loading and warmup",
        "ram_scope": "process lifetime high-water RSS including model loading and input data",
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("x", encoding="utf-8") as stream:
        json.dump(result, stream, ensure_ascii=False, indent=2)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()