chadstthomas commited on
Commit
5f55368
·
verified ·
1 Parent(s): 4b1aa2b

Add NCS1 industry starter packs and compact candidate

Browse files
COMPETITORS.md CHANGED
@@ -14,6 +14,8 @@ The arithmetic lowering of the 46-byte decision diagram compiled to a **9,600-by
14
 
15
  The resident rank-one Gather occupies 192 bytes of headers, 64 bytes each for input and output descriptors, 128 bytes for its stage and 64 bytes for the constants section in the stock 2020.3.2 exporter. This establishes a floor for that exporter and layout. Other stage types, toolchains and device-accepted layouts remain part of the search. [Intel section serializer](https://github.com/openvinotoolkit/openvino/blob/2020.3.2/inference-engine/src/vpu/graph_transformer/src/backend/serialize.cpp#L150-L175) · [Intel Gather stage](https://github.com/openvinotoolkit/openvino/blob/2020.3.2/inference-engine/src/vpu/graph_transformer/src/stages/gather.cpp#L62-L82)
16
 
 
 
17
  ## Published context
18
 
19
  | Reference | What its published evidence covers |
 
14
 
15
  The resident rank-one Gather occupies 192 bytes of headers, 64 bytes each for input and output descriptors, 128 bytes for its stage and 64 bytes for the constants section in the stock 2020.3.2 exporter. This establishes a floor for that exporter and layout. Other stage types, toolchains and device-accepted layouts remain part of the search. [Intel section serializer](https://github.com/openvinotoolkit/openvino/blob/2020.3.2/inference-engine/src/vpu/graph_transformer/src/backend/serialize.cpp#L150-L175) · [Intel Gather stage](https://github.com/openvinotoolkit/openvino/blob/2020.3.2/inference-engine/src/vpu/graph_transformer/src/stages/gather.cpp#L62-L82)
16
 
17
+ The compact radix format preserves every section start and every byte of the resident table. It removes 32 zero padding bytes at the end of the stock radix file. Physical NCS1 accepted the 480-byte artifact and returned identical rule bits and results. Its median was 5.31 ms for 128 short decisions in one submission, versus 5.37 ms for the padded radix build on the same fixtures. [Physical compact and padded reports](measurements/compact-gather-physical-ncs1.json)
18
+
19
  ## Published context
20
 
21
  | Reference | What its published evidence covers |
README.md CHANGED
@@ -17,7 +17,7 @@ tags:
17
 
18
  ![Eight, a small black billiard-ball automaton, and Relay, a floating green microchip, inspect a glowing circuit on a violet workbench.](./assets/workbench.webp)
19
 
20
- MagicEightBall reads up to **131,072 Needle 3 tokens** and returns a Boolean answer, a category, and a proposed action. The host counts tokens and extracts evidence. This private development preview packages the **512-byte** native build that passed the sustained NCS1 run. A **480-byte** candidate has passed direct physical replay with the same decision contract.
21
 
22
  ## Three decisions at the workbench
23
 
@@ -52,16 +52,20 @@ The release passed all 128 support-policy assignments on a physical NCS1, includ
52
  | CPU Boolean interpreter | 714-byte source policy | 4.57 / 8.26 ms | 39.26 / 49.48 ms |
53
  | CPU lookup | 128-byte generated table | 3.82 / 6.95 ms | 37.63 / 50.03 ms |
54
  | CPU decision diagram | 46-byte generated diagram | 4.03 / 7.37 ms | 37.92 / 52.50 ms |
 
 
55
 
56
  The CPU table and diagram figures cover decision data. Their runners also use the policy, tokenizer, and output mapping. The NCS1 took 223.70 ms median for the same 128 decisions issued one by one, about 35 times as long as the batch. In the streaming replay, short appends near the context limit took **1.90 ms median** after ingesting the initial prefix. Fresh full-context requests spend most of their time in host preparation. [Complete comparison report](./measurements/ncs1-cpu-comparison.json) · [Physical stream replay](./measurements/release-stream-ncs1.json)
57
 
58
- The **480-byte radix Gather** is the smallest native artifact verified in this comparison. It passed all 128 assignments, two exact-limit documents and overflow rejection on NCS1. It took 5.31 ms median for one batch of 128 short decisions, compared with 5.37 ms for its 512-byte padded control. The candidate is recorded separately from the sustained build in this draft. [Physical compact comparison](./measurements/compact-gather-physical-ncs1.json) · [Size and competitor comparison](./COMPETITORS.md)
59
 
60
  A **30-minute** mixed workload on the physical NCS1 completed **107,104 native requests** and **3,507,656 checked decisions**, with **26,776 overflows rejected**. The run exercised full documents, incremental vetoes and 128-decision batches on the resident release. [Physical soak report](./measurements/soak-release-30m-ncs1.json)
61
 
62
  ## Industry use cases
63
 
64
- The public version will include runnable industry policies, illustrative input documents and labeled simulation reports. Each simulation will publish the expected answer, category and proposed action, and cover incomplete evidence, explicit vetoes and distracting text. Simulated results measure behavior against the declared policy. Physical load and latency results are tracked separately.
 
 
65
 
66
  ## Scope and downloads
67
 
@@ -70,9 +74,11 @@ The shipped English support policy recognizes specific phrases and evaluates aut
70
  | Artifact | Bytes |
71
  |---|---:|
72
  | [Native release archive](./bundles/magiceightball.m8b), including both targets | 735 |
 
73
  | [Shared tokenizer](./needle3-tokenizer.m8t.xz) | 23,412 |
74
- | Release data total | **24,147** |
 
75
 
76
- The totals cover those two files. Python, OpenVINO, firmware, runner source and the artwork have separate sizes. [Checksums](./SHA256SUMS.txt)
77
 
78
  MyriadForge source and policy use the MIT license. The shared tokenizer restores the original Apache-2.0 Needle 3 tokenizer bytes and verifies the pinned SHA-256. [License](./LICENSE) · [Tokenizer provenance](./NOTICE.txt)
 
17
 
18
  ![Eight, a small black billiard-ball automaton, and Relay, a floating green microchip, inspect a glowing circuit on a violet workbench.](./assets/workbench.webp)
19
 
20
+ MagicEightBall reads up to **131,072 Needle 3 tokens** and returns a Boolean answer, a category, and a proposed action. The host counts tokens and extracts evidence. This private development preview includes the **512-byte** native build that passed the sustained NCS1 run and a **480-byte** candidate that passed direct and packaged physical replay.
21
 
22
  ## Three decisions at the workbench
23
 
 
52
  | CPU Boolean interpreter | 714-byte source policy | 4.57 / 8.26 ms | 39.26 / 49.48 ms |
53
  | CPU lookup | 128-byte generated table | 3.82 / 6.95 ms | 37.63 / 50.03 ms |
54
  | CPU decision diagram | 46-byte generated diagram | 4.03 / 7.37 ms | 37.92 / 52.50 ms |
55
+ | Compiled CPU lookup | 128-byte table and 2,560-byte native library | 3.29 / 4.02 ms | 33.58 / 38.09 ms |
56
+ | OpenVINO 2020.3.2 CPU Gather | Same 258-byte source ONNX | 4.04 / 4.80 ms | 33.53 / 41.25 ms |
57
 
58
  The CPU table and diagram figures cover decision data. Their runners also use the policy, tokenizer, and output mapping. The NCS1 took 223.70 ms median for the same 128 decisions issued one by one, about 35 times as long as the batch. In the streaming replay, short appends near the context limit took **1.90 ms median** after ingesting the initial prefix. Fresh full-context requests spend most of their time in host preparation. [Complete comparison report](./measurements/ncs1-cpu-comparison.json) · [Physical stream replay](./measurements/release-stream-ncs1.json)
59
 
60
+ The **480-byte radix Gather** is the smallest native artifact verified in this comparison. It passed all 128 assignments, two exact-limit documents and overflow rejection on NCS1. It took 5.31 ms median for one batch of 128 short decisions, compared with 5.37 ms for its 512-byte padded control. The packaged candidate also passed the vector and mixed-context replay. Its separate sustained run is in progress. [Physical compact comparison](./measurements/compact-gather-physical-ncs1.json) · [Packaged candidate replay](./measurements/compact-release-vector-ncs1.json) · [Size and competitor comparison](./COMPETITORS.md)
61
 
62
  A **30-minute** mixed workload on the physical NCS1 completed **107,104 native requests** and **3,507,656 checked decisions**, with **26,776 overflows rejected**. The run exercised full documents, incremental vetoes and 128-decision batches on the resident release. [Physical soak report](./measurements/soak-release-30m-ncs1.json)
63
 
64
  ## Industry use cases
65
 
66
+ Two starter packs are ready to try on one resident NCS1 graph. **Logistics and fulfillment** triages missing shipments and address exceptions. **Software on-call** triages network and capacity incidents. The record-mode examples take evidence from a declared field, so an archived approval or hold stays outside the decision. [Run the starter packs](./industries/README.md) · [Labeled cases](./industries/scenarios.json)
67
+
68
+ Both CPU and physical NCS1 agreed with all **18 of 18** simulated outcomes, including two 131,072-token cases with late vetoes. MagicEightBall issued zero proposals on the ten expected no-action cases. A baseline using the same rules without approval or veto checks issued seven. These results are from hand-authored simulations. [CPU simulation](./measurements/industry-simulation-cpu.json) · [Physical NCS1 simulation](./measurements/industry-simulation-ncs1.json)
69
 
70
  ## Scope and downloads
71
 
 
74
  | Artifact | Bytes |
75
  |---|---:|
76
  | [Native release archive](./bundles/magiceightball.m8b), including both targets | 735 |
77
+ | [Compact candidate archive](./bundles/magiceightball-ncs1-compact.m8b), with the 480-byte NCS1 image | 699 |
78
  | [Shared tokenizer](./needle3-tokenizer.m8t.xz) | 23,412 |
79
+ | Stock archive plus tokenizer | **24,147** |
80
+ | Compact archive plus tokenizer | **24,111** |
81
 
82
+ Each total covers one archive and the shared tokenizer. Python, OpenVINO, firmware, runner source and the artwork have separate sizes. [Checksums](./SHA256SUMS.txt)
83
 
84
  MyriadForge source and policy use the MIT license. The shared tokenizer restores the original Apache-2.0 Needle 3 tokenizer bytes and verifies the pinned SHA-256. [License](./LICENSE) · [Tokenizer provenance](./NOTICE.txt)
SHA256SUMS.txt CHANGED
@@ -1,16 +1,33 @@
 
1
  b3306882eafa0140c64782511e2410f7c3af67f65c60e602ff0b13a8d890c665 assets/relay-decisions-still.webp
2
  8159a4e6eee107efef2311842a81ec3dcf0a763dc6d7bf10dd969c43f3cebe99 assets/relay-decisions.webp
3
  e9775806f7bdc8b8d68c3dad5c83b289503110bed04a4596bf9662ee9ef801a1 assets/workbench.webp
4
- eecb32e0e68e90fef5e0b55f52a6958e1155e2687ba7ef8c5af35cddef947185 blob_layout.py
 
 
 
 
 
5
  6076cc698d9948e5a133ea63b331195aa5c0e2e00c4173310a84614748917850 bundles/magiceightball.m8b
6
  81b1fa3936a84bf8736ad900d35754b5166a2fa129aac2c0b83818c3a0e4a5fe compact_tokenizer.py
7
- e05dfd67f37d302212427f94157d841982763c7056e27d57678a159ca3640701 COMPETITORS.md
 
 
 
 
 
 
 
 
8
  d5c201295a6e23eaf03fcdd529af31629b48bb1a13c5c5f24c75477506434dc9 LICENSE
9
  cfd533aaa0b4750b644be9425680bbd362f106de85c82a69f20621c6155436bc measurements/compact-gather-physical-ncs1.json
 
10
  ddf47356e856ad45ebf207c0ad7ae3d7f2bb959595d98f8048072ab1b1afaab5 measurements/compare-compiled-table-cpu.json
11
  6230f1f350a25bf4a32962ba7d79e03dbd07ccd97995db241b8b7ec9a407bee6 measurements/compare-openvino-2020-cpu.json
12
  d1b5024052a92673d728eb08b8f89fa50977db0a36635b53414d0edc8c5a49e9 measurements/constant-free-pooling.json
13
  c8ef45bb68c3ce6660a62b92279fdb109ec4c483824c508a7b862a2290d9297d measurements/decision-diagram-native-controls.json
 
 
14
  109a416a538d082feed498c8643c9ddcd682d49dd29a1ca764b85475f5d2d7df measurements/native-release-and-stock-controls.json
15
  92ff4284bb33c5bfcc267e34798ac257799cbd327ce80d3d6689219bd4507cdf measurements/ncs1-cpu-comparison.json
16
  e5b13cf4a935892eabe91f7e9a8b7e1766dadcfc01d7602f4bc0bbf1dfbd9906 measurements/release-stream-ncs1.json
@@ -20,10 +37,13 @@ e5b13cf4a935892eabe91f7e9a8b7e1766dadcfc01d7602f4bc0bbf1dfbd9906 measurements/r
20
  f4ea979d548c51410e8bce44cf25980dc8813fe0ce2999319e8dc62ef14ff769 measurements/two-banks-ncs1.json
21
  97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9 needle3-tokenizer.m8t.xz
22
  ece5848c64d031c0e17952cda3232d805cb5841f3a8c06ac009f399b57b266d1 NOTICE.txt
 
23
  52ef0bb07e52712d16073c73030790e5d6a746c0291492e03917e13749dccdc2 policy.py
24
  1f530b66213e4c46939580856dcb4ccf57516b7f55202516bb7128ea4414110a radix.py
25
- cb4ec9b4a73de98bc2adc585761a66e76b38a66cde04849f143221fde64e4a38 README.md
26
- 4c122588a2f03c2fe09baf9f9308ca2785fe508634dc558b2c4e855aea381c8e release.py
27
  ee797b0ff94fbf99117cf0c580f118f447f0dd0100d1a19f64c6e7e4ffdfef8f runtime.py
 
28
  a1215ecf1dd1cec6f13221a00e48a44435b136291287fa7dccc05f5dbef4b9bc stream.py
 
29
  9b9c5c754c41e0dd8b8c5e2f2d7415e30c709d1915f333fabb7c83261ff35a22 support.json
 
1
+ b163b04556a7ed11c0bbb376d2404956c8441c858376809ba49d08e859bec9b6 adaptive.py
2
  b3306882eafa0140c64782511e2410f7c3af67f65c60e602ff0b13a8d890c665 assets/relay-decisions-still.webp
3
  8159a4e6eee107efef2311842a81ec3dcf0a763dc6d7bf10dd969c43f3cebe99 assets/relay-decisions.webp
4
  e9775806f7bdc8b8d68c3dad5c83b289503110bed04a4596bf9662ee9ef801a1 assets/workbench.webp
5
+ ceda70f87ab411c3a5294bee5c9a44d0a8c73914716d6004a96982fdb29f1730 benchmark.py
6
+ 704ab730971959fe77ac643edd342db3fec8ded07056d2af03101aeb477286a3 benchmark_batch_heads.py
7
+ f526d17fddcaea20a6108aac2b8f9d830034ebc480c01171fc6ff698ce2b2d51 benchmark_stream.py
8
+ 9e1666a0c8ebf5478f3bfd720be24636b26110b73bcb653ab77f3f0675c4a984 blob_layout.py
9
+ 111ac314774c52ccecad31c4f5adc86ec12d3a94e0877117aa2cac488975ce14 build.py
10
+ 1a8c1a021f62d89e236ebea379f9c69c9e4ffebe925c6bca49bb70df07d7cf61 bundles/magiceightball-ncs1-compact.m8b
11
  6076cc698d9948e5a133ea63b331195aa5c0e2e00c4173310a84614748917850 bundles/magiceightball.m8b
12
  81b1fa3936a84bf8736ad900d35754b5166a2fa129aac2c0b83818c3a0e4a5fe compact_tokenizer.py
13
+ 1e2b4c1395c4aab7c022246caa766d448aa0f70357a3b3d487daa55259ca7a84 COMPETITORS.md
14
+ 35531b9fcf4f8c265e26418dd458bbdf205faff7c11d822e9e3ae90ab6b955ba industries/adaptive.json
15
+ 7aafb73515f9dc25afe8b2a4dc58ac431cd5f4816aa93d3919b0cecbb648e269 industries/bundle/model.json
16
+ 72481bf69d70da97d0d0055c02f555ef2bd6b08625fdbf7c5d10b8995db5f6bb industries/bundle/model.onnx
17
+ fdbe4ace9b7d936db8da5a2daa11262e44c4ffad35336f0090683d60c7966c34 industries/bundle/ncs1-native.blob
18
+ 0f9cf03f7471f4e9397daa8623df8e9e4b7d803d100c5593b4348d57890e1871 industries/logistics.json
19
+ 3c51c71ab3c3d36fe4f2b3d5c61b8a1f3a19abe57502d538cd77036ba069fdc4 industries/policies.json
20
+ c4510a4628ae89d2327519badddaa3590273c34f3266d8d6c7f4ea3746d95e5e industries/README.md
21
+ 9b0777ab4e45f0ba6f5eed0d28e1fba3afc725436c844f3b41c868b8a8910b04 industries/scenarios.json
22
  d5c201295a6e23eaf03fcdd529af31629b48bb1a13c5c5f24c75477506434dc9 LICENSE
23
  cfd533aaa0b4750b644be9425680bbd362f106de85c82a69f20621c6155436bc measurements/compact-gather-physical-ncs1.json
24
+ 16144504646a9b4edccbee422dada63dec88e21073f8e18d381a1b703aef2991 measurements/compact-release-vector-ncs1.json
25
  ddf47356e856ad45ebf207c0ad7ae3d7f2bb959595d98f8048072ab1b1afaab5 measurements/compare-compiled-table-cpu.json
26
  6230f1f350a25bf4a32962ba7d79e03dbd07ccd97995db241b8b7ec9a407bee6 measurements/compare-openvino-2020-cpu.json
27
  d1b5024052a92673d728eb08b8f89fa50977db0a36635b53414d0edc8c5a49e9 measurements/constant-free-pooling.json
28
  c8ef45bb68c3ce6660a62b92279fdb109ec4c483824c508a7b862a2290d9297d measurements/decision-diagram-native-controls.json
29
+ a2de361e506926a1f9367cc3fa6430e0f14d829cf84ce4603f2f018667918dfe measurements/industry-simulation-cpu.json
30
+ 10fe96ad54942bfafabc37b5f521cdc9ee1a9bfb897a8691370d86de60c14d25 measurements/industry-simulation-ncs1.json
31
  109a416a538d082feed498c8643c9ddcd682d49dd29a1ca764b85475f5d2d7df measurements/native-release-and-stock-controls.json
32
  92ff4284bb33c5bfcc267e34798ac257799cbd327ce80d3d6689219bd4507cdf measurements/ncs1-cpu-comparison.json
33
  e5b13cf4a935892eabe91f7e9a8b7e1766dadcfc01d7602f4bc0bbf1dfbd9906 measurements/release-stream-ncs1.json
 
37
  f4ea979d548c51410e8bce44cf25980dc8813fe0ce2999319e8dc62ef14ff769 measurements/two-banks-ncs1.json
38
  97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9 needle3-tokenizer.m8t.xz
39
  ece5848c64d031c0e17952cda3232d805cb5841f3a8c06ac009f399b57b266d1 NOTICE.txt
40
+ 96495747ca35a24f6ed9ed741508edd31367c0e16cd9017131bbce0566bce46a oncall.json
41
  52ef0bb07e52712d16073c73030790e5d6a746c0291492e03917e13749dccdc2 policy.py
42
  1f530b66213e4c46939580856dcb4ccf57516b7f55202516bb7128ea4414110a radix.py
43
+ 7c4c4a4aec25862daede9b89f2dd4eaae51f2a7532b5d1d296cdc0e45edb0764 README.md
44
+ 9f435e1a91da46d3b294048da148f1e7a2820923d3896ed3d7fe9549d0c45eea release.py
45
  ee797b0ff94fbf99117cf0c580f118f447f0dd0100d1a19f64c6e7e4ffdfef8f runtime.py
46
+ 03856a5afdd900a593828cde92ddb3946d31220baed4427b3f5127123acef9a1 simulate_industries.py
47
  a1215ecf1dd1cec6f13221a00e48a44435b136291287fa7dccc05f5dbef4b9bc stream.py
48
+ 3a115da44828ad4f2d375118d7e0a42ab134aeb8ab0e014dd8e9c8bb042a23c7 supervisor.py
49
  9b9c5c754c41e0dd8b8c5e2f2d7415e30c709d1915f333fabb7c83261ff35a22 support.json
adaptive.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Learn exact preparation lanes by vertical and document structure behind each batch."""
2
+ import argparse
3
+ from functools import partial
4
+ import hashlib
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import sqlite3
9
+ import sys
10
+ import time
11
+
12
+ import numpy as np
13
+
14
+ from policy import SegmentMemo, needle_count, tokenizer_prior
15
+ from runtime import Runtime, json_output_stream
16
+ from supervisor import supervise
17
+
18
+
19
+ REFERENCE = "anchored"
20
+ LANES = (REFERENCE, "segmented", "cached")
21
+ EXPLORATION_ORDER = ("cached", "segmented", REFERENCE)
22
+ PROBE_INTERVAL = 8
23
+ COOLDOWN = 16
24
+
25
+
26
+ def profile_key(text):
27
+ prefix = text[:512].lstrip()
28
+ if prefix.startswith(("{", "[")):
29
+ structure = "json"
30
+ elif prefix.startswith("<"):
31
+ structure = "markup"
32
+ elif "\t" in prefix and "\n" in prefix:
33
+ structure = "rows"
34
+ else:
35
+ structure = "text"
36
+ length = len(text)
37
+ size = "short" if length < 4096 else "medium" if length < 100000 else "long"
38
+ return structure, size
39
+
40
+
41
+ def score_decision(result, expected):
42
+ correct = {key: int(result[key] == expected[key]) for key in ("answers", "category", "action")}
43
+ return dict(correct, labeled=1, joint=int(all(correct.values())),
44
+ proposed=int(result["action"] is not None),
45
+ correct_proposal=int(result["action"] is not None and correct["action"]))
46
+
47
+
48
+ def probe_excerpt(text):
49
+ if len(text) <= 16384:
50
+ return text
51
+ return text[:8192] + " " + text[-8192:]
52
+
53
+
54
+ class Profiles:
55
+ def __init__(self, path=":memory:"):
56
+ self.db = sqlite3.connect(str(path))
57
+ self.db.execute(
58
+ "CREATE TABLE IF NOT EXISTS lanes (profile TEXT PRIMARY KEY, state TEXT NOT NULL)"
59
+ )
60
+
61
+ def get(self, key):
62
+ record = self.db.execute("SELECT state FROM lanes WHERE profile = ?", (key,)).fetchone()
63
+ return json.loads(record[0]) if record else {"batches": 0, "ms": {}, "retry_at": {}}
64
+
65
+ def save(self, profiles):
66
+ with self.db:
67
+ self.db.executemany(
68
+ "INSERT OR REPLACE INTO lanes (profile, state) VALUES (?, ?)",
69
+ [(key, json.dumps(state)) for key, state in profiles.items()],
70
+ )
71
+
72
+ def close(self):
73
+ self.db.close()
74
+
75
+
76
+ class BatchEvidence:
77
+ """A constrained latency bandit with an independent evidence reference."""
78
+
79
+ def __init__(self, engine, state, memo):
80
+ self.engine = engine
81
+ self.state = state
82
+ self.memo = memo
83
+ self.used = {}
84
+ self.failures = {}
85
+ self.probe = state["batches"] % PROBE_INTERVAL == 0
86
+ self.audited = False
87
+
88
+ def measure(self, lane, text, evidence_text):
89
+ start = time.perf_counter()
90
+ memo = self.memo if lane == "cached" else None
91
+ tokens = needle_count(self.engine.tokenizer, text, memo=memo)
92
+ counted = time.perf_counter()
93
+ policy = self.engine.policy
94
+ atoms = (policy.anchored_atoms(evidence_text) if lane == REFERENCE
95
+ else policy.text_atoms(evidence_text))
96
+ return (tokens, atoms, counted), (time.perf_counter() - start) * 1000
97
+
98
+ def observe(self, lane, elapsed):
99
+ score = self.state["ms"]
100
+ score[lane] = 0.75 * score.get(lane, elapsed) + 0.25 * elapsed
101
+
102
+ def quarantine(self, lane, reason):
103
+ self.failures[lane] = reason
104
+ self.state["ms"].pop(lane, None)
105
+ self.state["retry_at"][lane] = self.state["batches"] + COOLDOWN
106
+ if lane == "cached":
107
+ self.memo.counts.clear()
108
+
109
+ def prepare(self, text, evidence_text=None):
110
+ evidence_text = text if evidence_text is None else evidence_text
111
+ scores = self.state["ms"]
112
+ checking = self.probe
113
+ if checking:
114
+ self.probe = False
115
+ probe, sample = probe_excerpt(text), probe_excerpt(evidence_text)
116
+ reference, _ = self.measure(REFERENCE, probe, sample)
117
+ eligible = {REFERENCE}
118
+ for lane in LANES[1:]:
119
+ if self.state["retry_at"].get(lane, 0) > self.state["batches"]:
120
+ continue
121
+ try:
122
+ prepared, _ = self.measure(lane, probe, sample)
123
+ if prepared[0] != reference[0] or not np.array_equal(prepared[1], reference[1]):
124
+ self.quarantine(lane, "evidence or token count disagreed with the reference")
125
+ else:
126
+ eligible.add(lane)
127
+ self.state["retry_at"].pop(lane, None)
128
+ except (RuntimeError, ValueError):
129
+ self.quarantine(lane, "preparation failed")
130
+ options = [lane for lane in EXPLORATION_ORDER if lane in eligible]
131
+ next_lane = next((lane for lane in options if lane not in scores), None)
132
+ rotation = (self.state["batches"] // PROBE_INTERVAL) % len(options)
133
+ selected = next_lane if next_lane is not None else options[rotation]
134
+ else:
135
+ eligible = [lane for lane in LANES if lane in scores]
136
+ selected = min(eligible, key=scores.__getitem__) if eligible else REFERENCE
137
+ try:
138
+ result, elapsed = self.measure(selected, text, evidence_text)
139
+ except (RuntimeError, ValueError):
140
+ if selected == REFERENCE:
141
+ raise
142
+ self.quarantine(selected, "preparation failed")
143
+ selected = REFERENCE
144
+ result, elapsed = self.measure(selected, text, evidence_text)
145
+ if checking and selected != REFERENCE:
146
+ policy = self.engine.policy
147
+ reference_atoms = policy.anchored_atoms(evidence_text)
148
+ if not np.array_equal(result[1], reference_atoms):
149
+ self.quarantine(selected, "full-document evidence disagreed with the reference")
150
+ selected = REFERENCE
151
+ result, elapsed = self.measure(selected, text, evidence_text)
152
+ self.observe(selected, elapsed)
153
+ self.used[selected] = self.used.get(selected, 0) + 1
154
+ return result
155
+
156
+ class AdaptiveRuntime:
157
+ """Use the requested policy on the physical stick and retry a failed device session once."""
158
+
159
+ def __init__(self, factories, profiles, scopes=None, banks=None):
160
+ self.factories = factories
161
+ self.profiles = profiles
162
+ self.scopes = scopes or {}
163
+ self.banks = banks or {}
164
+ self.engines = {}
165
+ self.memos = {}
166
+ self.prior = None
167
+
168
+ def engine(self, vertical):
169
+ factory = self.factories[vertical]
170
+ if factory not in self.engines:
171
+ engine = factory()
172
+ if engine.info["variant"] == "scan":
173
+ raise ValueError("Adaptive mode needs a bundle that accepts fact bits")
174
+ self.engines[factory] = engine
175
+ engine = self.engines[factory]
176
+ bank = self.banks.get(vertical)
177
+ return engine if bank is None else engine.policy_view(bank)
178
+
179
+ def batch(self, request, explain=False):
180
+ if not isinstance(request, dict):
181
+ raise ValueError("Expected a batch object")
182
+ vertical = request.get("vertical")
183
+ if not isinstance(vertical, str) or vertical not in self.factories:
184
+ raise ValueError("Choose a configured vertical")
185
+ rows = request.get("documents")
186
+ if not isinstance(rows, list) or not rows:
187
+ raise ValueError("Expected a nonempty documents array")
188
+ if any(not isinstance(row, dict) or not isinstance(row.get("text"), str) for row in rows):
189
+ raise ValueError("Each document needs a text string")
190
+ for row in rows:
191
+ if "expected" not in row:
192
+ continue
193
+ label = row["expected"]
194
+ if (not isinstance(label, dict) or set(label) != {"answers", "category", "action"}
195
+ or not isinstance(label["answers"], dict)
196
+ or any(type(value) is not bool for value in label["answers"].values())
197
+ or any(label[key] is not None and not isinstance(label[key], str)
198
+ for key in ("category", "action"))):
199
+ raise ValueError("Expected feedback with Boolean answers, a category and an action")
200
+ engine = self.engine(vertical)
201
+ signature = (engine.info["policy"], engine.info.get("onnx_sha256"))
202
+ policy_hash = hashlib.sha256(json.dumps(signature[0]).encode("utf8")).hexdigest()
203
+ if self.prior is None:
204
+ self.prior = tokenizer_prior(engine.tokenizer)
205
+ memo = self.memos.setdefault(vertical, SegmentMemo(prior=self.prior))
206
+ scope = self.scopes.get(vertical)
207
+ contexts, outputs = {}, [None] * len(rows)
208
+ pending = []
209
+ device_requests = 0
210
+
211
+ def flush():
212
+ nonlocal engine, device_requests
213
+ if not pending:
214
+ return
215
+ prepared = [job[3] for job in pending]
216
+
217
+ def infer():
218
+ nonlocal device_requests
219
+ device_requests += 1
220
+ results = engine.decide_prepared(prepared)
221
+ if len(results) != len(pending):
222
+ raise RuntimeError("Device returned an unexpected number of decisions")
223
+ for (_, evidence, _, _), result in zip(pending, results):
224
+ if evidence.audited or evidence.state["batches"] % PROBE_INTERVAL != 0:
225
+ continue
226
+ reference = engine.policy.reference(result["atoms"])
227
+ if not np.array_equal(reference, result["bits"]):
228
+ raise RuntimeError("Device disagreed with the Boolean reference")
229
+ evidence.audited = True
230
+ return results
231
+
232
+ recovered = False
233
+ try:
234
+ results = infer()
235
+ except RuntimeError:
236
+ recovered = True
237
+ if recovered:
238
+ self.engines.pop(self.factories[vertical], None)
239
+ for _, context in contexts.values():
240
+ context.engine = None
241
+ context.audited = False
242
+ del engine
243
+ engine = self.engine(vertical)
244
+ if (engine.info["policy"], engine.info.get("onnx_sha256")) != signature:
245
+ raise RuntimeError("Model changed during recovery")
246
+ for _, context in contexts.values():
247
+ context.engine = engine
248
+ results = infer()
249
+ for (index, evidence, evidence_text, _), result in zip(pending, results):
250
+ row = rows[index]
251
+ if explain:
252
+ result["explanation"] = engine.policy.explain(evidence_text, result["atoms"])
253
+ if "expected" in row:
254
+ scores = score_decision(result["result"], row["expected"])
255
+ totals = evidence.state.setdefault("feedback", {})
256
+ for name, score in scores.items():
257
+ totals[name] = totals.get(name, 0) + score
258
+ result["feedback"] = scores
259
+ outputs[index] = dict(result, id=row.get("id"), device_reloaded=recovered)
260
+ pending.clear()
261
+
262
+ for index, row in enumerate(rows):
263
+ text = row["text"]
264
+ shape = profile_key(text)
265
+ if shape not in contexts:
266
+ key = json.dumps(["v2", engine.lane, vertical, policy_hash, scope, *shape])
267
+ contexts[shape] = key, BatchEvidence(engine, self.profiles.get(key), memo)
268
+ _, evidence = contexts[shape]
269
+ try:
270
+ evidence_text = text
271
+ if scope is not None:
272
+ document = json.loads(text)
273
+ if not isinstance(document, dict) or not isinstance(document.get(scope), str):
274
+ raise ValueError("Expected a string in JSON evidence field %r" % scope)
275
+ evidence_text = document[scope]
276
+ prepare = partial(evidence.prepare, evidence_text=evidence_text)
277
+ prepared = engine.prepare_decision(text, prepare=prepare)
278
+ except ValueError as exc:
279
+ outputs[index] = {"id": row.get("id"), "error": str(exc)}
280
+ continue
281
+ pending.append((index, evidence, evidence_text, prepared))
282
+ if len(pending) == engine.batch_capacity:
283
+ flush()
284
+ flush()
285
+ updates, routes = {}, []
286
+ for (structure, size), (key, evidence) in contexts.items():
287
+ if evidence.used:
288
+ evidence.state["batches"] += 1
289
+ updates[key] = evidence.state
290
+ routes.append(dict(structure=structure, size=size, used=evidence.used,
291
+ quarantined=evidence.failures, feedback=evidence.state.get("feedback", {})))
292
+ self.profiles.save(updates)
293
+ return {"id": request.get("id"), "vertical": vertical, "routes": routes,
294
+ "documents": outputs, "device_requests": device_requests}
295
+
296
+
297
+ def main():
298
+ parser = argparse.ArgumentParser(description=__doc__)
299
+ parser.add_argument("config", type=Path, help="JSON object mapping vertical names to bundle and optional blob paths")
300
+ parser.add_argument("--state", type=Path, help="Retain only per-profile timing and health across runs")
301
+ parser.add_argument("--lane", choices=["ncs1", "ncs2"], default="ncs1")
302
+ parser.add_argument("--toolchain", type=Path)
303
+ parser.add_argument("--target")
304
+ parser.add_argument("--release-stick", choices=["ncs1", "ncs2"], help="Physical target for a .m8b archive")
305
+ parser.add_argument("--explain", action="store_true")
306
+ parser.add_argument("--batch-timeout", type=float, help="Worker deadline in seconds, including cold model load")
307
+ args = parser.parse_args()
308
+ if args.batch_timeout is not None:
309
+ if not math.isfinite(args.batch_timeout) or args.batch_timeout <= 0:
310
+ parser.error("--batch-timeout must be finite and positive")
311
+ command = [sys.executable, str(Path(__file__).resolve()), str(args.config), "--lane", args.lane]
312
+ for key in ("state", "toolchain", "target"):
313
+ value = getattr(args, key)
314
+ if value is not None:
315
+ command.extend(("--" + key, str(value)))
316
+ if args.release_stick:
317
+ command.extend(("--release-stick", args.release_stick))
318
+ if args.explain:
319
+ command.append("--explain")
320
+ with json_output_stream() as output:
321
+ supervise(command, sys.stdin.buffer, output, args.batch_timeout)
322
+ return
323
+ config = json.loads(args.config.read_bytes())
324
+ if not isinstance(config, dict) or not config:
325
+ parser.error("Config must map vertical names to bundle objects")
326
+ for name, entry in config.items():
327
+ if not isinstance(entry, dict) or not isinstance(entry.get("bundle"), str):
328
+ parser.error("Vertical %r needs a bundle path" % name)
329
+ for field in ("blob", "evidence_field", "bank"):
330
+ if field in entry and not isinstance(entry[field], str):
331
+ parser.error("Vertical %r requires a string for %s" % (name, field))
332
+
333
+ def load(bundle, blob):
334
+ return Runtime(bundle, args.toolchain, lane=args.lane, target=args.target, blob=blob,
335
+ release_stick=args.release_stick or "ncs1")
336
+
337
+ root = args.config.resolve().parent
338
+ by_bundle, factories = {}, {}
339
+ for name, entry in config.items():
340
+ bundle = (root / entry["bundle"]).resolve()
341
+ blob = (root / entry["blob"]).resolve() if "blob" in entry else None
342
+ factories[name] = by_bundle.setdefault((bundle, blob), partial(load, bundle, blob))
343
+ profiles = Profiles(args.state or ":memory:")
344
+ try:
345
+ with json_output_stream() as output:
346
+ runtime = AdaptiveRuntime(factories, profiles,
347
+ {name: entry.get("evidence_field") for name, entry in config.items()},
348
+ {name: entry.get("bank") for name, entry in config.items()})
349
+ for line in sys.stdin.buffer:
350
+ request = None
351
+ try:
352
+ request = json.loads(line)
353
+ response = runtime.batch(request, explain=args.explain)
354
+ except (ValueError, RuntimeError) as exc:
355
+ response = {"error": str(exc), "id": request.get("id") if isinstance(request, dict) else None}
356
+ print(json.dumps(response), file=output, flush=True)
357
+ finally:
358
+ profiles.close()
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()
benchmark.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure the support policy end to end, including real Needle tokenization."""
2
+ import argparse
3
+ import hashlib
4
+ import itertools
5
+ import json
6
+ from pathlib import Path
7
+ import tempfile
8
+ import time
9
+
10
+ import numpy as np
11
+ from policy import LIMIT, count_tokens
12
+ from runtime import Runtime
13
+
14
+
15
+ PHRASES = ("charged twice", "duplicate charge", "package missing", "parcel missing",
16
+ "review authorized", "do not route", "review cancelled")
17
+ CORPUS_SHA = "48e0522844402a86a3ea98f0947ba85ea54838db3c59022299298ed968a5a163"
18
+
19
+
20
+ def expected(indices):
21
+ present = set(indices)
22
+ billing = bool(present & {0,1})
23
+ delivery = bool(present & {2,3})
24
+ kind = "mixed" if billing and delivery else "billing" if billing else "delivery" if delivery else None
25
+ ready = bool(kind and 4 in present and not present & {5,6})
26
+ actions = {"mixed":"triage_mixed","billing":"review_billing","delivery":"review_delivery"}
27
+ return {"answers":{"may_route":ready}, "category":kind, "action":actions[kind] if ready else None}
28
+
29
+
30
+ def exact_document(tok, source_ids, size, start="", middle="", end=""):
31
+ # Leave room for insertions, then fill the small difference before the
32
+ # suffix. The final assertion measures the finished string independently.
33
+ body = tok.decode(source_ids[:max(1, size-70)])
34
+ halves = body.split(" ")
35
+ cut = len(halves)//2
36
+ prefix = " ".join([start, " ".join(halves[:cut]), middle, " ".join(halves[cut:])]).strip()
37
+ suffix = " " + end if end else ""
38
+ doc = prefix + suffix
39
+ gap = size - len(tok.encode(doc, out_type=int))
40
+ if gap < 0:
41
+ raise ValueError("Too little reserved space in fixture")
42
+ doc = prefix + " a"*gap + suffix
43
+ if len(tok.encode(doc, out_type=int)) != size:
44
+ raise AssertionError("Wrong fixture token count")
45
+ return doc
46
+
47
+
48
+ def quantiles(values):
49
+ return {k: float(np.percentile(values, v)) for k,v in (("p50",50),("p95",95),("max",100))}
50
+
51
+
52
+ def evaluate(engine, corpus, repeats, session, export_path=None):
53
+ policy, tok = engine.policy, engine.tokenizer
54
+ corpus_bytes = corpus.read_bytes()
55
+ if hashlib.sha256(corpus_bytes).hexdigest() != CORPUS_SHA:
56
+ raise ValueError("Unexpected benchmark corpus")
57
+ text = corpus_bytes.decode("utf-8-sig")
58
+ if any(policy.atoms(policy.project(text))):
59
+ raise AssertionError("Reference text unexpectedly contains an evidence phrase")
60
+ source = tok.encode(text, out_type=int)
61
+ if len(source) < LIMIT:
62
+ raise AssertionError("Need at least a full window of natural text")
63
+ def check(document, indices):
64
+ record = engine.decide(document)
65
+ want_atoms = [float(" ".join(literal) in {PHRASES[i] for i in indices})
66
+ for literal in policy.literals]
67
+ if record["result"] != expected(indices) or record["atoms"] != want_atoms:
68
+ raise AssertionError((indices, record, want_atoms))
69
+ if any(v not in (0,1) for v in record["bits"]):
70
+ raise AssertionError("Graph returned a non-Boolean value")
71
+ return record
72
+
73
+ checks = 0
74
+ for combination in itertools.product((False,True), repeat=len(PHRASES)):
75
+ indices = [i for i,on in enumerate(combination) if on]
76
+ check(" ; ".join(PHRASES[i] for i in indices), indices)
77
+ checks += 1
78
+ targeted = [
79
+ ("", []), ("CHARGED TWICE. REVIEW AUTHORIZED.", [0,4]),
80
+ ("duplicated charge; package apparently missing; preview authorized", []),
81
+ ("duplicate;charge; review-cancelled", []),
82
+ ("duplicate charge\nreview\tauthorized", [1,4]),
83
+ ("package missing but do not route. review authorized.", [2,4,5]),
84
+ ("Ångström 東京 charged twice 📃 review authorized", [0,4])]
85
+ for where in [63, 4095, 8191]:
86
+ targeted.append(("note "*where + "charged twice. review authorized", [0,4]))
87
+ targeted.append(("note "*where + "do not route. parcel missing. review authorized", [5,3,4]))
88
+ for doc, indices in targeted:
89
+ check(doc,indices)
90
+
91
+ long_cases = [
92
+ ("early", "charged twice review authorized", "", "", [0,4]),
93
+ ("middle", "", "charged twice review authorized", "", [0,4]),
94
+ ("last", "", "", "charged twice review authorized", [0,4]),
95
+ ("far_apart", "package missing", "", "review authorized", [2,4]),
96
+ ("late_veto", "duplicate charge", "review authorized", "review cancelled", [1,4,6]),
97
+ ("late_category", "parcel missing", "review authorized", "charged twice", [3,4,0]),
98
+ ("absent", "", "", "", [])]
99
+ cases = {}
100
+ for label, first, mid, last, indices in long_cases:
101
+ doc = exact_document(tok, source, LIMIT, first, mid, last)
102
+ result = check(doc, indices)
103
+ cases[label] = dict(tokens=result["needle_tokens"], result=result["result"],
104
+ input_sha256=hashlib.sha256(doc.encode("utf8")).hexdigest())
105
+ try:
106
+ engine.decide(exact_document(tok, source, LIMIT+1))
107
+ except ValueError as exc:
108
+ if "maximum" not in str(exc):
109
+ raise
110
+ else:
111
+ raise AssertionError("Over-limit input accepted")
112
+
113
+ timing = {}
114
+ for size in [1024, 32768, LIMIT]:
115
+ doc = exact_document(tok, source, size, PHRASES[1], "", PHRASES[4])
116
+ for _ in range(3):
117
+ check(doc,[1,4])
118
+ runs = []
119
+ cpu_ms = []
120
+ for _ in range(repeats):
121
+ runs.append(check(doc,[1,4]))
122
+ start = time.perf_counter()
123
+ count_tokens(tok, doc, fast=engine.fast_count)
124
+ atoms = (policy.text_atoms(doc) if engine.fast_count and engine.info["variant"] != "scan"
125
+ else policy.atoms(policy.project(doc)))
126
+ cpu_result = policy.result(policy.reference(atoms))
127
+ cpu_ms.append(1000*(time.perf_counter()-start))
128
+ if cpu_result != expected([1,4]):
129
+ raise AssertionError("CPU policy reference disagreed")
130
+ data = {name:quantiles([r[name] for r in runs]) for name in
131
+ ("total_ms","tokenization_ms","host_projection_ms","inference_path_ms")}
132
+ data.update(cpu_reference_ms=quantiles(cpu_ms), requests=runs[0]["requests"],
133
+ lexemes=runs[0]["lexemes"], utf8_bytes=len(doc.encode("utf8")),
134
+ documents=repeats, tokens_per_second_p50=size*1000/data["total_ms"]["p50"])
135
+ timing[str(size)] = data
136
+ ir = engine.ir
137
+ sizes = dict(onnx=(engine.folder/"model.onnx").stat().st_size, ir_xml=ir.stat().st_size,
138
+ ir_weights=ir.with_suffix(".bin").stat().st_size)
139
+ with tempfile.TemporaryDirectory() as tmp:
140
+ export = Path(tmp)/"myriad.blob"
141
+ engine.export_blob(export)
142
+ sizes["compiled_blob"] = export.stat().st_size
143
+ if export_path is not None:
144
+ export_path.write_bytes(export.read_bytes())
145
+ return dict(session=session, variant=engine.info["variant"], fast_count=engine.fast_count,
146
+ onnx_sha256=engine.info["onnx_sha256"],
147
+ corpus_sha256=CORPUS_SHA, load_ms=engine.load_ms, devices=engine.devices,
148
+ backend=engine.target, lane=engine.lane, openvino_version=engine.openvino_version,
149
+ exhaustive_combinations=checks, adversarial_cases=len(targeted),
150
+ context_cases=cases, rejected_131073=True, bytes=sizes, timing=timing)
151
+
152
+
153
+ if __name__ == "__main__":
154
+ p = argparse.ArgumentParser(description=__doc__)
155
+ p.add_argument("bundle", type=Path)
156
+ p.add_argument("--toolchain", type=Path)
157
+ p.add_argument("--lane", choices=["ncs1", "ncs2"], default="ncs1")
158
+ p.add_argument("--target")
159
+ p.add_argument("--export", type=Path)
160
+ p.add_argument("--corpus", type=Path, required=True)
161
+ p.add_argument("--output", type=Path, required=True)
162
+ p.add_argument("--repeats", type=int, default=30)
163
+ p.add_argument("--session", type=int, default=1)
164
+ p.add_argument("--fast-count", action="store_true")
165
+ args = p.parse_args()
166
+ if args.repeats < 1:
167
+ p.error("--repeats must be positive")
168
+ engine = Runtime(args.bundle, args.toolchain, fast_count=args.fast_count, lane=args.lane, target=args.target)
169
+ r = evaluate(engine, args.corpus, args.repeats, args.session, args.export)
170
+ args.output.parent.mkdir(exist_ok=True, parents=True)
171
+ args.output.write_text(json.dumps(r,indent=2)+"\n",encoding="utf8")
172
+ print(args.bundle.name, r["bytes"], r["timing"][str(LIMIT)]["total_ms"])
benchmark_batch_heads.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify and time a static Gather vector against one request per decision."""
2
+ import argparse
3
+ import hashlib
4
+ import itertools
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import random
9
+ import re
10
+ import subprocess
11
+ import time
12
+
13
+ from adaptive import AdaptiveRuntime, Profiles
14
+ from benchmark import CORPUS_SHA, PHRASES, exact_document, expected, quantiles
15
+ from blob_layout import inspect_blob
16
+ from policy import LIMIT
17
+ from runtime import Runtime
18
+
19
+
20
+ STICK_PRODUCT_IDS = {"ncs1": "2150", "ncs2": "2485"}
21
+
22
+
23
+ def check_usb_identity(expected_stick, lines):
24
+ products = []
25
+ for line in lines:
26
+ match = re.match(r"USB\\VID_03E7&PID_([0-9A-F]{4})\\", line.strip(), re.IGNORECASE)
27
+ if match:
28
+ products.append(match.group(1).upper())
29
+ want = STICK_PRODUCT_IDS[expected_stick]
30
+ if products != [want]:
31
+ raise RuntimeError("Expected one cold %s (USB 03E7:%s); Windows reported %s"
32
+ % (expected_stick.upper(), want, products))
33
+ return {"stick": expected_stick, "boot_usb_id": "03E7:" + want}
34
+
35
+
36
+ def windows_usb_identity(expected_stick):
37
+ if os.name != "nt":
38
+ raise RuntimeError("--expect-stick uses Windows USB enumeration")
39
+ command = ("Get-PnpDevice -PresentOnly | Where-Object "
40
+ "{ $_.InstanceId -like 'USB*VID_03E7*' } | Select-Object -ExpandProperty InstanceId")
41
+ process = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command],
42
+ check=True, stdout=subprocess.PIPE, text=True, timeout=15)
43
+ return check_usb_identity(expected_stick, process.stdout.splitlines())
44
+
45
+
46
+ def evaluate(engine, repeats, corpus):
47
+ rows = []
48
+ for flags in itertools.product((False, True), repeat=len(PHRASES)):
49
+ selected = [i for i, present in enumerate(flags) if present]
50
+ rows.append((" ; ".join(PHRASES[i] for i in selected), expected(selected)))
51
+ random.Random(120).shuffle(rows)
52
+
53
+ def dispatch(group_size):
54
+ for start in range(0, len(rows), group_size):
55
+ portion = rows[start:start + group_size]
56
+ ready = [engine.prepare_decision(text) for text, _ in portion]
57
+ results = engine.decide_prepared(ready)
58
+ for item, (_, gold) in zip(results, portion):
59
+ if item["result"] != gold or item["request_documents"] != len(portion):
60
+ raise AssertionError("Gather results differed from the truth table")
61
+
62
+ widths = sorted({1, engine.batch_capacity} | {n for n in (2, 8, 16, 32, 64) if n < engine.batch_capacity})
63
+ samples = {width: [] for width in widths}
64
+ for width in widths:
65
+ dispatch(width)
66
+ for trial in range(repeats):
67
+ order = widths if trial % 2 == 0 else list(reversed(widths))
68
+ for width in order:
69
+ start = time.perf_counter()
70
+ dispatch(width)
71
+ samples[width].append((time.perf_counter() - start) * 1000)
72
+ timings = {str(width): dict(ms_per_128_documents=quantiles(samples[width]),
73
+ device_requests=(128 + width - 1) // width) for width in widths}
74
+
75
+ payload = corpus.read_bytes()
76
+ if hashlib.sha256(payload).hexdigest() != CORPUS_SHA:
77
+ raise ValueError("Unexpected benchmark corpus")
78
+ source = engine.tokenizer.encode(payload.decode("utf-8-sig"))
79
+ documents = [
80
+ {"id": "early", "text": exact_document(engine.tokenizer, source, LIMIT, start="charged twice review authorized")},
81
+ {"id": "overflow", "text": exact_document(engine.tokenizer, source, LIMIT + 1)},
82
+ {"id": "late", "text": exact_document(engine.tokenizer, source, LIMIT, end="package missing review authorized")},
83
+ {"id": "veto", "text": exact_document(engine.tokenizer, source, LIMIT, start="parcel missing review authorized",
84
+ end="review cancelled")},
85
+ {"id": "empty", "text": ""},
86
+ ]
87
+ profiles = Profiles()
88
+ try:
89
+ routed = AdaptiveRuntime({"support": lambda: engine}, profiles).batch(
90
+ {"vertical": "support", "documents": documents}
91
+ )
92
+ finally:
93
+ profiles.close()
94
+ want = [expected([0, 4]), None, expected([2, 4]), expected([3, 4, 6]), expected([])]
95
+ if [row["id"] for row in routed["documents"]] != [row["id"] for row in documents]:
96
+ raise AssertionError("Grouped dispatch changed response ordering")
97
+ for row, gold in zip(routed["documents"], want):
98
+ if gold is None:
99
+ if str(LIMIT + 1) not in row.get("error", ""):
100
+ raise AssertionError("Overlong input reached the stick")
101
+ continue
102
+ if row["result"] != gold or row["needle_tokens"] != (0 if row["id"] == "empty" else LIMIT):
103
+ raise AssertionError("Unexpected result for mixed-length grouped input")
104
+ return dict(model=engine.model_name, backend=engine.target, lane=engine.lane,
105
+ toolchain=engine.openvino_version, capacity=engine.batch_capacity,
106
+ onnx_sha256=engine.info["onnx_sha256"],
107
+ truth_table_cases=len(rows), repeats=repeats, timing=timings,
108
+ mixed_length_device_requests=routed["device_requests"],
109
+ mixed_length_results=[{"id": r["id"], "tokens": r.get("needle_tokens"),
110
+ "result": r.get("result"), "error": r.get("error")}
111
+ for r in routed["documents"]])
112
+
113
+
114
+ if __name__ == "__main__":
115
+ parser = argparse.ArgumentParser(description=__doc__)
116
+ parser.add_argument("bundle", type=Path)
117
+ parser.add_argument("--blob", type=Path)
118
+ parser.add_argument("--toolchain", type=Path)
119
+ parser.add_argument("--lane", choices=("ncs1", "ncs2"), default="ncs1")
120
+ parser.add_argument("--target")
121
+ parser.add_argument("--expect-stick", choices=tuple(STICK_PRODUCT_IDS),
122
+ help="Require the specified cold stick as the only visible Movidius USB device")
123
+ parser.add_argument("--corpus", type=Path, required=True)
124
+ parser.add_argument("--output", type=Path, required=True)
125
+ parser.add_argument("--export", type=Path, help="Export the graph compiled on the selected runtime")
126
+ parser.add_argument("--repeats", type=int, default=13)
127
+ args = parser.parse_args()
128
+ if args.repeats < 1:
129
+ parser.error("--repeats must be positive")
130
+ identity = windows_usb_identity(args.expect_stick) if args.expect_stick else None
131
+ runtime = Runtime(args.bundle, args.toolchain, lane=args.lane, target=args.target, blob=args.blob,
132
+ release_stick=args.expect_stick or "ncs1")
133
+ report = evaluate(runtime, args.repeats, args.corpus)
134
+ if identity:
135
+ report["physical_usb_preflight"] = identity
136
+ if args.export:
137
+ runtime.export_blob(args.export)
138
+ if args.bundle.suffix.lower() == ".m8b":
139
+ report["release_archive_bytes"] = args.bundle.stat().st_size
140
+ compiled_path = args.export or args.blob
141
+ if compiled_path:
142
+ compiled = compiled_path.read_bytes()
143
+ report["compiled_blob_bytes"] = len(compiled)
144
+ report["compiled_blob_sha256"] = hashlib.sha256(compiled).hexdigest()
145
+ if args.lane == "ncs1":
146
+ report["legacy_layout"] = inspect_blob(compiled)
147
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf8")
148
+ print(json.dumps({"timing": report["timing"], "mixed_length_requests": report["mixed_length_device_requests"]}))
benchmark_stream.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure exact append-only decisions near the full Needle context limit."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ from benchmark import CORPUS_SHA, exact_document, expected, quantiles
10
+ from benchmark_batch_heads import windows_usb_identity
11
+ from policy import LIMIT, load_tokenizer
12
+ from runtime import Runtime
13
+ from stream import DecisionStream
14
+
15
+
16
+ def evaluate(engine, corpus):
17
+ raw = corpus.read_bytes()
18
+ if hashlib.sha256(raw).hexdigest() != CORPUS_SHA:
19
+ raise ValueError("Unexpected benchmark corpus")
20
+ tokenizer = engine.tokenizer
21
+ source = tokenizer.encode(raw.decode("utf-8-sig"), out_type=int)
22
+ prefix = exact_document(tokenizer, source, LIMIT - 640, start="duplicate charge. review authorized.")
23
+ fragments = [" Note %d filed." % i for i in range(24)]
24
+ veto = " do not route"
25
+ total = len(tokenizer.encode(prefix + "".join(fragments) + veto, out_type=int))
26
+ if total >= LIMIT:
27
+ raise AssertionError("Benchmark did not leave space for its final append")
28
+ fragments.append(" a" * (LIMIT - total) + veto)
29
+ stream = DecisionStream(engine)
30
+ initial = stream.append(prefix)
31
+ assert initial["needle_tokens"] == LIMIT - 640 and initial["result"] == expected([1, 4])
32
+ whole = prefix
33
+ samples = {"full_text": [], "stream": []}
34
+ for index, delta in enumerate(fragments):
35
+ whole += delta
36
+ if index % 2:
37
+ incremental, full = stream.append(delta), engine.decide(whole)
38
+ else:
39
+ full, incremental = engine.decide(whole), stream.append(delta)
40
+ for key in ("needle_tokens", "bits", "atoms", "result"):
41
+ if incremental[key] != full[key]:
42
+ raise AssertionError("Incremental replay disagreed with full input on %s" % key)
43
+ # Report the stable short-appends separately from the final padded veto.
44
+ if index < len(fragments) - 1:
45
+ samples["full_text"].append(full)
46
+ samples["stream"].append(incremental)
47
+ assert len(tokenizer.encode(whole, out_type=int)) == LIMIT
48
+ assert incremental["needle_tokens"] == LIMIT and incremental["result"] == expected([1, 4, 5])
49
+ saved = stream.state
50
+ try:
51
+ stream.append(" b")
52
+ except ValueError as exc:
53
+ if str(LIMIT + 1) not in str(exc):
54
+ raise
55
+ else:
56
+ raise AssertionError("Expected overflow rejection")
57
+ assert stream.state is saved
58
+ timing = {}
59
+ for name, records in samples.items():
60
+ host = np.array([r["tokenization_ms"] + r["host_projection_ms"] for r in records])
61
+ timing[name] = dict(host_preparation_ms=quantiles(host),
62
+ total_ms=quantiles([r["total_ms"] for r in records]))
63
+ return dict(model=engine.model_name, backend=engine.target, openvino_version=engine.openvino_version,
64
+ onnx_sha256=engine.info["onnx_sha256"], samples=len(samples["stream"]),
65
+ initial_tokens=initial["needle_tokens"], initial_ms=initial["total_ms"],
66
+ final_tokens=incremental["needle_tokens"], final_veto=incremental["result"],
67
+ overflow_rejected=True, timing=timing)
68
+
69
+
70
+ def cpu_control(bundle):
71
+ from openvino.runtime import Core, get_version
72
+
73
+ engine = Runtime.__new__(Runtime)
74
+ engine.folder = bundle
75
+ engine.bundle_info = json.loads((bundle / "model.json").read_text(encoding="utf8"))
76
+ engine._use_bank(None)
77
+ engine.tokenizer = load_tokenizer()
78
+ engine.fast_count = True
79
+ engine.lane = "ncs2"
80
+ engine.target = "CPU"
81
+ engine.openvino_version = get_version()
82
+ engine.compiled = Core().compile_model(str(engine.resolve_ir()), engine.target)
83
+ engine.request = engine.compiled.create_infer_request()
84
+ return engine
85
+
86
+
87
+ if __name__ == "__main__":
88
+ parser = argparse.ArgumentParser(description=__doc__)
89
+ parser.add_argument("bundle", type=Path)
90
+ parser.add_argument("--blob", type=Path)
91
+ parser.add_argument("--toolchain", type=Path)
92
+ parser.add_argument("--lane", choices=["ncs1", "ncs2"], default="ncs1")
93
+ target = parser.add_mutually_exclusive_group()
94
+ target.add_argument("--expect-stick", choices=["ncs1", "ncs2"])
95
+ target.add_argument("--cpu", action="store_true", help="Use OpenVINO 2022.3's CPU plugin and an IR bundle")
96
+ parser.add_argument("--corpus", type=Path, required=True)
97
+ parser.add_argument("--output", type=Path, required=True)
98
+ args = parser.parse_args()
99
+ if args.cpu and (args.blob or args.bundle.is_file()):
100
+ parser.error("--cpu requires an IR bundle directory")
101
+ identity = windows_usb_identity(args.expect_stick) if args.expect_stick else None
102
+ engine = (cpu_control(args.bundle) if args.cpu
103
+ else Runtime(args.bundle, args.toolchain, lane=args.lane, blob=args.blob,
104
+ release_stick=args.expect_stick or "ncs1"))
105
+ report = evaluate(engine, args.corpus)
106
+ report["physical_device_verified"] = identity is not None
107
+ if identity:
108
+ report["physical_usb_preflight"] = identity
109
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf8")
110
+ print(json.dumps(report))
blob_layout.py CHANGED
@@ -10,18 +10,43 @@ import struct
10
  ELF_HEADER_SIZE = 52
11
  HEADER = struct.Struct("<20I")
12
  SECTION_NAMES = ("headers", "input_descriptor", "output_descriptor", "stages", "constants")
 
13
 
14
 
15
- def inspect_blob(data):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  if not data.startswith(b"\x7felf") or len(data) < ELF_HEADER_SIZE + HEADER.size:
17
  raise ValueError("Expected an OpenVINO 2020.3 MYRIAD blob")
18
  fields = HEADER.unpack_from(data, ELF_HEADER_SIZE)
19
  magic, size, major, minor = fields[:4]
20
  boundaries = (0, *fields[16:], size)
21
  if (magic != 9709 or major != 5 or size != len(data)
22
- or list(boundaries) != sorted(boundaries) or any(n % 64 for n in boundaries)):
23
  raise ValueError("Invalid legacy MYRIAD header or section layout")
24
  layout = {name: end - start for name, start, end in zip(SECTION_NAMES, boundaries, boundaries[1:])}
 
 
 
 
 
25
  stage_count = fields[6]
26
  stage = None
27
  if stage_count == 1:
@@ -36,8 +61,24 @@ def inspect_blob(data):
36
  input_bytes=fields[7], output_bytes=fields[8], sections=layout, sole_stage=stage)
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  if __name__ == "__main__":
40
  parser = argparse.ArgumentParser(description=__doc__)
41
  parser.add_argument("blobs", nargs="+", type=Path)
 
42
  args = parser.parse_args()
43
- print(json.dumps({str(path): inspect_blob(path.read_bytes()) for path in args.blobs}, indent=2))
 
 
10
  ELF_HEADER_SIZE = 52
11
  HEADER = struct.Struct("<20I")
12
  SECTION_NAMES = ("headers", "input_descriptor", "output_descriptor", "stages", "constants")
13
+ GATHER_WORDS = struct.Struct("<32I")
14
 
15
 
16
+ def _gather_coefficient_bytes(data, fields):
17
+ """Verify the stock rank-one Gather stage before trusting its table extent."""
18
+ if fields[2:7] != (5, 0, 1, 1, 1) or fields[16:] != (192, 256, 320, 448):
19
+ raise ValueError("Compact terminal storage requires a canonical rank-one Gather")
20
+ words = GATHER_WORDS.unpack_from(data, fields[18])
21
+ slots, remainder = divmod(fields[7], 4)
22
+ # The three descriptors are FP16 table, FP16 output and signed I32 index.
23
+ # Their rank, element stride, location, port and offset come from data.cpp.
24
+ table = (0, 3, 1, words[8], 2, 3, 0)
25
+ output = (0, 3, 1, slots, 2, 2, 0, slots * 2, 0)
26
+ indices = (2, 3, 1, slots, 4, 1, 0, slots * 4, 0)
27
+ if (not slots or remainder or fields[8] != slots * 2 or not words[8]
28
+ or words[:2] != (128, 100) or words[3:5] != (8, 0)
29
+ or words[5:12] != table or words[12:21] != output or words[21:30] != indices
30
+ or words[30:] != (100, 2139356953)):
31
+ raise ValueError("Unexpected rank-one Gather descriptors")
32
+ return words[8] * 2
33
+
34
+
35
+ def inspect_blob(data, compact_coefficients=None):
36
  if not data.startswith(b"\x7felf") or len(data) < ELF_HEADER_SIZE + HEADER.size:
37
  raise ValueError("Expected an OpenVINO 2020.3 MYRIAD blob")
38
  fields = HEADER.unpack_from(data, ELF_HEADER_SIZE)
39
  magic, size, major, minor = fields[:4]
40
  boundaries = (0, *fields[16:], size)
41
  if (magic != 9709 or major != 5 or size != len(data)
42
+ or list(boundaries) != sorted(boundaries) or any(n % 64 for n in boundaries[:-1])):
43
  raise ValueError("Invalid legacy MYRIAD header or section layout")
44
  layout = {name: end - start for name, start, end in zip(SECTION_NAMES, boundaries, boundaries[1:])}
45
+ if size % 64:
46
+ if type(compact_coefficients) is not int or compact_coefficients != layout["constants"]:
47
+ raise ValueError("Invalid compact Gather constant extent")
48
+ if _gather_coefficient_bytes(data, fields) != compact_coefficients:
49
+ raise ValueError("Compact Gather stage and manifest disagree on the constant extent")
50
  stage_count = fields[6]
51
  stage = None
52
  if stage_count == 1:
 
61
  input_bytes=fields[7], output_bytes=fields[8], sections=layout, sole_stage=stage)
62
 
63
 
64
+ def compact_gather_blob(data, coefficient_bytes):
65
+ """Drop only the terminal zero padding after a stock Gather's FP16 table."""
66
+ inspect_blob(data)
67
+ fields = HEADER.unpack_from(data, ELF_HEADER_SIZE)
68
+ if type(coefficient_bytes) is not int or _gather_coefficient_bytes(data, fields) != coefficient_bytes:
69
+ raise ValueError("Gather stage and manifest disagree on the constant extent")
70
+ end = fields[19] + coefficient_bytes
71
+ if not 0 <= len(data) - end < 64 or any(data[end:]):
72
+ raise ValueError("Expected zero padding in the final Gather section")
73
+ compact = bytearray(data[:end])
74
+ struct.pack_into("<I", compact, ELF_HEADER_SIZE + 4, end)
75
+ return bytes(compact)
76
+
77
+
78
  if __name__ == "__main__":
79
  parser = argparse.ArgumentParser(description=__doc__)
80
  parser.add_argument("blobs", nargs="+", type=Path)
81
+ parser.add_argument("--compact-coefficients", type=int)
82
  args = parser.parse_args()
83
+ print(json.dumps({str(path): inspect_blob(path.read_bytes(), args.compact_coefficients)
84
+ for path in args.blobs}, indent=2))
build.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compile exact Boolean policies to static graphs for Myriad 2."""
2
+ import argparse
3
+ import hashlib
4
+ from itertools import combinations
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import onnx
10
+ from onnx import TensorProto, helper as h, numpy_helper
11
+
12
+ from policy import Policy
13
+ from radix import CAPACITY, encode_ranks
14
+
15
+
16
+ class Graph:
17
+ def __init__(self):
18
+ self.nodes = []
19
+ self.constants = []
20
+
21
+ def const(self, data):
22
+ key = "k%d" % len(self.constants)
23
+ self.constants.append(numpy_helper.from_array(np.asarray(data, dtype=np.float32), key))
24
+ return key
25
+
26
+ def op(self, op, inputs, **attributes):
27
+ value = "v%d" % len(self.nodes)
28
+ self.nodes.append(h.make_node(op, inputs, [value], name=value, **attributes))
29
+ return value
30
+
31
+ def conv(self, inputs, weights, bias):
32
+ return self.op("Conv", [inputs, self.const(weights), self.const(bias)],
33
+ kernel_shape=list(weights.shape[2:]))
34
+
35
+
36
+ def dense_head(g, policy, features):
37
+ # Inverted edges allow both AND and OR to use one affine/ReLU gate each.
38
+ n = len(policy.literals)
39
+ gates = []
40
+ levels = [0] * n
41
+ def lower(node):
42
+ if node[0] == "literal":
43
+ return policy.literals.index(node[1]), False
44
+ if node[0] == "not":
45
+ i, invert = lower(node[1])
46
+ return i, not invert
47
+ disjunction = node[0] == "or"
48
+ args = tuple(sorted((i, inv ^ disjunction) for i, inv in map(lower, node[1:])))
49
+ if args not in gates:
50
+ gates.append(args)
51
+ levels.append(1 + max(levels[i] for i, _ in args))
52
+ return n + gates.index(args), disjunction
53
+ ends = [lower(node) for node in policy.outputs]
54
+ live = list(range(n))
55
+ for depth in range(1, max(levels) + 1):
56
+ needed = {i for i, _ in ends}
57
+ for j, pair in enumerate(gates, n):
58
+ if levels[j] > depth:
59
+ needed.update(i for i, _ in pair)
60
+ layer = [i for i in live if i in needed] + [i for i, d in enumerate(levels) if d == depth]
61
+ matrix = np.zeros((len(layer), len(live), 1, 1), dtype=np.float32)
62
+ bias = np.zeros(len(layer), dtype=np.float32)
63
+ for row, key in enumerate(layer):
64
+ if key in live:
65
+ matrix[row, live.index(key)] = 1
66
+ else:
67
+ bias[row] = -1
68
+ for i, inv in gates[key-n]:
69
+ matrix[row, live.index(i)] += -1 if inv else 1
70
+ bias[row] += int(inv)
71
+ features = g.op("Relu", [g.conv(features, matrix, bias)])
72
+ live = layer
73
+ matrix = np.zeros((len(ends), len(live), 1, 1), dtype=np.float32)
74
+ bias = []
75
+ for row, (i, inv) in enumerate(ends):
76
+ matrix[row, live.index(i)] = -1 if inv else 1
77
+ bias.append(int(inv))
78
+ return g.conv(features, matrix, bias)
79
+
80
+
81
+ def gates_head(g, policy, features):
82
+ slices = ["atom%d" % i for i in range(len(policy.literals))]
83
+ g.nodes.append(h.make_node("Split", [features], slices, axis=1, split=[1]*len(slices)))
84
+ one = g.const(np.ones((1, 1, 1, 1)))
85
+ seen = {}
86
+ def emit(node):
87
+ if node not in seen:
88
+ if node[0] == "literal":
89
+ v = slices[policy.literals.index(node[1])]
90
+ elif node[0] == "not":
91
+ v = g.op("Sub", [one, emit(node[1])])
92
+ else:
93
+ v = g.op("Mul" if node[0] == "and" else "Max", [emit(n) for n in node[1:]])
94
+ seen[node] = v
95
+ return seen[node]
96
+ return g.op("Concat", [emit(node) for node in policy.outputs], axis=1)
97
+
98
+
99
+ def scanner(g, policy, side):
100
+ # Exact equality on small integer word IDs using adjacent ReLU hinges.
101
+ vocab = len(policy.word_ids)
102
+ hinges = np.ones((vocab+2, 1, 1, 1), dtype=np.float32)
103
+ cuts = g.op("Relu", [g.conv("lexemes", hinges, -np.arange(vocab+2))])
104
+ tents = np.zeros((vocab, vocab+2, 1, 1), dtype=np.float32)
105
+ for i in range(vocab):
106
+ tents[i, i:i+3, 0, 0] = [1, -2, 1]
107
+ equal = g.conv(cuts, tents, np.zeros(vocab))
108
+ width = max(map(len, policy.patterns))
109
+ w = np.zeros((len(policy.patterns), vocab, 1, width), dtype=np.float32)
110
+ for row, phrase in enumerate(policy.patterns):
111
+ for j, token in enumerate(phrase):
112
+ w[row, token-1, 0, width - len(phrase) + j] = 1
113
+ scores = g.op("Relu", [g.conv(equal, w, [1-len(p) for p in policy.patterns])])
114
+ remaining = side
115
+ while remaining > 1:
116
+ size = 4 if remaining % 4 == 0 else 2
117
+ scores = g.op("MaxPool", [scores], kernel_shape=[size,size], strides=[size,size])
118
+ remaining //= size
119
+ return g.op("Max", [scores, "prior"])
120
+
121
+
122
+ def _two_symbol_rows(codes, facts, base):
123
+ if facts < 3 or base * base * 256 > CAPACITY:
124
+ return None
125
+
126
+ def masks(bits):
127
+ return [sum(((mask >> index) & 1) << fact for index, fact in enumerate(bits))
128
+ for mask in range(1 << len(bits))]
129
+
130
+ for lane_facts in combinations(range(facts), 3):
131
+ address_facts = tuple(i for i in range(facts) if i not in lane_facts)
132
+ lanes = masks(lane_facts)
133
+ words = []
134
+ for address in masks(address_facts):
135
+ row = [codes[address | lane] for lane in lanes]
136
+ low, high = min(row), max(row)
137
+ if any(code not in (low, high) for code in row):
138
+ break
139
+ selectors = sum((code != low) << lane for lane, code in enumerate(row))
140
+ words.append((low * base + high) * 256 + selectors)
141
+ else:
142
+ return words, lane_facts + address_facts
143
+ return None
144
+
145
+
146
+ def packed_table(policy, codec="binary"):
147
+ """Encode reachable output vectors using signed, exact FP16 integers."""
148
+ facts = len(policy.literals)
149
+ if facts > 10:
150
+ raise ValueError("Packed lookup supports up to 10 literal predicates")
151
+ rows = [tuple(map(int, policy.reference([(mask >> j) & 1 for j in range(facts)])))
152
+ for mask in range(1 << facts)]
153
+ codebook = sorted(set(rows))
154
+ indices = {row: i for i, row in enumerate(codebook)}
155
+ if codec == "radix":
156
+ base = len(codebook)
157
+ codes = [indices[row] for row in rows]
158
+ lanes = 1
159
+ while lanes < len(rows) and base ** (lanes + 1) <= CAPACITY:
160
+ lanes += 1
161
+ weights = [sum(code * base ** lane
162
+ for lane, code in enumerate(codes[first:first + lanes]))
163
+ for first in range(0, len(rows), lanes)]
164
+ metadata = dict(codebook=codebook, radix_digits=lanes)
165
+ if facts >= 3 and (1 << (facts - 3)) < len(weights):
166
+ paired = _two_symbol_rows(codes, facts, base)
167
+ if paired is not None:
168
+ weights, order = paired
169
+ metadata.update(radix_digits=8, pair_fact_order=order)
170
+ return encode_ranks(weights).astype(np.float32), metadata
171
+
172
+ code_width = max(1, (len(codebook) - 1).bit_length())
173
+ lane_bits = min(facts, (12 // code_width).bit_length() - 1)
174
+ lanes = 1 << lane_bits
175
+ # FP16 represents every integer in [-2048, 2047] exactly. Centering
176
+ # the word at zero fits 12 bits where an unsigned word would fit 11.
177
+ offset = 1 << (code_width * lanes - 1)
178
+ words = [sum(indices[row] << (lane * code_width)
179
+ for lane, row in enumerate(rows[first:first + lanes])) - offset
180
+ for first in range(0, len(rows), lanes)]
181
+ table = np.asarray(words, dtype=np.float32).reshape(1, -1, 1, 1)
182
+ return table, dict(codebook=codebook, code_width=code_width, lane_bits=lane_bits, offset=offset)
183
+
184
+
185
+ def _write_bundle(g, shapes, outputs, directory, manifest):
186
+ variant = manifest["variant"]
187
+
188
+ def ports(mapping):
189
+ return [h.make_tensor_value_info(
190
+ name, TensorProto.INT32 if variant == "gather" and name == "features" else TensorProto.FLOAT, shape
191
+ ) for name, shape in mapping.items()]
192
+
193
+ graph = h.make_graph(g.nodes, "boolean_" + variant, ports(shapes), ports(outputs), g.constants)
194
+ model = h.make_model(graph, opset_imports=[h.make_opsetid("", 9)], ir_version=6)
195
+ onnx.checker.check_model(model)
196
+ directory.mkdir(exist_ok=True, parents=True)
197
+ blob = model.SerializeToString()
198
+ (directory/"model.onnx").write_bytes(blob)
199
+ manifest.update(input_shapes=shapes, onnx_sha256=hashlib.sha256(blob).hexdigest(),
200
+ fp16_coefficient_bytes=2*sum(np.prod(v.dims, dtype=int).item() for v in g.constants),
201
+ learned_parameters=0)
202
+ (directory/"model.json").write_text(json.dumps(manifest, indent=2)+"\n", encoding="utf8")
203
+
204
+
205
+ def compile_banks(sources, directory, slots=128):
206
+ if slots < 1 or not isinstance(sources, dict) or not sources:
207
+ raise ValueError("Expected named policy banks and a positive Gather capacity")
208
+ g = Graph()
209
+ tables, banks, locations = [], {}, {}
210
+ offset = 0
211
+ for bank, source in sources.items():
212
+ if not isinstance(bank, str) or not bank or not isinstance(source, Path):
213
+ raise ValueError("Each bank needs a name and a policy path")
214
+ spec = json.loads(source.read_bytes())
215
+ table, metadata = packed_table(Policy(spec), "radix")
216
+ key = table.tobytes()
217
+ if key not in locations:
218
+ locations[key] = offset
219
+ tables.append(table)
220
+ offset += table.size
221
+ banks[bank] = dict(policy=spec, bank_offset=locations[key], **metadata)
222
+ shapes = {"features": [slots]}
223
+ decisions = g.op("Gather", [g.const(np.concatenate(tables)), "features"], axis=0)
224
+ _write_bundle(g, shapes, {decisions: [slots]}, directory,
225
+ dict(name="magiceightball", variant="gather", decisions=decisions,
226
+ default_bank=next(iter(banks)), banks=banks))
227
+
228
+
229
+ def compile_policy(source, directory, variant, side=64, slots=1, codec="binary"):
230
+ if side < 2 or side & (side-1):
231
+ raise ValueError("Tile side must be a power of two")
232
+ if slots < 1 or (slots != 1 and variant != "gather"):
233
+ raise ValueError("Multiple positive slots are supported only with Gather")
234
+ if codec not in ("binary", "radix") or (codec == "radix" and variant != "gather"):
235
+ raise ValueError("The radix codec is supported only with Gather")
236
+ spec = json.loads(source.read_text(encoding="utf8"))
237
+ policy = Policy(spec)
238
+ g = Graph()
239
+ nf = len(policy.literals)
240
+ shapes = {"features": [1, nf, 1, 1]}
241
+ outputs = {}
242
+ metadata = {}
243
+ if variant == "scan":
244
+ shapes = {"lexemes": [1, 1, side, side + max(map(len,policy.patterns)) - 1],
245
+ "prior": [1, nf, 1, 1]}
246
+ features = scanner(g, policy, side)
247
+ else:
248
+ features = "features"
249
+ if variant in ("packed", "gather"):
250
+ table, metadata = packed_table(policy, codec)
251
+ if variant == "gather":
252
+ shapes = {"features": [slots]}
253
+ decisions = g.op("Gather", [g.const(table.reshape(-1)), "features"], axis=0)
254
+ outputs[decisions] = [slots]
255
+ else:
256
+ shapes = {"features": [1, table.shape[1], 1, 1]}
257
+ decisions = g.conv("features", table, [0])
258
+ outputs[decisions] = [1, 1, 1, 1]
259
+ elif variant == "lookup":
260
+ if nf > 10:
261
+ raise ValueError("The lookup form is intended for at most 10 literal predicates")
262
+ count = 1 << nf
263
+ words = (len(policy.outputs)+9)//10
264
+ table = np.zeros((words,count,1,1),dtype=np.float32)
265
+ for index in range(count):
266
+ facts = [(index >> j) & 1 for j in range(nf)]
267
+ for k,bit in enumerate(policy.reference(facts)):
268
+ table[k//10,index,0,0] += int(bit) << (k % 10)
269
+ shapes = {"features":[1,count,1,1]}
270
+ decisions = g.conv("features",table,np.zeros(words))
271
+ outputs[decisions] = [1,words,1,1]
272
+ else:
273
+ head = gates_head if variant == "gates" else dense_head
274
+ decisions = head(g, policy, features)
275
+ if variant == "scan":
276
+ decisions = g.op("Concat", [features, decisions], axis=1)
277
+ outputs[decisions] = [1, len(policy.outputs) + (nf if variant == "scan" else 0), 1, 1]
278
+ # OpenVINO uses producer node names when naming outputs, so keep those names in the manifest.
279
+ _write_bundle(g, shapes, outputs, directory, dict(
280
+ policy=spec, variant=variant, decisions=decisions,
281
+ state_channels=nf if variant=="scan" else 0, tile_side=side, **metadata,
282
+ ))
283
+
284
+
285
+ if __name__ == "__main__":
286
+ p = argparse.ArgumentParser(description=__doc__)
287
+ p.add_argument("policy", type=Path)
288
+ p.add_argument("output", type=Path)
289
+ p.add_argument("--variant", choices=["gates", "dense", "scan", "lookup", "packed", "gather", "banks"], required=True)
290
+ p.add_argument("--side", type=int, default=64)
291
+ p.add_argument("--slots", type=int, default=1, help="Independent decisions per Gather request")
292
+ p.add_argument("--codec", choices=["binary", "radix"], default="binary")
293
+ args = p.parse_args()
294
+ if args.variant == "banks":
295
+ sources = json.loads(args.policy.read_bytes())
296
+ if not isinstance(sources, dict) or any(not isinstance(path, str) for path in sources.values()):
297
+ p.error("A bank configuration maps names to policy filenames")
298
+ compile_banks({name: args.policy.parent / path for name, path in sources.items()},
299
+ args.output, args.slots)
300
+ else:
301
+ compile_policy(args.policy, args.output, args.variant, args.side, args.slots, args.codec)
bundles/magiceightball-ncs1-compact.m8b ADDED
Binary file (699 Bytes). View file
 
industries/README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MagicEightBall industry starter packs
2
+
3
+ One resident 512-byte native model supports two policies. Its policy bank is selected per request. The result is a proposal your application can review before doing any work.
4
+
5
+ | Pack | Use case | Example result |
6
+ |---|---|---|
7
+ | Logistics and fulfillment | Triage missing shipments and address exceptions. A proposal requires explicit dispatch approval and clears when a hold is present. | `parcel`, `trace_parcel` |
8
+ | Software on-call | Triage network and capacity incidents. Capacity-only proposals need both capacity signals, plus paging approval. Maintenance and cancellation veto paging. | `capacity`, `page_capacity` |
9
+
10
+ ## Run a case on NCS1
11
+
12
+ From the directory containing `runtime.py`, set the toolchain to your working Windows OpenVINO 2020.3.2 NCS1 installation. The Needle tokenizer belongs beside the runner.
13
+
14
+ ```powershell
15
+ $toolchain = 'D:/NTVStudy/tools/ncs1'
16
+ $python = Join-Path $toolchain '.venv/Scripts/python.exe'
17
+ $bundle = 'industries/bundle'
18
+ & $python runtime.py $bundle --toolchain $toolchain --blob "$bundle/ncs1-native.blob" --bank logistics --text 'Parcel missing. Dispatch approved.'
19
+ ```
20
+
21
+ Expect `may_escalate=true`, `category=parcel`, and `action=trace_parcel`. For software on-call, use `--bank oncall --text 'Queue backed up. Workers saturated. Paging approved.'` and expect `may_page=true`, `category=capacity`, and `action=page_capacity`.
22
+
23
+ For JSON records, the [adaptive config](adaptive.json) provides `logistics-record` and `oncall-record`. Those modes count the whole document toward the token limit and extract decision evidence from the `evidence` field. Use `adaptive.py industries/adaptive.json --toolchain <path> --batch-timeout 30` and send a JSON line containing `vertical` and `documents`. Each document contains `id` and `text`, where `text` is the serialized source record. Keep prior approvals and old holds outside `evidence`.
24
+
25
+ ## Simulation results
26
+
27
+ The [labeled suite](scenarios.json) contains 18 hand-authored cases. It includes routine authorization, incomplete evidence, contradictory history fields, explicit vetoes and two documents that place a veto at the 131,072-token boundary. The adapted policies matched **18 of 18** cases on both CPU and physical NCS1. Across the ten cases labeled for no action, the policies returned no proposals. An ungated baseline retained the class and corroboration logic but ignored approval and veto. It proposed actions in seven of those ten cases. These scores describe the labeled simulations. Live use needs labels from the intended workflow and validation with its actual records. [CPU report](../measurements/industry-simulation-cpu.json) · [NCS1 report](../measurements/industry-simulation-ncs1.json)
28
+
29
+ Rebuild the bank from the policy sources with `python build.py industries/policies.json <output> --variant banks --slots 128`. The bank has the same ONNX graph bytes as the previously measured two-bank build. Its manifest supplies the logistics and on-call phrases and result labels. To reproduce the simulation, run `simulate_industries.py industries/bundle --corpus <pinned-corpus> --output <report.json>` with OpenVINO 2022.3.1 for CPU. To run on NCS1, use the legacy runtime and add `--backend ncs1 --toolchain <path> --blob industries/bundle/ncs1-native.blob`.
industries/adaptive.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "logistics-text": {"bundle": "bundle", "blob": "bundle/ncs1-native.blob", "bank": "logistics"},
3
+ "logistics-record": {"bundle": "bundle", "blob": "bundle/ncs1-native.blob", "bank": "logistics", "evidence_field": "evidence"},
4
+ "oncall-text": {"bundle": "bundle", "blob": "bundle/ncs1-native.blob", "bank": "oncall"},
5
+ "oncall-record": {"bundle": "bundle", "blob": "bundle/ncs1-native.blob", "bank": "oncall", "evidence_field": "evidence"}
6
+ }
industries/bundle/model.json ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "magiceightball",
3
+ "variant": "gather",
4
+ "decisions": "v0",
5
+ "default_bank": "logistics",
6
+ "banks": {
7
+ "logistics": {
8
+ "policy": {
9
+ "name": "logistics",
10
+ "rules": {
11
+ "parcel": "\"parcel missing\" OR \"tracking stalled\"",
12
+ "address": "\"address mismatch\" OR \"postcode rejected\"",
13
+ "incident": "@parcel OR @address",
14
+ "ready": "@incident AND \"dispatch approved\" AND NOT (\"do not dispatch\" OR \"fraud review\")"
15
+ },
16
+ "answers": {
17
+ "may_escalate": "@ready"
18
+ },
19
+ "categories": {
20
+ "mixed_exception": "@parcel AND @address",
21
+ "parcel": "@parcel",
22
+ "address": "@address"
23
+ },
24
+ "actions": {
25
+ "review_shipment": "@ready AND @parcel AND @address",
26
+ "trace_parcel": "@ready AND @parcel",
27
+ "verify_address": "@ready AND @address"
28
+ }
29
+ },
30
+ "bank_offset": 0,
31
+ "codebook": [
32
+ [
33
+ 0,
34
+ 0,
35
+ 0,
36
+ 0,
37
+ 0,
38
+ 0,
39
+ 0
40
+ ],
41
+ [
42
+ 0,
43
+ 0,
44
+ 0,
45
+ 1,
46
+ 0,
47
+ 0,
48
+ 0
49
+ ],
50
+ [
51
+ 0,
52
+ 0,
53
+ 1,
54
+ 0,
55
+ 0,
56
+ 0,
57
+ 0
58
+ ],
59
+ [
60
+ 0,
61
+ 1,
62
+ 1,
63
+ 1,
64
+ 0,
65
+ 0,
66
+ 0
67
+ ],
68
+ [
69
+ 1,
70
+ 0,
71
+ 0,
72
+ 1,
73
+ 0,
74
+ 0,
75
+ 1
76
+ ],
77
+ [
78
+ 1,
79
+ 0,
80
+ 1,
81
+ 0,
82
+ 0,
83
+ 1,
84
+ 0
85
+ ],
86
+ [
87
+ 1,
88
+ 1,
89
+ 1,
90
+ 1,
91
+ 1,
92
+ 1,
93
+ 1
94
+ ]
95
+ ],
96
+ "radix_digits": 8,
97
+ "pair_fact_order": [
98
+ 4,
99
+ 5,
100
+ 6,
101
+ 0,
102
+ 1,
103
+ 2,
104
+ 3
105
+ ]
106
+ },
107
+ "oncall": {
108
+ "policy": {
109
+ "name": "oncall",
110
+ "rules": {
111
+ "network": "\"gateway unreachable\" OR \"connection reset\"",
112
+ "capacity": "\"queue backed up\" OR \"workers saturated\"",
113
+ "confirmed": "@network OR (\"queue backed up\" AND \"workers saturated\")",
114
+ "ready": "@confirmed AND \"paging approved\" AND NOT (\"maintenance window\" OR \"page cancelled\")"
115
+ },
116
+ "answers": {
117
+ "may_page": "@ready"
118
+ },
119
+ "categories": {
120
+ "mixed_incident": "@network AND @capacity",
121
+ "network": "@network",
122
+ "capacity": "@capacity"
123
+ },
124
+ "actions": {
125
+ "page_incident": "@ready AND @network AND @capacity",
126
+ "page_network": "@ready AND @network",
127
+ "page_capacity": "@ready AND @capacity"
128
+ }
129
+ },
130
+ "bank_offset": 16,
131
+ "codebook": [
132
+ [
133
+ 0,
134
+ 0,
135
+ 0,
136
+ 0,
137
+ 0,
138
+ 0,
139
+ 0
140
+ ],
141
+ [
142
+ 0,
143
+ 0,
144
+ 0,
145
+ 1,
146
+ 0,
147
+ 0,
148
+ 0
149
+ ],
150
+ [
151
+ 0,
152
+ 0,
153
+ 1,
154
+ 0,
155
+ 0,
156
+ 0,
157
+ 0
158
+ ],
159
+ [
160
+ 0,
161
+ 1,
162
+ 1,
163
+ 1,
164
+ 0,
165
+ 0,
166
+ 0
167
+ ],
168
+ [
169
+ 1,
170
+ 0,
171
+ 0,
172
+ 1,
173
+ 0,
174
+ 0,
175
+ 1
176
+ ],
177
+ [
178
+ 1,
179
+ 0,
180
+ 1,
181
+ 0,
182
+ 0,
183
+ 1,
184
+ 0
185
+ ],
186
+ [
187
+ 1,
188
+ 1,
189
+ 1,
190
+ 1,
191
+ 1,
192
+ 1,
193
+ 1
194
+ ]
195
+ ],
196
+ "radix_digits": 8,
197
+ "pair_fact_order": [
198
+ 4,
199
+ 5,
200
+ 6,
201
+ 0,
202
+ 1,
203
+ 2,
204
+ 3
205
+ ]
206
+ }
207
+ },
208
+ "input_shapes": {
209
+ "features": [
210
+ 128
211
+ ]
212
+ },
213
+ "onnx_sha256": "72481bf69d70da97d0d0055c02f555ef2bd6b08625fdbf7c5d10b8995db5f6bb",
214
+ "fp16_coefficient_bytes": 64,
215
+ "learned_parameters": 0
216
+ }
industries/bundle/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72481bf69d70da97d0d0055c02f555ef2bd6b08625fdbf7c5d10b8995db5f6bb
3
+ size 258
industries/bundle/ncs1-native.blob ADDED
Binary file (512 Bytes). View file
 
industries/logistics.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "logistics",
3
+ "rules": {
4
+ "parcel": "\"parcel missing\" OR \"tracking stalled\"",
5
+ "address": "\"address mismatch\" OR \"postcode rejected\"",
6
+ "incident": "@parcel OR @address",
7
+ "ready": "@incident AND \"dispatch approved\" AND NOT (\"do not dispatch\" OR \"fraud review\")"
8
+ },
9
+ "answers": {"may_escalate": "@ready"},
10
+ "categories": {
11
+ "mixed_exception": "@parcel AND @address",
12
+ "parcel": "@parcel",
13
+ "address": "@address"
14
+ },
15
+ "actions": {
16
+ "review_shipment": "@ready AND @parcel AND @address",
17
+ "trace_parcel": "@ready AND @parcel",
18
+ "verify_address": "@ready AND @address"
19
+ }
20
+ }
industries/policies.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "logistics": "logistics.json",
3
+ "oncall": "../oncall.json"
4
+ }
industries/scenarios.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "logistics": {
3
+ "authorization": "dispatch approved",
4
+ "vetoes": ["do not dispatch", "fraud review"],
5
+ "cases": [
6
+ {"id": "carrier-trace", "text": "Carrier event: parcel missing. Dispatch approved.", "expected": {"answers": {"may_escalate": true}, "category": "parcel", "action": "trace_parcel"}},
7
+ {"id": "address-review", "text": "Postcode rejected by depot. Dispatch approved by shift lead.", "expected": {"answers": {"may_escalate": true}, "category": "address", "action": "verify_address"}},
8
+ {"id": "two-exceptions", "text": "Tracking stalled, with an address mismatch. Dispatch approved.", "expected": {"answers": {"may_escalate": true}, "category": "mixed_exception", "action": "review_shipment"}},
9
+ {"id": "await-approval", "text": "Tracking stalled. Awaiting the shift lead.", "expected": {"answers": {"may_escalate": false}, "category": "parcel", "action": null}},
10
+ {"id": "fraud-hold", "text": "Parcel missing. Dispatch approved. Fraud review opened.", "expected": {"answers": {"may_escalate": false}, "category": "parcel", "action": null}},
11
+ {"id": "non-exception", "text": "Dispatch approved. Parcel missingness is an unrelated dashboard label.", "expected": {"answers": {"may_escalate": false}, "category": null, "action": null}},
12
+ {"id": "archived-approval", "record": {"evidence": "Address mismatch. Current approval pending.", "history": "Dispatch approved yesterday."}, "expected": {"answers": {"may_escalate": false}, "category": "address", "action": null}},
13
+ {"id": "archived-hold", "record": {"evidence": "Parcel missing. Dispatch approved.", "history": "Do not dispatch the prior replacement."}, "expected": {"answers": {"may_escalate": true}, "category": "parcel", "action": "trace_parcel"}},
14
+ {"id": "late-hold", "context": {"start": "Parcel missing. Dispatch approved.", "end": "Do not dispatch."}, "expected": {"answers": {"may_escalate": false}, "category": "parcel", "action": null}}
15
+ ]
16
+ },
17
+ "oncall": {
18
+ "authorization": "paging approved",
19
+ "vetoes": ["maintenance window", "page cancelled"],
20
+ "cases": [
21
+ {"id": "network-page", "text": "Gateway unreachable. Paging approved by the duty lead.", "expected": {"answers": {"may_page": true}, "category": "network", "action": "page_network"}},
22
+ {"id": "capacity-page", "text": "Queue backed up. Workers saturated. Paging approved.", "expected": {"answers": {"may_page": true}, "category": "capacity", "action": "page_capacity"}},
23
+ {"id": "mixed-page", "text": "Connection reset and queue backed up. Paging approved.", "expected": {"answers": {"may_page": true}, "category": "mixed_incident", "action": "page_incident"}},
24
+ {"id": "uncorroborated-capacity", "text": "Queue backed up. Paging approved. Workers still have free slots.", "expected": {"answers": {"may_page": false}, "category": "capacity", "action": null}},
25
+ {"id": "planned-downtime", "text": "Gateway unreachable. Paging approved. Maintenance window in effect.", "expected": {"answers": {"may_page": false}, "category": "network", "action": null}},
26
+ {"id": "unrelated-event", "text": "Paging approved for a later drill. Service healthy at the moment.", "expected": {"answers": {"may_page": false}, "category": null, "action": null}},
27
+ {"id": "stale-paging-approval", "record": {"evidence": "Gateway unreachable. Paging awaiting a decision.", "history": "Paging approved for the prior incident."}, "expected": {"answers": {"may_page": false}, "category": "network", "action": null}},
28
+ {"id": "archived-maintenance", "record": {"evidence": "Connection reset. Paging approved.", "history": "Maintenance window ended two hours ago."}, "expected": {"answers": {"may_page": true}, "category": "network", "action": "page_network"}},
29
+ {"id": "late-cancel", "context": {"start": "Gateway unreachable. Paging approved.", "end": "Page cancelled."}, "expected": {"answers": {"may_page": false}, "category": "network", "action": null}}
30
+ ]
31
+ }
32
+ }
measurements/compact-release-vector-ncs1.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "magiceightball",
3
+ "backend": "MYRIAD",
4
+ "lane": "ncs1",
5
+ "toolchain": "2.1.2020.3.2-3506-c35b42b1d89-releases/2020/3",
6
+ "capacity": 128,
7
+ "onnx_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
8
+ "truth_table_cases": 128,
9
+ "repeats": 13,
10
+ "timing": {
11
+ "1": {
12
+ "ms_per_128_documents": {
13
+ "p50": 224.57980000000077,
14
+ "p95": 251.49375999999955,
15
+ "max": 261.4405
16
+ },
17
+ "device_requests": 128
18
+ },
19
+ "2": {
20
+ "ms_per_128_documents": {
21
+ "p50": 116.44149999999965,
22
+ "p95": 132.1755999999999,
23
+ "max": 138.87759999999983
24
+ },
25
+ "device_requests": 64
26
+ },
27
+ "8": {
28
+ "ms_per_128_documents": {
29
+ "p50": 32.472399999999624,
30
+ "p95": 43.04804000000022,
31
+ "max": 43.13360000000088
32
+ },
33
+ "device_requests": 16
34
+ },
35
+ "16": {
36
+ "ms_per_128_documents": {
37
+ "p50": 18.588199999999944,
38
+ "p95": 29.636939999999953,
39
+ "max": 35.988900000000434
40
+ },
41
+ "device_requests": 8
42
+ },
43
+ "32": {
44
+ "ms_per_128_documents": {
45
+ "p50": 13.821799999998774,
46
+ "p95": 19.4669000000001,
47
+ "max": 24.249499999999813
48
+ },
49
+ "device_requests": 4
50
+ },
51
+ "64": {
52
+ "ms_per_128_documents": {
53
+ "p50": 9.075100000000447,
54
+ "p95": 14.985800000000538,
55
+ "max": 15.713899999999725
56
+ },
57
+ "device_requests": 2
58
+ },
59
+ "128": {
60
+ "ms_per_128_documents": {
61
+ "p50": 7.594600000000007,
62
+ "p95": 10.528500000000207,
63
+ "max": 10.83600000000029
64
+ },
65
+ "device_requests": 1
66
+ }
67
+ },
68
+ "mixed_length_device_requests": 1,
69
+ "mixed_length_results": [
70
+ {
71
+ "id": "early",
72
+ "tokens": 131072,
73
+ "result": {
74
+ "answers": {
75
+ "may_route": true
76
+ },
77
+ "category": "billing",
78
+ "action": "review_billing"
79
+ },
80
+ "error": null
81
+ },
82
+ {
83
+ "id": "overflow",
84
+ "tokens": null,
85
+ "result": null,
86
+ "error": "Input has 131073 Needle tokens; maximum is 131072"
87
+ },
88
+ {
89
+ "id": "late",
90
+ "tokens": 131072,
91
+ "result": {
92
+ "answers": {
93
+ "may_route": true
94
+ },
95
+ "category": "delivery",
96
+ "action": "review_delivery"
97
+ },
98
+ "error": null
99
+ },
100
+ {
101
+ "id": "veto",
102
+ "tokens": 131072,
103
+ "result": {
104
+ "answers": {
105
+ "may_route": false
106
+ },
107
+ "category": "delivery",
108
+ "action": null
109
+ },
110
+ "error": null
111
+ },
112
+ {
113
+ "id": "empty",
114
+ "tokens": 0,
115
+ "result": {
116
+ "answers": {
117
+ "may_route": false
118
+ },
119
+ "category": null,
120
+ "action": null
121
+ },
122
+ "error": null
123
+ }
124
+ ],
125
+ "physical_usb_preflight": {
126
+ "stick": "ncs1",
127
+ "boot_usb_id": "03E7:2150"
128
+ },
129
+ "release_archive_bytes": 699,
130
+ "release_sha256": "1a8c1a021f62d89e236ebea379f9c69c9e4ffebe925c6bca49bb70df07d7cf61"
131
+ }
measurements/industry-simulation-cpu.json ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "simulated_cases": 18,
3
+ "matched_cases": 18,
4
+ "ungated_matched_cases": 11,
5
+ "expected_no_action_cases": 10,
6
+ "wrong_proposals": {
7
+ "magiceightball": 0,
8
+ "ungated": 7
9
+ },
10
+ "repeats": 15,
11
+ "workload_ms": {
12
+ "logistics-text": {
13
+ "p50": 0.5040999967604876,
14
+ "p95": 0.8582999929785726,
15
+ "max": 0.9989999234676361
16
+ },
17
+ "logistics-structured": {
18
+ "p50": 0.32270001247525215,
19
+ "p95": 0.5735299899242818,
20
+ "max": 0.5903999553993344
21
+ },
22
+ "logistics-full_context": {
23
+ "p50": 29.40570004284382,
24
+ "p95": 61.654259986244135,
25
+ "max": 66.11410004552454
26
+ },
27
+ "oncall-text": {
28
+ "p50": 0.7131000747904181,
29
+ "p95": 0.965509994421154,
30
+ "max": 1.1150999926030636
31
+ },
32
+ "oncall-structured": {
33
+ "p50": 0.7792001124471426,
34
+ "p95": 1.3064200873486695,
35
+ "max": 1.5076000709086657
36
+ },
37
+ "oncall-full_context": {
38
+ "p50": 32.79029997065663,
39
+ "p95": 55.77731996309012,
40
+ "max": 57.83770000562072
41
+ }
42
+ },
43
+ "cases": [
44
+ {
45
+ "vertical": "logistics",
46
+ "workload": "text",
47
+ "id": "carrier-trace",
48
+ "tokens": 15,
49
+ "expected": {
50
+ "answers": {
51
+ "may_escalate": true
52
+ },
53
+ "category": "parcel",
54
+ "action": "trace_parcel"
55
+ },
56
+ "actual": {
57
+ "answers": {
58
+ "may_escalate": true
59
+ },
60
+ "category": "parcel",
61
+ "action": "trace_parcel"
62
+ },
63
+ "ungated": {
64
+ "answers": {
65
+ "may_escalate": true
66
+ },
67
+ "category": "parcel",
68
+ "action": "trace_parcel"
69
+ }
70
+ },
71
+ {
72
+ "vertical": "logistics",
73
+ "workload": "text",
74
+ "id": "address-review",
75
+ "tokens": 18,
76
+ "expected": {
77
+ "answers": {
78
+ "may_escalate": true
79
+ },
80
+ "category": "address",
81
+ "action": "verify_address"
82
+ },
83
+ "actual": {
84
+ "answers": {
85
+ "may_escalate": true
86
+ },
87
+ "category": "address",
88
+ "action": "verify_address"
89
+ },
90
+ "ungated": {
91
+ "answers": {
92
+ "may_escalate": true
93
+ },
94
+ "category": "address",
95
+ "action": "verify_address"
96
+ }
97
+ },
98
+ {
99
+ "vertical": "logistics",
100
+ "workload": "text",
101
+ "id": "two-exceptions",
102
+ "tokens": 18,
103
+ "expected": {
104
+ "answers": {
105
+ "may_escalate": true
106
+ },
107
+ "category": "mixed_exception",
108
+ "action": "review_shipment"
109
+ },
110
+ "actual": {
111
+ "answers": {
112
+ "may_escalate": true
113
+ },
114
+ "category": "mixed_exception",
115
+ "action": "review_shipment"
116
+ },
117
+ "ungated": {
118
+ "answers": {
119
+ "may_escalate": true
120
+ },
121
+ "category": "mixed_exception",
122
+ "action": "review_shipment"
123
+ }
124
+ },
125
+ {
126
+ "vertical": "logistics",
127
+ "workload": "text",
128
+ "id": "await-approval",
129
+ "tokens": 14,
130
+ "expected": {
131
+ "answers": {
132
+ "may_escalate": false
133
+ },
134
+ "category": "parcel",
135
+ "action": null
136
+ },
137
+ "actual": {
138
+ "answers": {
139
+ "may_escalate": false
140
+ },
141
+ "category": "parcel",
142
+ "action": null
143
+ },
144
+ "ungated": {
145
+ "answers": {
146
+ "may_escalate": true
147
+ },
148
+ "category": "parcel",
149
+ "action": "trace_parcel"
150
+ }
151
+ },
152
+ {
153
+ "vertical": "logistics",
154
+ "workload": "text",
155
+ "id": "fraud-hold",
156
+ "tokens": 17,
157
+ "expected": {
158
+ "answers": {
159
+ "may_escalate": false
160
+ },
161
+ "category": "parcel",
162
+ "action": null
163
+ },
164
+ "actual": {
165
+ "answers": {
166
+ "may_escalate": false
167
+ },
168
+ "category": "parcel",
169
+ "action": null
170
+ },
171
+ "ungated": {
172
+ "answers": {
173
+ "may_escalate": true
174
+ },
175
+ "category": "parcel",
176
+ "action": "trace_parcel"
177
+ }
178
+ },
179
+ {
180
+ "vertical": "logistics",
181
+ "workload": "text",
182
+ "id": "non-exception",
183
+ "tokens": 19,
184
+ "expected": {
185
+ "answers": {
186
+ "may_escalate": false
187
+ },
188
+ "category": null,
189
+ "action": null
190
+ },
191
+ "actual": {
192
+ "answers": {
193
+ "may_escalate": false
194
+ },
195
+ "category": null,
196
+ "action": null
197
+ },
198
+ "ungated": {
199
+ "answers": {
200
+ "may_escalate": false
201
+ },
202
+ "category": null,
203
+ "action": null
204
+ }
205
+ },
206
+ {
207
+ "vertical": "logistics",
208
+ "workload": "structured",
209
+ "id": "archived-approval",
210
+ "tokens": 31,
211
+ "expected": {
212
+ "answers": {
213
+ "may_escalate": false
214
+ },
215
+ "category": "address",
216
+ "action": null
217
+ },
218
+ "actual": {
219
+ "answers": {
220
+ "may_escalate": false
221
+ },
222
+ "category": "address",
223
+ "action": null
224
+ },
225
+ "ungated": {
226
+ "answers": {
227
+ "may_escalate": true
228
+ },
229
+ "category": "address",
230
+ "action": "verify_address"
231
+ }
232
+ },
233
+ {
234
+ "vertical": "logistics",
235
+ "workload": "structured",
236
+ "id": "archived-hold",
237
+ "tokens": 31,
238
+ "expected": {
239
+ "answers": {
240
+ "may_escalate": true
241
+ },
242
+ "category": "parcel",
243
+ "action": "trace_parcel"
244
+ },
245
+ "actual": {
246
+ "answers": {
247
+ "may_escalate": true
248
+ },
249
+ "category": "parcel",
250
+ "action": "trace_parcel"
251
+ },
252
+ "ungated": {
253
+ "answers": {
254
+ "may_escalate": true
255
+ },
256
+ "category": "parcel",
257
+ "action": "trace_parcel"
258
+ }
259
+ },
260
+ {
261
+ "vertical": "logistics",
262
+ "workload": "full_context",
263
+ "id": "late-hold",
264
+ "tokens": 131072,
265
+ "expected": {
266
+ "answers": {
267
+ "may_escalate": false
268
+ },
269
+ "category": "parcel",
270
+ "action": null
271
+ },
272
+ "actual": {
273
+ "answers": {
274
+ "may_escalate": false
275
+ },
276
+ "category": "parcel",
277
+ "action": null
278
+ },
279
+ "ungated": {
280
+ "answers": {
281
+ "may_escalate": true
282
+ },
283
+ "category": "parcel",
284
+ "action": "trace_parcel"
285
+ }
286
+ },
287
+ {
288
+ "vertical": "oncall",
289
+ "workload": "text",
290
+ "id": "network-page",
291
+ "tokens": 18,
292
+ "expected": {
293
+ "answers": {
294
+ "may_page": true
295
+ },
296
+ "category": "network",
297
+ "action": "page_network"
298
+ },
299
+ "actual": {
300
+ "answers": {
301
+ "may_page": true
302
+ },
303
+ "category": "network",
304
+ "action": "page_network"
305
+ },
306
+ "ungated": {
307
+ "answers": {
308
+ "may_page": true
309
+ },
310
+ "category": "network",
311
+ "action": "page_network"
312
+ }
313
+ },
314
+ {
315
+ "vertical": "oncall",
316
+ "workload": "text",
317
+ "id": "capacity-page",
318
+ "tokens": 18,
319
+ "expected": {
320
+ "answers": {
321
+ "may_page": true
322
+ },
323
+ "category": "capacity",
324
+ "action": "page_capacity"
325
+ },
326
+ "actual": {
327
+ "answers": {
328
+ "may_page": true
329
+ },
330
+ "category": "capacity",
331
+ "action": "page_capacity"
332
+ },
333
+ "ungated": {
334
+ "answers": {
335
+ "may_page": true
336
+ },
337
+ "category": "capacity",
338
+ "action": "page_capacity"
339
+ }
340
+ },
341
+ {
342
+ "vertical": "oncall",
343
+ "workload": "text",
344
+ "id": "mixed-page",
345
+ "tokens": 17,
346
+ "expected": {
347
+ "answers": {
348
+ "may_page": true
349
+ },
350
+ "category": "mixed_incident",
351
+ "action": "page_incident"
352
+ },
353
+ "actual": {
354
+ "answers": {
355
+ "may_page": true
356
+ },
357
+ "category": "mixed_incident",
358
+ "action": "page_incident"
359
+ },
360
+ "ungated": {
361
+ "answers": {
362
+ "may_page": true
363
+ },
364
+ "category": "mixed_incident",
365
+ "action": "page_incident"
366
+ }
367
+ },
368
+ {
369
+ "vertical": "oncall",
370
+ "workload": "text",
371
+ "id": "uncorroborated-capacity",
372
+ "tokens": 20,
373
+ "expected": {
374
+ "answers": {
375
+ "may_page": false
376
+ },
377
+ "category": "capacity",
378
+ "action": null
379
+ },
380
+ "actual": {
381
+ "answers": {
382
+ "may_page": false
383
+ },
384
+ "category": "capacity",
385
+ "action": null
386
+ },
387
+ "ungated": {
388
+ "answers": {
389
+ "may_page": false
390
+ },
391
+ "category": "capacity",
392
+ "action": null
393
+ }
394
+ },
395
+ {
396
+ "vertical": "oncall",
397
+ "workload": "text",
398
+ "id": "planned-downtime",
399
+ "tokens": 20,
400
+ "expected": {
401
+ "answers": {
402
+ "may_page": false
403
+ },
404
+ "category": "network",
405
+ "action": null
406
+ },
407
+ "actual": {
408
+ "answers": {
409
+ "may_page": false
410
+ },
411
+ "category": "network",
412
+ "action": null
413
+ },
414
+ "ungated": {
415
+ "answers": {
416
+ "may_page": true
417
+ },
418
+ "category": "network",
419
+ "action": "page_network"
420
+ }
421
+ },
422
+ {
423
+ "vertical": "oncall",
424
+ "workload": "text",
425
+ "id": "unrelated-event",
426
+ "tokens": 17,
427
+ "expected": {
428
+ "answers": {
429
+ "may_page": false
430
+ },
431
+ "category": null,
432
+ "action": null
433
+ },
434
+ "actual": {
435
+ "answers": {
436
+ "may_page": false
437
+ },
438
+ "category": null,
439
+ "action": null
440
+ },
441
+ "ungated": {
442
+ "answers": {
443
+ "may_page": false
444
+ },
445
+ "category": null,
446
+ "action": null
447
+ }
448
+ },
449
+ {
450
+ "vertical": "oncall",
451
+ "workload": "structured",
452
+ "id": "stale-paging-approval",
453
+ "tokens": 36,
454
+ "expected": {
455
+ "answers": {
456
+ "may_page": false
457
+ },
458
+ "category": "network",
459
+ "action": null
460
+ },
461
+ "actual": {
462
+ "answers": {
463
+ "may_page": false
464
+ },
465
+ "category": "network",
466
+ "action": null
467
+ },
468
+ "ungated": {
469
+ "answers": {
470
+ "may_page": true
471
+ },
472
+ "category": "network",
473
+ "action": "page_network"
474
+ }
475
+ },
476
+ {
477
+ "vertical": "oncall",
478
+ "workload": "structured",
479
+ "id": "archived-maintenance",
480
+ "tokens": 32,
481
+ "expected": {
482
+ "answers": {
483
+ "may_page": true
484
+ },
485
+ "category": "network",
486
+ "action": "page_network"
487
+ },
488
+ "actual": {
489
+ "answers": {
490
+ "may_page": true
491
+ },
492
+ "category": "network",
493
+ "action": "page_network"
494
+ },
495
+ "ungated": {
496
+ "answers": {
497
+ "may_page": true
498
+ },
499
+ "category": "network",
500
+ "action": "page_network"
501
+ }
502
+ },
503
+ {
504
+ "vertical": "oncall",
505
+ "workload": "full_context",
506
+ "id": "late-cancel",
507
+ "tokens": 131072,
508
+ "expected": {
509
+ "answers": {
510
+ "may_page": false
511
+ },
512
+ "category": "network",
513
+ "action": null
514
+ },
515
+ "actual": {
516
+ "answers": {
517
+ "may_page": false
518
+ },
519
+ "category": "network",
520
+ "action": null
521
+ },
522
+ "ungated": {
523
+ "answers": {
524
+ "may_page": true
525
+ },
526
+ "category": "network",
527
+ "action": "page_network"
528
+ }
529
+ }
530
+ ],
531
+ "backend": "CPU",
532
+ "physical_usb_preflight": null,
533
+ "runtime": "2022.3.1-9227-cf2c7da5689-releases/2022/3",
534
+ "onnx_sha256": "72481bf69d70da97d0d0055c02f555ef2bd6b08625fdbf7c5d10b8995db5f6bb",
535
+ "scenario_sha256": "9b0777ab4e45f0ba6f5eed0d28e1fba3afc725436c844f3b41c868b8a8910b04",
536
+ "corpus_sha256": "48e0522844402a86a3ea98f0947ba85ea54838db3c59022299298ed968a5a163",
537
+ "evidence_type": "hand-authored simulation",
538
+ "manifest_sha256": "7aafb73515f9dc25afe8b2a4dc58ac431cd5f4816aa93d3919b0cecbb648e269"
539
+ }
measurements/industry-simulation-ncs1.json ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "simulated_cases": 18,
3
+ "matched_cases": 18,
4
+ "ungated_matched_cases": 11,
5
+ "expected_no_action_cases": 10,
6
+ "wrong_proposals": {
7
+ "magiceightball": 0,
8
+ "ungated": 7
9
+ },
10
+ "repeats": 15,
11
+ "workload_ms": {
12
+ "logistics-text": {
13
+ "p50": 1.9835999999999743,
14
+ "p95": 2.188110000000254,
15
+ "max": 2.300599999999875
16
+ },
17
+ "logistics-structured": {
18
+ "p50": 1.9295999999995317,
19
+ "p95": 2.331220000000034,
20
+ "max": 2.516299999999916
21
+ },
22
+ "logistics-full_context": {
23
+ "p50": 35.86040000000068,
24
+ "p95": 64.58602999999997,
25
+ "max": 73.0700999999998
26
+ },
27
+ "oncall-text": {
28
+ "p50": 2.265999999999657,
29
+ "p95": 2.7947999999996753,
30
+ "max": 2.8815999999993736
31
+ },
32
+ "oncall-structured": {
33
+ "p50": 2.1626000000001255,
34
+ "p95": 2.5457299999997574,
35
+ "max": 2.729200000000098
36
+ },
37
+ "oncall-full_context": {
38
+ "p50": 34.86110000000053,
39
+ "p95": 64.56761000000044,
40
+ "max": 80.89979999999919
41
+ }
42
+ },
43
+ "cases": [
44
+ {
45
+ "vertical": "logistics",
46
+ "workload": "text",
47
+ "id": "carrier-trace",
48
+ "tokens": 15,
49
+ "expected": {
50
+ "answers": {
51
+ "may_escalate": true
52
+ },
53
+ "category": "parcel",
54
+ "action": "trace_parcel"
55
+ },
56
+ "actual": {
57
+ "answers": {
58
+ "may_escalate": true
59
+ },
60
+ "category": "parcel",
61
+ "action": "trace_parcel"
62
+ },
63
+ "ungated": {
64
+ "answers": {
65
+ "may_escalate": true
66
+ },
67
+ "category": "parcel",
68
+ "action": "trace_parcel"
69
+ }
70
+ },
71
+ {
72
+ "vertical": "logistics",
73
+ "workload": "text",
74
+ "id": "address-review",
75
+ "tokens": 18,
76
+ "expected": {
77
+ "answers": {
78
+ "may_escalate": true
79
+ },
80
+ "category": "address",
81
+ "action": "verify_address"
82
+ },
83
+ "actual": {
84
+ "answers": {
85
+ "may_escalate": true
86
+ },
87
+ "category": "address",
88
+ "action": "verify_address"
89
+ },
90
+ "ungated": {
91
+ "answers": {
92
+ "may_escalate": true
93
+ },
94
+ "category": "address",
95
+ "action": "verify_address"
96
+ }
97
+ },
98
+ {
99
+ "vertical": "logistics",
100
+ "workload": "text",
101
+ "id": "two-exceptions",
102
+ "tokens": 18,
103
+ "expected": {
104
+ "answers": {
105
+ "may_escalate": true
106
+ },
107
+ "category": "mixed_exception",
108
+ "action": "review_shipment"
109
+ },
110
+ "actual": {
111
+ "answers": {
112
+ "may_escalate": true
113
+ },
114
+ "category": "mixed_exception",
115
+ "action": "review_shipment"
116
+ },
117
+ "ungated": {
118
+ "answers": {
119
+ "may_escalate": true
120
+ },
121
+ "category": "mixed_exception",
122
+ "action": "review_shipment"
123
+ }
124
+ },
125
+ {
126
+ "vertical": "logistics",
127
+ "workload": "text",
128
+ "id": "await-approval",
129
+ "tokens": 14,
130
+ "expected": {
131
+ "answers": {
132
+ "may_escalate": false
133
+ },
134
+ "category": "parcel",
135
+ "action": null
136
+ },
137
+ "actual": {
138
+ "answers": {
139
+ "may_escalate": false
140
+ },
141
+ "category": "parcel",
142
+ "action": null
143
+ },
144
+ "ungated": {
145
+ "answers": {
146
+ "may_escalate": true
147
+ },
148
+ "category": "parcel",
149
+ "action": "trace_parcel"
150
+ }
151
+ },
152
+ {
153
+ "vertical": "logistics",
154
+ "workload": "text",
155
+ "id": "fraud-hold",
156
+ "tokens": 17,
157
+ "expected": {
158
+ "answers": {
159
+ "may_escalate": false
160
+ },
161
+ "category": "parcel",
162
+ "action": null
163
+ },
164
+ "actual": {
165
+ "answers": {
166
+ "may_escalate": false
167
+ },
168
+ "category": "parcel",
169
+ "action": null
170
+ },
171
+ "ungated": {
172
+ "answers": {
173
+ "may_escalate": true
174
+ },
175
+ "category": "parcel",
176
+ "action": "trace_parcel"
177
+ }
178
+ },
179
+ {
180
+ "vertical": "logistics",
181
+ "workload": "text",
182
+ "id": "non-exception",
183
+ "tokens": 19,
184
+ "expected": {
185
+ "answers": {
186
+ "may_escalate": false
187
+ },
188
+ "category": null,
189
+ "action": null
190
+ },
191
+ "actual": {
192
+ "answers": {
193
+ "may_escalate": false
194
+ },
195
+ "category": null,
196
+ "action": null
197
+ },
198
+ "ungated": {
199
+ "answers": {
200
+ "may_escalate": false
201
+ },
202
+ "category": null,
203
+ "action": null
204
+ }
205
+ },
206
+ {
207
+ "vertical": "logistics",
208
+ "workload": "structured",
209
+ "id": "archived-approval",
210
+ "tokens": 31,
211
+ "expected": {
212
+ "answers": {
213
+ "may_escalate": false
214
+ },
215
+ "category": "address",
216
+ "action": null
217
+ },
218
+ "actual": {
219
+ "answers": {
220
+ "may_escalate": false
221
+ },
222
+ "category": "address",
223
+ "action": null
224
+ },
225
+ "ungated": {
226
+ "answers": {
227
+ "may_escalate": true
228
+ },
229
+ "category": "address",
230
+ "action": "verify_address"
231
+ }
232
+ },
233
+ {
234
+ "vertical": "logistics",
235
+ "workload": "structured",
236
+ "id": "archived-hold",
237
+ "tokens": 31,
238
+ "expected": {
239
+ "answers": {
240
+ "may_escalate": true
241
+ },
242
+ "category": "parcel",
243
+ "action": "trace_parcel"
244
+ },
245
+ "actual": {
246
+ "answers": {
247
+ "may_escalate": true
248
+ },
249
+ "category": "parcel",
250
+ "action": "trace_parcel"
251
+ },
252
+ "ungated": {
253
+ "answers": {
254
+ "may_escalate": true
255
+ },
256
+ "category": "parcel",
257
+ "action": "trace_parcel"
258
+ }
259
+ },
260
+ {
261
+ "vertical": "logistics",
262
+ "workload": "full_context",
263
+ "id": "late-hold",
264
+ "tokens": 131072,
265
+ "expected": {
266
+ "answers": {
267
+ "may_escalate": false
268
+ },
269
+ "category": "parcel",
270
+ "action": null
271
+ },
272
+ "actual": {
273
+ "answers": {
274
+ "may_escalate": false
275
+ },
276
+ "category": "parcel",
277
+ "action": null
278
+ },
279
+ "ungated": {
280
+ "answers": {
281
+ "may_escalate": true
282
+ },
283
+ "category": "parcel",
284
+ "action": "trace_parcel"
285
+ }
286
+ },
287
+ {
288
+ "vertical": "oncall",
289
+ "workload": "text",
290
+ "id": "network-page",
291
+ "tokens": 18,
292
+ "expected": {
293
+ "answers": {
294
+ "may_page": true
295
+ },
296
+ "category": "network",
297
+ "action": "page_network"
298
+ },
299
+ "actual": {
300
+ "answers": {
301
+ "may_page": true
302
+ },
303
+ "category": "network",
304
+ "action": "page_network"
305
+ },
306
+ "ungated": {
307
+ "answers": {
308
+ "may_page": true
309
+ },
310
+ "category": "network",
311
+ "action": "page_network"
312
+ }
313
+ },
314
+ {
315
+ "vertical": "oncall",
316
+ "workload": "text",
317
+ "id": "capacity-page",
318
+ "tokens": 18,
319
+ "expected": {
320
+ "answers": {
321
+ "may_page": true
322
+ },
323
+ "category": "capacity",
324
+ "action": "page_capacity"
325
+ },
326
+ "actual": {
327
+ "answers": {
328
+ "may_page": true
329
+ },
330
+ "category": "capacity",
331
+ "action": "page_capacity"
332
+ },
333
+ "ungated": {
334
+ "answers": {
335
+ "may_page": true
336
+ },
337
+ "category": "capacity",
338
+ "action": "page_capacity"
339
+ }
340
+ },
341
+ {
342
+ "vertical": "oncall",
343
+ "workload": "text",
344
+ "id": "mixed-page",
345
+ "tokens": 17,
346
+ "expected": {
347
+ "answers": {
348
+ "may_page": true
349
+ },
350
+ "category": "mixed_incident",
351
+ "action": "page_incident"
352
+ },
353
+ "actual": {
354
+ "answers": {
355
+ "may_page": true
356
+ },
357
+ "category": "mixed_incident",
358
+ "action": "page_incident"
359
+ },
360
+ "ungated": {
361
+ "answers": {
362
+ "may_page": true
363
+ },
364
+ "category": "mixed_incident",
365
+ "action": "page_incident"
366
+ }
367
+ },
368
+ {
369
+ "vertical": "oncall",
370
+ "workload": "text",
371
+ "id": "uncorroborated-capacity",
372
+ "tokens": 20,
373
+ "expected": {
374
+ "answers": {
375
+ "may_page": false
376
+ },
377
+ "category": "capacity",
378
+ "action": null
379
+ },
380
+ "actual": {
381
+ "answers": {
382
+ "may_page": false
383
+ },
384
+ "category": "capacity",
385
+ "action": null
386
+ },
387
+ "ungated": {
388
+ "answers": {
389
+ "may_page": false
390
+ },
391
+ "category": "capacity",
392
+ "action": null
393
+ }
394
+ },
395
+ {
396
+ "vertical": "oncall",
397
+ "workload": "text",
398
+ "id": "planned-downtime",
399
+ "tokens": 20,
400
+ "expected": {
401
+ "answers": {
402
+ "may_page": false
403
+ },
404
+ "category": "network",
405
+ "action": null
406
+ },
407
+ "actual": {
408
+ "answers": {
409
+ "may_page": false
410
+ },
411
+ "category": "network",
412
+ "action": null
413
+ },
414
+ "ungated": {
415
+ "answers": {
416
+ "may_page": true
417
+ },
418
+ "category": "network",
419
+ "action": "page_network"
420
+ }
421
+ },
422
+ {
423
+ "vertical": "oncall",
424
+ "workload": "text",
425
+ "id": "unrelated-event",
426
+ "tokens": 17,
427
+ "expected": {
428
+ "answers": {
429
+ "may_page": false
430
+ },
431
+ "category": null,
432
+ "action": null
433
+ },
434
+ "actual": {
435
+ "answers": {
436
+ "may_page": false
437
+ },
438
+ "category": null,
439
+ "action": null
440
+ },
441
+ "ungated": {
442
+ "answers": {
443
+ "may_page": false
444
+ },
445
+ "category": null,
446
+ "action": null
447
+ }
448
+ },
449
+ {
450
+ "vertical": "oncall",
451
+ "workload": "structured",
452
+ "id": "stale-paging-approval",
453
+ "tokens": 36,
454
+ "expected": {
455
+ "answers": {
456
+ "may_page": false
457
+ },
458
+ "category": "network",
459
+ "action": null
460
+ },
461
+ "actual": {
462
+ "answers": {
463
+ "may_page": false
464
+ },
465
+ "category": "network",
466
+ "action": null
467
+ },
468
+ "ungated": {
469
+ "answers": {
470
+ "may_page": true
471
+ },
472
+ "category": "network",
473
+ "action": "page_network"
474
+ }
475
+ },
476
+ {
477
+ "vertical": "oncall",
478
+ "workload": "structured",
479
+ "id": "archived-maintenance",
480
+ "tokens": 32,
481
+ "expected": {
482
+ "answers": {
483
+ "may_page": true
484
+ },
485
+ "category": "network",
486
+ "action": "page_network"
487
+ },
488
+ "actual": {
489
+ "answers": {
490
+ "may_page": true
491
+ },
492
+ "category": "network",
493
+ "action": "page_network"
494
+ },
495
+ "ungated": {
496
+ "answers": {
497
+ "may_page": true
498
+ },
499
+ "category": "network",
500
+ "action": "page_network"
501
+ }
502
+ },
503
+ {
504
+ "vertical": "oncall",
505
+ "workload": "full_context",
506
+ "id": "late-cancel",
507
+ "tokens": 131072,
508
+ "expected": {
509
+ "answers": {
510
+ "may_page": false
511
+ },
512
+ "category": "network",
513
+ "action": null
514
+ },
515
+ "actual": {
516
+ "answers": {
517
+ "may_page": false
518
+ },
519
+ "category": "network",
520
+ "action": null
521
+ },
522
+ "ungated": {
523
+ "answers": {
524
+ "may_page": true
525
+ },
526
+ "category": "network",
527
+ "action": "page_network"
528
+ }
529
+ }
530
+ ],
531
+ "backend": "MYRIAD",
532
+ "physical_usb_preflight": {
533
+ "stick": "ncs1",
534
+ "boot_usb_id": "03E7:2150"
535
+ },
536
+ "runtime": "2.1.2020.3.2-3506-c35b42b1d89-releases/2020/3",
537
+ "onnx_sha256": "72481bf69d70da97d0d0055c02f555ef2bd6b08625fdbf7c5d10b8995db5f6bb",
538
+ "scenario_sha256": "9b0777ab4e45f0ba6f5eed0d28e1fba3afc725436c844f3b41c868b8a8910b04",
539
+ "corpus_sha256": "48e0522844402a86a3ea98f0947ba85ea54838db3c59022299298ed968a5a163",
540
+ "evidence_type": "hand-authored simulation",
541
+ "manifest_sha256": "7aafb73515f9dc25afe8b2a4dc58ac431cd5f4816aa93d3919b0cecbb648e269",
542
+ "native_blob_sha256": "fdbe4ace9b7d936db8da5a2daa11262e44c4ffad35336f0090683d60c7966c34"
543
+ }
oncall.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "oncall",
3
+ "rules": {
4
+ "network": "\"gateway unreachable\" OR \"connection reset\"",
5
+ "capacity": "\"queue backed up\" OR \"workers saturated\"",
6
+ "confirmed": "@network OR (\"queue backed up\" AND \"workers saturated\")",
7
+ "ready": "@confirmed AND \"paging approved\" AND NOT (\"maintenance window\" OR \"page cancelled\")"
8
+ },
9
+ "answers": {"may_page": "@ready"},
10
+ "categories": {
11
+ "mixed_incident": "@network AND @capacity",
12
+ "network": "@network",
13
+ "capacity": "@capacity"
14
+ },
15
+ "actions": {
16
+ "page_incident": "@ready AND @network AND @capacity",
17
+ "page_network": "@ready AND @network",
18
+ "page_capacity": "@ready AND @capacity"
19
+ }
20
+ }
release.py CHANGED
@@ -5,7 +5,7 @@ from pathlib import Path
5
  import struct
6
  import zlib
7
 
8
- from blob_layout import inspect_blob
9
 
10
 
11
  MAGIC = b"M8B1"
@@ -21,18 +21,23 @@ def _validate(manifest, blobs):
21
  shape = inputs.get("features") if isinstance(inputs, dict) else None
22
  if not isinstance(shape, list) or len(shape) != 1 or type(shape[0]) is not int or shape[0] < 1:
23
  raise ValueError("Release has invalid Gather geometry")
24
- for blob in blobs.values():
25
- layout = inspect_blob(blob)
 
26
  if (layout["input_bytes"] != shape[0] * 4 or layout["output_bytes"] != shape[0] * 2
27
  or layout["stage_count"] != 1 or layout["sole_stage"]["type"] != 100):
28
  raise ValueError("Native Gather blob does not match the release geometry")
29
 
30
 
31
- def pack_bundle(directory):
32
  manifest = (directory / "model.json").read_bytes()
33
  blobs = {stick: (directory / filename).read_bytes()
34
  for stick, (filename, _) in TARGETS.items()}
35
- _validate(json.loads(manifest), blobs)
 
 
 
 
36
  fields = (manifest, blobs["ncs1"], blobs["ncs2"])
37
  return zlib.compress(HEADER.pack(MAGIC, *(len(field) for field in fields)) + b"".join(fields), 9)
38
 
@@ -59,7 +64,8 @@ if __name__ == "__main__":
59
  parser = argparse.ArgumentParser(description=__doc__)
60
  parser.add_argument("bundle", type=Path)
61
  parser.add_argument("output", type=Path)
 
62
  args = parser.parse_args()
63
- archive = pack_bundle(args.bundle)
64
  args.output.write_bytes(archive)
65
  print("%d bytes" % len(archive))
 
5
  import struct
6
  import zlib
7
 
8
+ from blob_layout import compact_gather_blob, inspect_blob
9
 
10
 
11
  MAGIC = b"M8B1"
 
21
  shape = inputs.get("features") if isinstance(inputs, dict) else None
22
  if not isinstance(shape, list) or len(shape) != 1 or type(shape[0]) is not int or shape[0] < 1:
23
  raise ValueError("Release has invalid Gather geometry")
24
+ for stick, blob in blobs.items():
25
+ count = manifest.get("fp16_coefficient_bytes") if stick == "ncs1" else None
26
+ layout = inspect_blob(blob, compact_coefficients=count)
27
  if (layout["input_bytes"] != shape[0] * 4 or layout["output_bytes"] != shape[0] * 2
28
  or layout["stage_count"] != 1 or layout["sole_stage"]["type"] != 100):
29
  raise ValueError("Native Gather blob does not match the release geometry")
30
 
31
 
32
+ def pack_bundle(directory, compact_ncs1=False):
33
  manifest = (directory / "model.json").read_bytes()
34
  blobs = {stick: (directory / filename).read_bytes()
35
  for stick, (filename, _) in TARGETS.items()}
36
+ model = json.loads(manifest)
37
+ _validate(model, blobs)
38
+ if compact_ncs1:
39
+ blobs["ncs1"] = compact_gather_blob(blobs["ncs1"], model.get("fp16_coefficient_bytes"))
40
+ manifest = json.dumps(model, ensure_ascii=False, separators=(",", ":")).encode("utf8")
41
  fields = (manifest, blobs["ncs1"], blobs["ncs2"])
42
  return zlib.compress(HEADER.pack(MAGIC, *(len(field) for field in fields)) + b"".join(fields), 9)
43
 
 
64
  parser = argparse.ArgumentParser(description=__doc__)
65
  parser.add_argument("bundle", type=Path)
66
  parser.add_argument("output", type=Path)
67
+ parser.add_argument("--compact-ncs1", action="store_true", help="Remove verified NCS1 terminal zero padding")
68
  args = parser.parse_args()
69
+ archive = pack_bundle(args.bundle, args.compact_ncs1)
70
  args.output.write_bytes(archive)
71
  print("%d bytes" % len(archive))
simulate_industries.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay labeled industry scenarios on the resident CPU or NCS1 model."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import time
8
+
9
+ from adaptive import AdaptiveRuntime, Profiles
10
+ from benchmark import CORPUS_SHA, exact_document, quantiles
11
+ from benchmark_batch_heads import windows_usb_identity
12
+ from benchmark_stream import cpu_control
13
+ from policy import LIMIT
14
+ from runtime import Runtime
15
+
16
+
17
+ SCENARIOS = Path(__file__).with_name("industries") / "scenarios.json"
18
+
19
+
20
+ def evaluate(engine, corpus, scenarios, repeats):
21
+ payload = corpus.read_bytes()
22
+ if hashlib.sha256(payload).hexdigest() != CORPUS_SHA:
23
+ raise ValueError("Unexpected benchmark corpus")
24
+ source = engine.tokenizer.encode(payload.decode("utf-8-sig"), out_type=int)
25
+ groups, controls = {}, {}
26
+ for bank, suite in scenarios.items():
27
+ policy = engine.policy_view(bank).policy
28
+ auth = tuple(suite["authorization"].split())
29
+ vetoes = {tuple(phrase.split()) for phrase in suite["vetoes"]}
30
+ for case in suite["cases"]:
31
+ if "record" in case:
32
+ kind = "structured"
33
+ evidence = case["record"]["evidence"]
34
+ text = json.dumps(case["record"], ensure_ascii=False)
35
+ elif "context" in case:
36
+ kind = "full_context"
37
+ evidence = text = exact_document(engine.tokenizer, source, LIMIT, **case["context"])
38
+ else:
39
+ kind = "text"
40
+ evidence = text = case["text"]
41
+ key = (bank, kind)
42
+ groups.setdefault(key, []).append(dict(id=case["id"], text=text, expected=case["expected"]))
43
+
44
+ # Keep the classifier and corroboration rules. Remove only the
45
+ # approval and hold requirements to measure an ungated baseline.
46
+ facts = policy.text_atoms(evidence)
47
+ for index, phrase in enumerate(policy.literals):
48
+ if phrase == auth:
49
+ facts[index] = 1
50
+ elif phrase in vetoes:
51
+ facts[index] = 0
52
+ controls[case["id"]] = policy.result(policy.reference(facts))
53
+
54
+ keys = {bank + "-" + kind: (bank, kind) for bank, kind in groups}
55
+ factory = lambda: engine
56
+ profiles = Profiles()
57
+ try:
58
+ runner = AdaptiveRuntime({key: factory for key in keys}, profiles,
59
+ scopes={key: "evidence" for key, (_, kind) in keys.items() if kind == "structured"},
60
+ banks={key: bank for key, (bank, _) in keys.items()})
61
+ results, timings = [], {}
62
+ for vertical, (bank, kind) in keys.items():
63
+ batch = {"vertical": vertical, "documents": groups[bank, kind]}
64
+ elapsed = []
65
+ for repeat in range(repeats + 4):
66
+ started = time.perf_counter()
67
+ output = runner.batch(batch)
68
+ duration = (time.perf_counter() - started) * 1000
69
+ if repeat >= 4:
70
+ elapsed.append(duration)
71
+ if output["device_requests"] != 1 or len(output["documents"]) != len(batch["documents"]):
72
+ raise AssertionError("Unexpected inference grouping for " + vertical)
73
+ for sent, observed in zip(batch["documents"], output["documents"]):
74
+ if observed.get("id") != sent["id"] or observed.get("result") != sent["expected"]:
75
+ raise AssertionError("Fixture failed: %s: %s" % (sent["id"], observed))
76
+ if kind == "full_context" and observed["needle_tokens"] != LIMIT:
77
+ raise AssertionError("Context fixture did not reach the token limit")
78
+ for sent, observed in zip(batch["documents"], output["documents"]):
79
+ results.append(dict(vertical=bank, workload=kind, id=sent["id"],
80
+ tokens=observed["needle_tokens"], expected=sent["expected"],
81
+ actual=observed["result"], ungated=controls[sent["id"]]))
82
+ timings[vertical] = quantiles(elapsed)
83
+ finally:
84
+ profiles.close()
85
+
86
+ blocked = [row for row in results if row["expected"]["action"] is None]
87
+ return {"simulated_cases": len(results), "matched_cases": len(results),
88
+ "ungated_matched_cases": sum(row["ungated"] == row["expected"] for row in results),
89
+ "expected_no_action_cases": len(blocked),
90
+ "wrong_proposals": {"magiceightball": 0, "ungated": sum(row["ungated"]["action"] is not None
91
+ for row in blocked)},
92
+ "repeats": repeats, "workload_ms": timings,
93
+ "cases": results}
94
+
95
+
96
+ def main():
97
+ parser = argparse.ArgumentParser(description=__doc__)
98
+ parser.add_argument("bundle", type=Path)
99
+ parser.add_argument("--backend", choices=("cpu", "ncs1"), default="cpu")
100
+ parser.add_argument("--blob", type=Path)
101
+ parser.add_argument("--toolchain", type=Path)
102
+ parser.add_argument("--scenarios", type=Path, default=SCENARIOS)
103
+ parser.add_argument("--corpus", type=Path, required=True)
104
+ parser.add_argument("--output", type=Path, required=True)
105
+ parser.add_argument("--repeats", type=int, default=15)
106
+ args = parser.parse_args()
107
+ if args.repeats < 1 or (args.backend == "cpu" and args.blob):
108
+ parser.error("Repeats must be positive and a native blob requires --backend ncs1")
109
+ physical = windows_usb_identity("ncs1") if args.backend == "ncs1" else None
110
+ engine = Runtime(args.bundle, args.toolchain, blob=args.blob) if physical else cpu_control(args.bundle)
111
+ cases = args.scenarios.read_bytes()
112
+ report = evaluate(engine, args.corpus, json.loads(cases), args.repeats)
113
+ report.update(backend=engine.target, physical_usb_preflight=physical, runtime=engine.openvino_version,
114
+ onnx_sha256=engine.info["onnx_sha256"], scenario_sha256=hashlib.sha256(cases).hexdigest(),
115
+ manifest_sha256=hashlib.sha256((args.bundle / "model.json").read_bytes()).hexdigest(),
116
+ corpus_sha256=CORPUS_SHA, evidence_type="hand-authored simulation")
117
+ if args.blob:
118
+ report["native_blob_sha256"] = hashlib.sha256(args.blob.read_bytes()).hexdigest()
119
+ args.output.parent.mkdir(parents=True, exist_ok=True)
120
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf8")
121
+ print(json.dumps({name: report[name] for name in ("backend", "simulated_cases", "wrong_proposals")}))
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
supervisor.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bound native driver stalls by supervising the batch worker's JSONL pipe."""
2
+ import json
3
+ import os
4
+ from queue import Empty, Queue
5
+ import subprocess
6
+ from threading import Thread
7
+
8
+
9
+ class BatchWorker:
10
+ def __init__(self, command):
11
+ self.child = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
12
+ self.requests = Queue()
13
+ self.responses = Queue()
14
+ self.thread = Thread(target=self.exchange, daemon=True)
15
+ self.thread.start()
16
+
17
+ def exchange(self):
18
+ try:
19
+ with self.child.stdin as request_pipe, self.child.stdout as response_pipe:
20
+ while True:
21
+ request = self.requests.get()
22
+ if request is None:
23
+ return
24
+ request_pipe.write(request if request.endswith(b"\n") else request + b"\n")
25
+ request_pipe.flush()
26
+ reply = response_pipe.readline()
27
+ if not reply:
28
+ break
29
+ self.responses.put(reply)
30
+ except OSError:
31
+ pass
32
+ self.responses.put(None)
33
+
34
+ def request(self, raw, timeout):
35
+ self.requests.put(raw)
36
+ try:
37
+ response = self.responses.get(timeout=timeout)
38
+ except Empty as exc:
39
+ raise RuntimeError("Batch timed out. The worker will restart for the next batch.") from exc
40
+ if response is None:
41
+ raise RuntimeError("Batch worker exited before returning a result")
42
+ return response
43
+
44
+ def close(self, force=False):
45
+ self.requests.put(None)
46
+ if not force:
47
+ try:
48
+ self.child.wait(timeout=5)
49
+ except subprocess.TimeoutExpired:
50
+ pass
51
+ if self.child.poll() is None:
52
+ if os.name == "nt":
53
+ # The venv launcher can create a child holding the native driver.
54
+ subprocess.run(["taskkill.exe", "/PID", str(self.child.pid), "/T", "/F"],
55
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=8)
56
+ else:
57
+ self.child.kill()
58
+ self.child.wait(timeout=5)
59
+ self.thread.join(timeout=1)
60
+
61
+
62
+ def supervise(command, stdin, output, timeout):
63
+ worker = None
64
+ try:
65
+ for line in stdin:
66
+ if worker is None:
67
+ worker = BatchWorker(command)
68
+ try:
69
+ response = worker.request(line, timeout).decode("utf8").rstrip("\r\n") + "\n"
70
+ except RuntimeError as exc:
71
+ worker.close(force=True)
72
+ worker = None
73
+ try:
74
+ request = json.loads(line)
75
+ except ValueError:
76
+ request = None
77
+ request_id = request.get("id") if isinstance(request, dict) else None
78
+ response = json.dumps({"id": request_id, "error": str(exc)}) + "\n"
79
+ output.write(response)
80
+ output.flush()
81
+ finally:
82
+ if worker is not None:
83
+ worker.close()