File size: 7,555 Bytes
5f55368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""Verify and time a static Gather vector against one request per decision."""
import argparse
import hashlib
import itertools
import json
import os
from pathlib import Path
import random
import re
import subprocess
import time

from adaptive import AdaptiveRuntime, Profiles
from benchmark import CORPUS_SHA, PHRASES, exact_document, expected, quantiles
from blob_layout import inspect_blob
from policy import LIMIT
from runtime import Runtime


STICK_PRODUCT_IDS = {"ncs1": "2150", "ncs2": "2485"}


def check_usb_identity(expected_stick, lines):
    products = []
    for line in lines:
        match = re.match(r"USB\\VID_03E7&PID_([0-9A-F]{4})\\", line.strip(), re.IGNORECASE)
        if match:
            products.append(match.group(1).upper())
    want = STICK_PRODUCT_IDS[expected_stick]
    if products != [want]:
        raise RuntimeError("Expected one cold %s (USB 03E7:%s); Windows reported %s"
                           % (expected_stick.upper(), want, products))
    return {"stick": expected_stick, "boot_usb_id": "03E7:" + want}


def windows_usb_identity(expected_stick):
    if os.name != "nt":
        raise RuntimeError("--expect-stick uses Windows USB enumeration")
    command = ("Get-PnpDevice -PresentOnly | Where-Object "
               "{ $_.InstanceId -like 'USB*VID_03E7*' } | Select-Object -ExpandProperty InstanceId")
    process = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command],
                             check=True, stdout=subprocess.PIPE, text=True, timeout=15)
    return check_usb_identity(expected_stick, process.stdout.splitlines())


def evaluate(engine, repeats, corpus):
    rows = []
    for flags in itertools.product((False, True), repeat=len(PHRASES)):
        selected = [i for i, present in enumerate(flags) if present]
        rows.append((" ; ".join(PHRASES[i] for i in selected), expected(selected)))
    random.Random(120).shuffle(rows)

    def dispatch(group_size):
        for start in range(0, len(rows), group_size):
            portion = rows[start:start + group_size]
            ready = [engine.prepare_decision(text) for text, _ in portion]
            results = engine.decide_prepared(ready)
            for item, (_, gold) in zip(results, portion):
                if item["result"] != gold or item["request_documents"] != len(portion):
                    raise AssertionError("Gather results differed from the truth table")

    widths = sorted({1, engine.batch_capacity} | {n for n in (2, 8, 16, 32, 64) if n < engine.batch_capacity})
    samples = {width: [] for width in widths}
    for width in widths:
        dispatch(width)
    for trial in range(repeats):
        order = widths if trial % 2 == 0 else list(reversed(widths))
        for width in order:
            start = time.perf_counter()
            dispatch(width)
            samples[width].append((time.perf_counter() - start) * 1000)
    timings = {str(width): dict(ms_per_128_documents=quantiles(samples[width]),
                                device_requests=(128 + width - 1) // width) for width in widths}

    payload = corpus.read_bytes()
    if hashlib.sha256(payload).hexdigest() != CORPUS_SHA:
        raise ValueError("Unexpected benchmark corpus")
    source = engine.tokenizer.encode(payload.decode("utf-8-sig"))
    documents = [
        {"id": "early", "text": exact_document(engine.tokenizer, source, LIMIT, start="charged twice review authorized")},
        {"id": "overflow", "text": exact_document(engine.tokenizer, source, LIMIT + 1)},
        {"id": "late", "text": exact_document(engine.tokenizer, source, LIMIT, end="package missing review authorized")},
        {"id": "veto", "text": exact_document(engine.tokenizer, source, LIMIT, start="parcel missing review authorized",
                                               end="review cancelled")},
        {"id": "empty", "text": ""},
    ]
    profiles = Profiles()
    try:
        routed = AdaptiveRuntime({"support": lambda: engine}, profiles).batch(
            {"vertical": "support", "documents": documents}
        )
    finally:
        profiles.close()
    want = [expected([0, 4]), None, expected([2, 4]), expected([3, 4, 6]), expected([])]
    if [row["id"] for row in routed["documents"]] != [row["id"] for row in documents]:
        raise AssertionError("Grouped dispatch changed response ordering")
    for row, gold in zip(routed["documents"], want):
        if gold is None:
            if str(LIMIT + 1) not in row.get("error", ""):
                raise AssertionError("Overlong input reached the stick")
            continue
        if row["result"] != gold or row["needle_tokens"] != (0 if row["id"] == "empty" else LIMIT):
            raise AssertionError("Unexpected result for mixed-length grouped input")
    return dict(model=engine.model_name, backend=engine.target, lane=engine.lane,
                toolchain=engine.openvino_version, capacity=engine.batch_capacity,
                onnx_sha256=engine.info["onnx_sha256"],
                truth_table_cases=len(rows), repeats=repeats, timing=timings,
                mixed_length_device_requests=routed["device_requests"],
                mixed_length_results=[{"id": r["id"], "tokens": r.get("needle_tokens"),
                                       "result": r.get("result"), "error": r.get("error")}
                                      for r in routed["documents"]])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("bundle", type=Path)
    parser.add_argument("--blob", type=Path)
    parser.add_argument("--toolchain", type=Path)
    parser.add_argument("--lane", choices=("ncs1", "ncs2"), default="ncs1")
    parser.add_argument("--target")
    parser.add_argument("--expect-stick", choices=tuple(STICK_PRODUCT_IDS),
                        help="Require the specified cold stick as the only visible Movidius USB device")
    parser.add_argument("--corpus", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--export", type=Path, help="Export the graph compiled on the selected runtime")
    parser.add_argument("--repeats", type=int, default=13)
    args = parser.parse_args()
    if args.repeats < 1:
        parser.error("--repeats must be positive")
    identity = windows_usb_identity(args.expect_stick) if args.expect_stick else None
    runtime = Runtime(args.bundle, args.toolchain, lane=args.lane, target=args.target, blob=args.blob,
                      release_stick=args.expect_stick or "ncs1")
    report = evaluate(runtime, args.repeats, args.corpus)
    if identity:
        report["physical_usb_preflight"] = identity
    if args.export:
        runtime.export_blob(args.export)
    if args.bundle.suffix.lower() == ".m8b":
        report["release_archive_bytes"] = args.bundle.stat().st_size
    compiled_path = args.export or args.blob
    if compiled_path:
        compiled = compiled_path.read_bytes()
        report["compiled_blob_bytes"] = len(compiled)
        report["compiled_blob_sha256"] = hashlib.sha256(compiled).hexdigest()
        if args.lane == "ncs1":
            report["legacy_layout"] = inspect_blob(compiled)
    args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf8")
    print(json.dumps({"timing": report["timing"], "mixed_length_requests": report["mixed_length_device_requests"]}))