chadstthomas commited on
Commit
efc59a3
·
verified ·
1 Parent(s): ea668a6

Stage verified RailShot Stream industry preview

Browse files
Files changed (36) hide show
  1. .gitattributes +3 -0
  2. LICENSE +21 -0
  3. NOTICE.md +7 -0
  4. README.md +74 -0
  5. RUN.md +44 -0
  6. SHA256SUMS.txt +34 -0
  7. TOKENIZER-LICENSE +202 -0
  8. apps/railshot/__init__.py +1 -0
  9. apps/railshot/__main__.py +66 -0
  10. apps/railshot/magiceightball.py +59 -0
  11. apps/railshot/runtime.py +184 -0
  12. assets/hero-motion.webp +3 -0
  13. assets/hero.png +3 -0
  14. assets/industry-replay.webp +3 -0
  15. industry_replay.py +121 -0
  16. labs/shave_models/boolean/adaptive.py +362 -0
  17. labs/shave_models/boolean/benchmark.py +172 -0
  18. labs/shave_models/boolean/benchmark_batch_heads.py +148 -0
  19. labs/shave_models/boolean/blob_layout.py +84 -0
  20. labs/shave_models/boolean/bundles/magiceightball-ncs1-compact.m8b +0 -0
  21. labs/shave_models/boolean/bundles/magiceightball-radix/model.json +113 -0
  22. labs/shave_models/boolean/bundles/magiceightball-radix/model.onnx +3 -0
  23. labs/shave_models/boolean/compact_tokenizer.py +142 -0
  24. labs/shave_models/boolean/industries/frontline/bundle/model.json +316 -0
  25. labs/shave_models/boolean/industries/frontline/bundle/model.onnx +3 -0
  26. labs/shave_models/boolean/industries/frontline/bundle/ncs1-native.blob +0 -0
  27. labs/shave_models/boolean/needle3-tokenizer.m8t.xz +3 -0
  28. labs/shave_models/boolean/policy.py +308 -0
  29. labs/shave_models/boolean/portable_runtime.py +111 -0
  30. labs/shave_models/boolean/radix.py +31 -0
  31. labs/shave_models/boolean/release.py +71 -0
  32. labs/shave_models/boolean/runtime.py +455 -0
  33. labs/shave_models/boolean/stream.py +85 -0
  34. labs/shave_models/boolean/supervisor.py +83 -0
  35. measurements/industry-results.json +1973 -0
  36. measurements/physical-replay.json +434 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/hero-motion.webp filter=lfs diff=lfs merge=lfs -text
37
+ assets/hero.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/industry-replay.webp filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chad St. Thomas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
NOTICE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RailShot release notices
2
+
3
+ The RailShot host code and MagicEightBall implementation use the included MyriadForge MIT license.
4
+
5
+ The included compact tokenizer restores the original Needle 3 SentencePiece vocabulary byte for byte. It carries the included Apache-2.0 tokenizer license. [Pinned tokenizer source](https://huggingface.co/Cactus-Compute/needle3/blob/d6c7d6a2e9655505e0f8e23339356dd1705900eb/tokenizer/tokenizer.model)
6
+
7
+ The industry inputs are original simulated workflow examples. The measurements record actual execution on CPU and the original Intel Neural Compute Stick. OpenVINO and its device runtime are external dependencies.
README.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: mit-and-apache-2.0
4
+ license_link: LICENSE
5
+ language:
6
+ - en
7
+ pipeline_tag: text-classification
8
+ tags:
9
+ - railshot
10
+ - rack-lab
11
+ - intel-ncs1
12
+ - openvino
13
+ - onnx
14
+ - streaming
15
+ - sqlite
16
+ ---
17
+ # RailShot Stream v0.1 Preview
18
+
19
+ [![RailShot, a blue-striped pool ball, guides input packets along illuminated rails.](assets/hero-motion.webp)](assets/hero-motion.webp)
20
+
21
+ RailShot runs ordered, restartable text decision sessions on a single machine. It keeps separate documents for each stream, runs the MagicEightBall decision head on CPU or the original Intel Neural Compute Stick, and commits each accepted fragment and result to SQLite before replying. The release includes the compact MagicEightBall native archive, a portable ONNX graph, and the three frontline policy banks.
22
+
23
+ ## Industry replay
24
+
25
+ The records below are authored simulations. Every row was executed on the CPU and the physical NCS1. The second process reopened the same journal, retrieved the original approval result for an exact retry, then applied the new veto.
26
+
27
+ | Workflow | Split approval completed | Added after restart | New proposal |
28
+ | --- | --- | --- | --- |
29
+ | Dealership service intake | **Service requested. Intake approved.** → `review_service_intake` | **Customer declined.** | `null` |
30
+ | Manufacturing maintenance | **Vibration alert. Maintenance review approved.** → `review_mechanical_alert` | **Maintenance hold.** | `null` |
31
+ | Store equipment review | **Camera offline. Security review approved.** → `review_camera_alert` | **Alert cleared.** | `null` |
32
+
33
+ **48/48 checks passed across both backends.** Each workflow also exercises a sequence gap, a conflicting retry, an independent stream and a reset. A separate physical replay accepted exactly **131,072 tokens** and recovered after rejecting a 131,073-token append. [Raw industry results](measurements/industry-results.json) · [Physical limit and restart replay](measurements/physical-replay.json)
34
+
35
+ [![Three actual industry replay results. Each initial review proposal was cleared by the corresponding late event after restart.](assets/industry-replay.webp)](assets/industry-replay.webp)
36
+
37
+ ## Run the preview
38
+
39
+ Download the repository as a directory and run from its root. The examples below use Windows PowerShell.
40
+
41
+ ~~~powershell
42
+ hf download tablinum/RailShot-Stream --local-dir RailShot-Stream
43
+ cd RailShot-Stream
44
+ python -m pip install numpy onnxruntime sentencepiece
45
+ python industry_replay.py --out ./results/cpu
46
+ ~~~
47
+
48
+ For a physical NCS1 replay, use a functioning Windows OpenVINO 2020.3.2 toolchain with Python 3.7 and SentencePiece 0.1.99. Keep the original stick in its cold USB state before each session.
49
+
50
+ ~~~powershell
51
+ $toolchain = 'C:/path/to/ncs1'
52
+ $native = Join-Path $toolchain '.venv/Scripts/python.exe'
53
+ & $native -m pip install sentencepiece==0.1.99
54
+ python industry_replay.py --out ./results/physical --native-python $native --toolchain $toolchain
55
+ ~~~
56
+
57
+ Here's an individual stream on the dealership policy.
58
+
59
+ ~~~powershell
60
+ $bundle = 'labs/shave_models/boolean/industries/frontline/bundle'
61
+ @'
62
+ {"stream_id":"service-42","seq":1,"append":"Service requested. Intake "}
63
+ {"stream_id":"service-42","seq":2,"append":"approved."}
64
+ {"stream_id":"service-42","seq":3,"append":" Customer declined."}
65
+ '@ | python -m apps.railshot --db results/dealership.sqlite3 --artifact "$bundle/model.onnx" --bank dealership
66
+ ~~~
67
+
68
+ On NCS1, run the same command with the legacy interpreter and pass `--backend ncs1 --toolchain $toolchain --artifact "$bundle/ncs1-native.blob"`. Give the native lane its own journal. The [runtime guide](RUN.md) explains sequencing, replay, error responses, and the durable transaction boundary.
69
+
70
+ ## Scope
71
+
72
+ The device runs the learned MagicEightBall decision head. Host code handles the pinned tokenizer, evidence phrases, sequencing, and SQLite. Each page example produces a review proposal for another application or person. This preview covers authored policy phrases and local process restart. It stores request text in the local journal. Disk flushes affect acknowledgement latency, and longer histories require more recovery replay between resets.
73
+
74
+ [MagicEightBall](https://huggingface.co/tablinum/MagicEightBall) · [The Break Room](https://huggingface.co/spaces/tablinum/The-Break-Room) · [MyriadForge](https://github.com/chadstthomas-svg/myriadforge) · [License notices](NOTICE.md) · [File hashes](SHA256SUMS.txt)
RUN.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RailShot Stream
2
+
3
+ RailShot adds durable, ordered JSONL sessions to MagicEightBall’s incremental CPU and NCS1 runners. Text fragments in a session share a document and a decision history. Each successful append returns the resulting Boolean answer, category, and proposed action as data.
4
+
5
+ ## Run locally
6
+
7
+ Use Python 3.11+ with NumPy, ONNX Runtime, and SentencePiece. Run from the repository root.
8
+
9
+ ```powershell
10
+ python -m pip install numpy onnxruntime sentencepiece
11
+ @"
12
+ {"stream_id":"case-42","seq":1,"append":"Duplicate charge. "}
13
+ {"stream_id":"case-42","seq":2,"append":"Review authorized."}
14
+ {"stream_id":"case-42","seq":3,"append":" Do not route."}
15
+ "@ | python -m apps.railshot --db results/railshot.sqlite3
16
+ ```
17
+
18
+ The second result proposes `review_billing`. The third clears the proposal. Run the same command again with the same journal to retrieve the committed results. To continue the document, send sequence 4.
19
+
20
+ The default CPU artifact is the repository’s radix ONNX. Use `--artifact path/to/model.onnx` for another MagicEightBall CPU export and keep its adjacent `model.json`. A journal is bound to the artifact, policy manifest, and tokenizer.
21
+
22
+ ## Run on the original Intel NCS
23
+
24
+ Use the Windows OpenVINO 2020.3.2 toolchain with Python 3.7, NumPy and SentencePiece 0.1.99. The adapter checks for a cold USB device with product ID 2150 before loading the compact native archive. Use a separate journal for the two backends.
25
+
26
+ ```powershell
27
+ $toolchain = 'C:/path/to/ncs1'
28
+ $python = Join-Path $toolchain '.venv/Scripts/python.exe'
29
+ & $python -m pip install sentencepiece==0.1.99
30
+ @"
31
+ {"stream_id":"case-42","seq":1,"append":"Duplicate charge. "}
32
+ {"stream_id":"case-42","seq":2,"append":"Review authorized."}
33
+ "@ | & $python -m apps.railshot --backend ncs1 --toolchain $toolchain --db results/railshot-ncs1.sqlite3
34
+ ```
35
+
36
+ The learned decision head runs on the stick. Tokenization, evidence extraction, and transaction commits run on the host. The physical replay passed two process launches, two independent documents, exact retries, a late veto, a gap rejection, and recovery after an append exceeded 131,072 tokens. Stable JSON replies go to stdout. Native runtime diagnostics go to stderr.
37
+
38
+ ## Protocol
39
+
40
+ - A `stream_id` has 1–64 ASCII letters, digits, underscores, periods, or hyphens, beginning with a letter or digit. Each stream starts at `seq: 1` and advances by one on each commit. Different streams can be interleaved.
41
+ - Send `append` as a text fragment. `reset: true` starts a fresh document at the next sequence number, with optional initial text. Each active document has MagicEightBall’s 131,072-token limit.
42
+ - Success is a `railshot.result/1` object with `ok: true`, the stream ID, sequence, and `decision`. Resubmitting the same fragment and reset flag at an accepted sequence returns the recorded response. A different payload at that sequence produces `conflicting_retry`.
43
+ - Errors return `ok: false` with an `error` object. A gap reports `out_of_order` and `expected_seq`. A rejected append leaves the next sequence available. Successful results carry stable decision fields for replay.
44
+ - SQLite stores the request text, reset flag, and response in one transaction before stdout acknowledges success. Restart with the same journal to recover the active document from its committed fragments. Earlier results remain available for retries after a reset.
SHA256SUMS.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ b0cb99e3b0e56f8215aa0d4b503f2c9dcb63674c3f7b4e7c3e6a94c57c035a26 apps/railshot/__init__.py
2
+ 10c79b3c3ee19d679f3ec6beb97fb480b7da1b474c9fd1182ab8e557878d8263 apps/railshot/__main__.py
3
+ d7f67a5c90b6efa16ecc5b68e48967ac7a1fd16d3bf5f7f0835913c2eafb761b apps/railshot/magiceightball.py
4
+ a1c157b6e7113e78004e8b340e8393ab03ac82c716359279c44396f50c839acf apps/railshot/runtime.py
5
+ c61a881a51732b8deb7e5af159464328fb539b62cca93847ba67ef90632ccfe8 assets/hero-motion.webp
6
+ 5d1da11af939fab40d5aa664156156a0845972d055d793e9e403c5d7a3a8f5fe assets/hero.png
7
+ 631f454aa4af58ac3ae6d71ded04f90208a46aa67424aa24ec860665bc599b05 assets/industry-replay.webp
8
+ 84f97db62ece4e9b90ddcb004927d27d0bf052bd666ad873116b569a8e498cab industry_replay.py
9
+ b163b04556a7ed11c0bbb376d2404956c8441c858376809ba49d08e859bec9b6 labs/shave_models/boolean/adaptive.py
10
+ ceda70f87ab411c3a5294bee5c9a44d0a8c73914716d6004a96982fdb29f1730 labs/shave_models/boolean/benchmark.py
11
+ 704ab730971959fe77ac643edd342db3fec8ded07056d2af03101aeb477286a3 labs/shave_models/boolean/benchmark_batch_heads.py
12
+ 9e1666a0c8ebf5478f3bfd720be24636b26110b73bcb653ab77f3f0675c4a984 labs/shave_models/boolean/blob_layout.py
13
+ 1a8c1a021f62d89e236ebea379f9c69c9e4ffebe925c6bca49bb70df07d7cf61 labs/shave_models/boolean/bundles/magiceightball-ncs1-compact.m8b
14
+ 0c3ba89470cbb93bf7e6c5f9a4fdb0ffcec8fadc1da4557cdfb2ce2c81051198 labs/shave_models/boolean/bundles/magiceightball-radix/model.json
15
+ 9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5 labs/shave_models/boolean/bundles/magiceightball-radix/model.onnx
16
+ 81b1fa3936a84bf8736ad900d35754b5166a2fa129aac2c0b83818c3a0e4a5fe labs/shave_models/boolean/compact_tokenizer.py
17
+ d6456efe29b4ad80214c667d8d213f372464ef8afe6abc49b1db0df7a33ba0ec labs/shave_models/boolean/industries/frontline/bundle/model.json
18
+ 9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5 labs/shave_models/boolean/industries/frontline/bundle/model.onnx
19
+ 812c8f393db056c68cbca7f42fe7ac72ec9570d18f4e15f8e6eac2460ca04e46 labs/shave_models/boolean/industries/frontline/bundle/ncs1-native.blob
20
+ 97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9 labs/shave_models/boolean/needle3-tokenizer.m8t.xz
21
+ 52ef0bb07e52712d16073c73030790e5d6a746c0291492e03917e13749dccdc2 labs/shave_models/boolean/policy.py
22
+ 7894179273323a4de36c6df4134af4b4abb41dd88bbfc5d235d042f79e02c243 labs/shave_models/boolean/portable_runtime.py
23
+ 1f530b66213e4c46939580856dcb4ccf57516b7f55202516bb7128ea4414110a labs/shave_models/boolean/radix.py
24
+ 9f435e1a91da46d3b294048da148f1e7a2820923d3896ed3d7fe9549d0c45eea labs/shave_models/boolean/release.py
25
+ ee797b0ff94fbf99117cf0c580f118f447f0dd0100d1a19f64c6e7e4ffdfef8f labs/shave_models/boolean/runtime.py
26
+ a1215ecf1dd1cec6f13221a00e48a44435b136291287fa7dccc05f5dbef4b9bc labs/shave_models/boolean/stream.py
27
+ 3a115da44828ad4f2d375118d7e0a42ab134aeb8ab0e014dd8e9c8bb042a23c7 labs/shave_models/boolean/supervisor.py
28
+ e2048c75b0833284edc0429e6e373499be85e880d02850b45d70c9d96ea3bc9d LICENSE
29
+ d520bd483ad56cb985ddc1e194e094bac48c8b9d5bc943f9c16a0e4b6408e434 measurements/industry-results.json
30
+ 3e35ee291fd745a0028578b2419a8cd61615f856019d20e5faa44bd68eb65524 measurements/physical-replay.json
31
+ 63205a481429165d5b7c470cca17a61a3c1ef8580626cfbf3cb026e0e795e16c NOTICE.md
32
+ 983ffc1b805010bb3ab1b8da29f343c777470b848392f4d58ed788340bada416 README.md
33
+ a53e6f296ce14c9e1f529dfbbd4559eb089dbb5f7a3f38e5ea2827fefddf8c81 RUN.md
34
+ 3ddf9be5c28fe27dad143a5dc76eea25222ad1dd68934a047064e56ed2fa40c5 TOKENIZER-LICENSE
TOKENIZER-LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
apps/railshot/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Durable JSONL streams for local inference."""
apps/railshot/__main__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the RailShot append protocol over newline-delimited UTF-8 JSON."""
2
+
3
+ import argparse
4
+ from contextlib import closing
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sqlite3
9
+ import sys
10
+
11
+ from .magiceightball import DEFAULT_ARTIFACT, NCS1_ARTIFACT, MagicEightBall
12
+ from .runtime import RESULT_SCHEMA, RailShot, Request, StreamError, encode
13
+
14
+
15
+ def serve(railshot, source, output):
16
+ for line in source:
17
+ request = None
18
+ try:
19
+ try:
20
+ document = json.loads(line)
21
+ except (ValueError, RecursionError) as exc:
22
+ raise StreamError("invalid_json", "Expected one UTF-8 JSON object per line") from exc
23
+ request = Request.parse(document)
24
+ response = railshot.process(request)
25
+ except (StreamError, sqlite3.Error) as exc:
26
+ error = {"code": "journal_error", "message": str(exc)}
27
+ response = {"schema": RESULT_SCHEMA, "ok": False, "error": error}
28
+ if isinstance(exc, StreamError):
29
+ error["code"] = exc.code
30
+ if exc.expected_seq is not None:
31
+ error["expected_seq"] = exc.expected_seq
32
+ if request is not None:
33
+ response.update(stream_id=request.stream_id, seq=request.seq)
34
+ print(encode(response), file=output, flush=True)
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument("--db", required=True, type=Path, help="SQLite journal path")
40
+ parser.add_argument("--backend", choices=("cpu", "ncs1"), default="cpu",
41
+ help="Inference backend (CPU by default)")
42
+ parser.add_argument("--artifact", type=Path,
43
+ help="MagicEightBall model file (defaults to the backend's release artifact)")
44
+ parser.add_argument("--toolchain", type=Path,
45
+ help="OpenVINO 2020.3.2 toolchain root for the NCS1 backend")
46
+ parser.add_argument("--bank", help="Named policy bank in the selected artifact")
47
+ args = parser.parse_args()
48
+ if args.toolchain is not None and args.backend != "ncs1":
49
+ parser.error("--toolchain requires --backend ncs1")
50
+ artifact = args.artifact or (NCS1_ARTIFACT if args.backend == "ncs1" else DEFAULT_ARTIFACT)
51
+ output = sys.stdout
52
+ if args.backend == "ncs1":
53
+ # Keep the reply channel before loading OpenVINO. MYRIAD can write
54
+ # native diagnostics to stdout, including during interpreter teardown.
55
+ output = os.fdopen(os.dup(sys.stdout.fileno()), "w", encoding="utf-8")
56
+ os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
57
+ try:
58
+ journal = RailShot(args.db, MagicEightBall(artifact, args.backend, args.toolchain, args.bank))
59
+ except (ImportError, ValueError, OSError, RuntimeError, sqlite3.Error) as exc:
60
+ parser.exit(1, f"RailShot: {exc}\n")
61
+ with closing(journal):
62
+ serve(journal, sys.stdin.buffer, output)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
apps/railshot/magiceightball.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Connect the released MagicEightBall CPU or physical NCS1 head to RailShot."""
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+ import subprocess
6
+ import sys
7
+
8
+ from .runtime import encode
9
+
10
+
11
+ MODEL_DIR = Path(__file__).resolve().parents[2] / "labs" / "shave_models" / "boolean"
12
+ DEFAULT_ARTIFACT = MODEL_DIR / "bundles" / "magiceightball-radix" / "model.onnx"
13
+ NCS1_ARTIFACT = MODEL_DIR / "bundles" / "magiceightball-ncs1-compact.m8b"
14
+
15
+
16
+ class MagicEightBall:
17
+ def __init__(self, artifact, backend="cpu", toolchain=None, bank=None):
18
+ # The released runner uses sibling imports when launched as a script.
19
+ sys.path.insert(0, str(MODEL_DIR))
20
+ try:
21
+ from compact_tokenizer import TOKENIZER_HASH
22
+ from stream import DecisionStream
23
+
24
+ artifact = Path(artifact)
25
+ device = {}
26
+ if backend == "cpu":
27
+ from portable_runtime import PortableRuntime
28
+ self.engine = PortableRuntime(artifact).policy_view(bank)
29
+ elif backend == "ncs1":
30
+ suffix = artifact.suffix.casefold()
31
+ if suffix not in (".m8b", ".blob"):
32
+ raise ValueError("Use a MagicEightBall .m8b archive or a .blob with its bundle manifest")
33
+ from benchmark_batch_heads import windows_usb_identity
34
+ from runtime import Runtime
35
+ try:
36
+ device = windows_usb_identity("ncs1")
37
+ except subprocess.SubprocessError as exc:
38
+ raise RuntimeError("Unable to check NCS1 USB identity") from exc
39
+ if suffix == ".m8b":
40
+ self.engine = Runtime(artifact, toolchain=toolchain, bank=bank, release_stick="ncs1")
41
+ else:
42
+ blob = artifact.resolve()
43
+ self.engine = Runtime(blob.parent, toolchain=toolchain, blob=blob, bank=bank)
44
+ else:
45
+ raise ValueError("Unsupported RailShot backend: " + backend)
46
+ self.stream_class = DecisionStream
47
+ self.identity = encode({
48
+ "adapter": "magiceightball/1",
49
+ "artifact_sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(),
50
+ "manifest": self.engine.info,
51
+ "tokenizer_sha256": TOKENIZER_HASH,
52
+ **device,
53
+ **({"bank": bank} if bank is not None else {}),
54
+ })
55
+ finally:
56
+ sys.path.remove(str(MODEL_DIR))
57
+
58
+ def open_stream(self):
59
+ return self.stream_class(self.engine)
apps/railshot/runtime.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persist ordered inference requests and their stable results in SQLite."""
2
+
3
+ from collections import OrderedDict
4
+ from dataclasses import dataclass
5
+ import json
6
+ from pathlib import Path
7
+ import re
8
+ import sqlite3
9
+
10
+
11
+ RESULT_SCHEMA = "railshot.result/1"
12
+ STREAM_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}")
13
+ MAX_SEQUENCE = (1 << 63) - 1
14
+ RESIDENT_STREAMS = 16
15
+
16
+
17
+ def encode(value):
18
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)
19
+
20
+
21
+ class StreamError(ValueError):
22
+ def __init__(self, code, message, expected_seq=None):
23
+ super().__init__(message)
24
+ self.code = code
25
+ self.expected_seq = expected_seq
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Request:
30
+ stream_id: str
31
+ seq: int
32
+ append: str
33
+ reset: bool
34
+
35
+ @classmethod
36
+ def parse(cls, value):
37
+ if not isinstance(value, dict) or value.keys() - {"stream_id", "seq", "append", "reset"}:
38
+ raise StreamError("invalid_request", "Expected stream_id, seq, append, and optional reset")
39
+ stream_id = value.get("stream_id")
40
+ if not isinstance(stream_id, str) or STREAM_ID.fullmatch(stream_id) is None:
41
+ raise StreamError("invalid_request", "Invalid stream_id")
42
+ seq = value.get("seq")
43
+ if type(seq) is not int or not 1 <= seq <= MAX_SEQUENCE:
44
+ raise StreamError("invalid_request", "seq must be a positive signed 64-bit integer")
45
+ reset = value.get("reset", False)
46
+ fragment = value.get("append", "" if reset is True else None)
47
+ if type(reset) is not bool or not isinstance(fragment, str):
48
+ raise StreamError("invalid_request", "Use an append string or reset=true")
49
+ try:
50
+ fragment.encode("utf-8")
51
+ except UnicodeEncodeError as exc:
52
+ raise StreamError("invalid_request", "append must contain valid Unicode text") from exc
53
+ return cls(stream_id, seq, fragment, reset)
54
+
55
+
56
+ class RailShot:
57
+ def __init__(self, path, adapter):
58
+ path = Path(path)
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ self.connection = sqlite3.connect(path, isolation_level=None, timeout=30)
61
+ self.adapter = adapter
62
+ self.resident = OrderedDict()
63
+ try:
64
+ self.connection.execute("PRAGMA synchronous = FULL")
65
+ with self.connection:
66
+ self.connection.execute("BEGIN IMMEDIATE")
67
+ self.connection.execute(
68
+ "CREATE TABLE IF NOT EXISTS railshot_metadata (name TEXT PRIMARY KEY, value TEXT NOT NULL)"
69
+ )
70
+ self.connection.execute(
71
+ """CREATE TABLE IF NOT EXISTS railshot_entries (
72
+ stream_id TEXT NOT NULL,
73
+ seq INTEGER NOT NULL,
74
+ fragment TEXT NOT NULL,
75
+ reset INTEGER NOT NULL CHECK (reset IN (0, 1)),
76
+ response TEXT NOT NULL,
77
+ PRIMARY KEY (stream_id, seq)
78
+ ) WITHOUT ROWID"""
79
+ )
80
+ self.connection.execute(
81
+ "INSERT OR IGNORE INTO railshot_metadata VALUES ('adapter/v1', ?)", (adapter.identity,)
82
+ )
83
+ (identity,) = self.connection.execute(
84
+ "SELECT value FROM railshot_metadata WHERE name = 'adapter/v1'"
85
+ ).fetchone()
86
+ if identity != adapter.identity:
87
+ raise StreamError("adapter_mismatch", "This journal belongs to a different inference adapter")
88
+ except BaseException:
89
+ self.close()
90
+ raise
91
+
92
+ def close(self):
93
+ self.connection.close()
94
+
95
+ @staticmethod
96
+ def _decision(stream, request):
97
+ outcome = stream.append(request.append, reset=request.reset)
98
+ # Runtime timings are observations; durable decisions must compare exactly on replay.
99
+ return {
100
+ "schema": RESULT_SCHEMA,
101
+ "ok": True,
102
+ "stream_id": request.stream_id,
103
+ "seq": request.seq,
104
+ "decision": {key: value for key, value in outcome.items() if not key.endswith("_ms")},
105
+ }
106
+
107
+ def _restore(self, stream_id, last_seq):
108
+ replay_after, stream = self.resident.get(stream_id, (0, None))
109
+ if stream is None:
110
+ stream = self.adapter.open_stream()
111
+ if replay_after == last_seq:
112
+ return stream
113
+ # Reset starts a new document. Older rows still serve idempotent retries.
114
+ (last_reset,) = self.connection.execute(
115
+ "SELECT MAX(seq) FROM railshot_entries WHERE stream_id = ? AND reset = 1 AND seq > ?",
116
+ (stream_id, replay_after),
117
+ ).fetchone()
118
+ if last_reset is not None:
119
+ stream = self.adapter.open_stream()
120
+ replay_after = last_reset - 1
121
+ rows = self.connection.execute(
122
+ """SELECT seq, fragment, reset, response FROM railshot_entries
123
+ WHERE stream_id = ? AND seq > ? ORDER BY seq""",
124
+ (stream_id, replay_after),
125
+ )
126
+ for seq, fragment, reset, recorded in rows:
127
+ request = Request(stream_id, seq, fragment, bool(reset))
128
+ try:
129
+ actual = encode(self._decision(stream, request))
130
+ except Exception as exc:
131
+ raise StreamError("replay_failed", f"Unable to replay committed seq {seq}") from exc
132
+ if seq != replay_after + 1 or recorded != actual:
133
+ raise StreamError("replay_mismatch", f"Committed result disagrees at seq {seq}")
134
+ replay_after = seq
135
+ return stream
136
+
137
+ def process(self, request):
138
+ db = self.connection
139
+ stream_id = request.stream_id
140
+ state_used = False
141
+ try:
142
+ with db:
143
+ db.execute("BEGIN IMMEDIATE")
144
+ existing = db.execute(
145
+ "SELECT fragment, reset, response FROM railshot_entries WHERE stream_id = ? AND seq = ?",
146
+ (stream_id, request.seq),
147
+ ).fetchone()
148
+ if existing is not None:
149
+ fragment, reset, response = existing
150
+ if (request.append, request.reset) != (fragment, bool(reset)):
151
+ raise StreamError("conflicting_retry", "This seq already has a different request")
152
+ return json.loads(response)
153
+
154
+ (last_seq,) = db.execute(
155
+ "SELECT COALESCE(MAX(seq), 0) FROM railshot_entries WHERE stream_id = ?", (stream_id,)
156
+ ).fetchone()
157
+ if request.seq != last_seq + 1:
158
+ raise StreamError("out_of_order", "Expected the next contiguous seq", last_seq + 1)
159
+
160
+ state_used = True
161
+ stream = self.adapter.open_stream() if request.reset else self._restore(stream_id, last_seq)
162
+ try:
163
+ result = self._decision(stream, request)
164
+ encoded = encode(result)
165
+ except ValueError as exc:
166
+ raise StreamError("invalid_append", str(exc), request.seq) from exc
167
+ except Exception as exc:
168
+ raise StreamError("inference_failed", str(exc), request.seq) from exc
169
+ db.execute(
170
+ "INSERT INTO railshot_entries VALUES (?, ?, ?, ?, ?)",
171
+ (stream_id, request.seq, request.append, request.reset, encoded),
172
+ )
173
+ except BaseException:
174
+ # An inference or commit can fail after mutating a resident stream.
175
+ # The next attempt restores it from SQLite's committed rows.
176
+ if state_used:
177
+ self.resident.pop(stream_id, None)
178
+ raise
179
+
180
+ self.resident[stream_id] = (request.seq, stream)
181
+ self.resident.move_to_end(stream_id)
182
+ if len(self.resident) > RESIDENT_STREAMS:
183
+ self.resident.popitem(last=False)
184
+ return result
assets/hero-motion.webp ADDED

Git LFS Details

  • SHA256: c61a881a51732b8deb7e5af159464328fb539b62cca93847ba67ef90632ccfe8
  • Pointer size: 132 Bytes
  • Size of remote file: 1.11 MB
assets/hero.png ADDED

Git LFS Details

  • SHA256: 5d1da11af939fab40d5aa664156156a0845972d055d793e9e403c5d7a3a8f5fe
  • Pointer size: 132 Bytes
  • Size of remote file: 1.85 MB
assets/industry-replay.webp ADDED

Git LFS Details

  • SHA256: 631f454aa4af58ac3ae6d71ded04f90208a46aa67424aa24ec860665bc599b05
  • Pointer size: 131 Bytes
  • Size of remote file: 102 kB
industry_replay.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay three simulated industry workflows using the real RailShot CLI."""
2
+
3
+ import argparse
4
+ from datetime import datetime
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sqlite3
9
+ import subprocess
10
+ import sys
11
+
12
+ ROOT = Path(__file__).resolve().parent
13
+ BUNDLE = ROOT / "labs/shave_models/boolean/industries/frontline/bundle"
14
+ SCENARIOS = {
15
+ "dealership": {
16
+ "opening": "Service requested. Intake ",
17
+ "approval": "approved.",
18
+ "reversal": " Customer declined.",
19
+ "category": "service",
20
+ "proposal": "review_service_intake",
21
+ },
22
+ "manufacturing": {
23
+ "opening": "Vibration alert. Maintenance review ",
24
+ "approval": "approved.",
25
+ "reversal": " Maintenance hold.",
26
+ "category": "mechanical",
27
+ "proposal": "review_mechanical_alert",
28
+ },
29
+ "store_security": {
30
+ "opening": "Camera offline. Security review ",
31
+ "approval": "approved.",
32
+ "reversal": " Alert cleared.",
33
+ "category": "camera_alert",
34
+ "proposal": "review_camera_alert",
35
+ },
36
+ }
37
+
38
+
39
+ def req(stream, step, fragment, reset=False):
40
+ return {"stream_id":stream,"seq":step,"append":fragment,"reset":reset}
41
+
42
+
43
+ def decision(case, action):
44
+ return {"answers":{"may_route":action is not None},"category":case["category"],"action":action}
45
+
46
+
47
+ def run_fixture(args, backend, out, bank, case):
48
+ db=out/f"{backend}-{bank}.sqlite3"
49
+ artifact=BUNDLE/("model.onnx" if backend=="cpu" else "ncs1-native.blob")
50
+ exe=sys.executable if backend=="cpu" else str(args.native_python.resolve())
51
+ cmd=[exe,"-m","apps.railshot","--db",str(db),"--backend",backend,
52
+ "--artifact",str(artifact),"--bank",bank]
53
+ env=os.environ.copy()
54
+ env["PYTHONDONTWRITEBYTECODE"]="1"
55
+ if backend=="ncs1":
56
+ cmd.extend(["--toolchain",str(args.toolchain.resolve())])
57
+ if args.legacy_extras:
58
+ env["PYTHONPATH"]=str(args.legacy_extras.resolve())
59
+
60
+ def run(rows):
61
+ requests="".join(json.dumps(row)+"\n" for row in rows)
62
+ p=subprocess.run(cmd,cwd=ROOT,input=requests.encode("utf-8"),capture_output=True,
63
+ timeout=60,env=env)
64
+ if p.returncode:
65
+ raise RuntimeError(p.stderr.decode("utf-8",errors="replace"))
66
+ replies=[json.loads(line) for line in p.stdout.splitlines()]
67
+ assert len(replies)==len(rows)
68
+ return replies
69
+
70
+ opened=req("active",1,case["opening"])
71
+ approved=req("active",2,case["approval"])
72
+ rows_a=[opened,req("active",3,"Skipped"),approved,req("unrelated",1,"Routine note only.")]
73
+ a=run(rows_a)
74
+ assert a[0]["ok"] and a[0]["decision"]["result"]==decision(case,None),a[0]
75
+ assert a[1]["error"]["code"]=="out_of_order" and a[1]["error"]["expected_seq"]==2,a[1]
76
+ assert a[2]["decision"]["result"]==decision(case,case["proposal"]),a[2]
77
+ assert a[3]["decision"]["result"]["action"] is None,a[3]
78
+ rows_b=[approved,req("active",3,case["reversal"]),req("active",2,"Conflicting approval"),
79
+ req("active",4,case["opening"]+case["approval"],True)]
80
+ b=run(rows_b)
81
+ assert b[0]==a[2],b[0]
82
+ assert b[1]["decision"]["result"]==decision(case,None),b[1]
83
+ assert b[2]["error"]["code"]=="conflicting_retry",b[2]
84
+ assert b[3]["decision"]["result"]==decision(case,case["proposal"]),b[3]
85
+ with sqlite3.connect(db) as connection:
86
+ raw=connection.execute("SELECT value FROM railshot_metadata WHERE name='adapter/v1'").fetchone()[0]
87
+ committed=connection.execute("SELECT stream_id,count(*) FROM railshot_entries GROUP BY stream_id").fetchall()
88
+ identity=json.loads(raw)
89
+ assert identity["bank"]==bank
90
+ assert backend!="ncs1" or identity["boot_usb_id"]=="03E7:2150"
91
+ assert committed==[("active",4),("unrelated",1)]
92
+ return {"bank":bank,"backend":backend,"passes":len(a)+len(b),
93
+ "source":"authored simulation of structured workflow records, with actual inference and SQLite commits",
94
+ "identity":{k:v for k,v in identity.items() if k!="manifest"},
95
+ "process_1":{"requests":rows_a,"responses":a},
96
+ "process_2":{"requests":rows_b,"responses":b}}
97
+
98
+
99
+ def main():
100
+ p=argparse.ArgumentParser(description=__doc__)
101
+ p.add_argument("--out",type=Path,required=True)
102
+ p.add_argument("--native-python",type=Path)
103
+ p.add_argument("--toolchain",type=Path)
104
+ p.add_argument("--legacy-extras",type=Path)
105
+ args=p.parse_args()
106
+ if bool(args.native_python)!=bool(args.toolchain):
107
+ p.error("Supply both --native-python and --toolchain to run the NCS1 lane")
108
+ args.out.mkdir(parents=True,exist_ok=False)
109
+ lanes=["cpu"] + (["ncs1"] if args.native_python else [])
110
+ evidence=[]
111
+ for lane in lanes:
112
+ for bank,case in SCENARIOS.items():
113
+ row=run_fixture(args,lane,args.out,bank,case)
114
+ evidence.append(row)
115
+ print(lane,bank,row["passes"],flush=True)
116
+ result={"schema":"railshot.industry-replay/1","ranges":evidence}
117
+ (args.out/"industry-results.json").write_text(json.dumps(result,indent=2)+"\n",encoding="utf-8")
118
+
119
+
120
+ if __name__=="__main__":
121
+ main()
labs/shave_models/boolean/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()
labs/shave_models/boolean/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"])
labs/shave_models/boolean/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"]}))
labs/shave_models/boolean/blob_layout.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read the documented section layout of an OpenVINO 2020.3 MYRIAD blob."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import struct
7
+
8
+
9
+ # OpenVINO 2020.3.2 blob_format.hpp and backend/serialize.cpp.
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:
53
+ if layout["stages"] < 12:
54
+ raise ValueError("Invalid MYRIAD stage")
55
+ length, operation, shaves = struct.unpack_from("<3I", data, fields[18])
56
+ if not 12 <= length <= layout["stages"]:
57
+ raise ValueError("Invalid legacy MYRIAD stage length")
58
+ stage = {"length": length, "type": operation, "shaves_field": shaves}
59
+ return dict(bytes=size, sha256=hashlib.sha256(data).hexdigest(), version=[major, minor],
60
+ inputs=fields[4], outputs=fields[5], stage_count=stage_count,
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))
labs/shave_models/boolean/bundles/magiceightball-ncs1-compact.m8b ADDED
Binary file (699 Bytes). View file
 
labs/shave_models/boolean/bundles/magiceightball-radix/model.json ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "policy": {
3
+ "name": "magiceightball",
4
+ "rules": {
5
+ "billing": "\"charged twice\" OR \"duplicate charge\"",
6
+ "delivery": "\"package missing\" OR \"parcel missing\"",
7
+ "permission": "\"review authorized\"",
8
+ "hold": "\"do not route\" OR \"review cancelled\"",
9
+ "case_found": "@billing OR @delivery",
10
+ "ready": "@case_found AND @permission AND NOT @hold"
11
+ },
12
+ "answers": {
13
+ "may_route": "@ready"
14
+ },
15
+ "categories": {
16
+ "mixed": "@billing AND @delivery",
17
+ "billing": "@billing",
18
+ "delivery": "@delivery"
19
+ },
20
+ "actions": {
21
+ "triage_mixed": "@ready AND @billing AND @delivery",
22
+ "review_billing": "@ready AND @billing",
23
+ "review_delivery": "@ready AND @delivery"
24
+ }
25
+ },
26
+ "variant": "gather",
27
+ "decisions": "v0",
28
+ "state_channels": 0,
29
+ "tile_side": 64,
30
+ "input_shapes": {
31
+ "features": [
32
+ 128
33
+ ]
34
+ },
35
+ "onnx_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
36
+ "fp16_coefficient_bytes": 32,
37
+ "learned_parameters": 0,
38
+ "codebook": [
39
+ [
40
+ 0,
41
+ 0,
42
+ 0,
43
+ 0,
44
+ 0,
45
+ 0,
46
+ 0
47
+ ],
48
+ [
49
+ 0,
50
+ 0,
51
+ 0,
52
+ 1,
53
+ 0,
54
+ 0,
55
+ 0
56
+ ],
57
+ [
58
+ 0,
59
+ 0,
60
+ 1,
61
+ 0,
62
+ 0,
63
+ 0,
64
+ 0
65
+ ],
66
+ [
67
+ 0,
68
+ 1,
69
+ 1,
70
+ 1,
71
+ 0,
72
+ 0,
73
+ 0
74
+ ],
75
+ [
76
+ 1,
77
+ 0,
78
+ 0,
79
+ 1,
80
+ 0,
81
+ 0,
82
+ 1
83
+ ],
84
+ [
85
+ 1,
86
+ 0,
87
+ 1,
88
+ 0,
89
+ 0,
90
+ 1,
91
+ 0
92
+ ],
93
+ [
94
+ 1,
95
+ 1,
96
+ 1,
97
+ 1,
98
+ 1,
99
+ 1,
100
+ 1
101
+ ]
102
+ ],
103
+ "radix_digits": 8,
104
+ "pair_fact_order": [
105
+ 4,
106
+ 5,
107
+ 6,
108
+ 0,
109
+ 1,
110
+ 2,
111
+ 3
112
+ ]
113
+ }
labs/shave_models/boolean/bundles/magiceightball-radix/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5
3
+ size 192
labs/shave_models/boolean/compact_tokenizer.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lossless storage for the pinned Needle 3 SentencePiece model."""
2
+ import argparse
3
+ from collections import Counter
4
+ import hashlib
5
+ import lzma
6
+ from pathlib import Path
7
+ import struct
8
+
9
+
10
+ TOKENIZER_HASH = "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
11
+ LEGACY_MAGIC = b"M8T1"
12
+ MAGIC = b"M8T2"
13
+ HEADER = struct.Struct("<4s3H")
14
+ SPECIAL_PIECES = 284
15
+ MAX_SHORT_PIECE = 120
16
+ METASPACE = "\u2581".encode("utf8")
17
+ HAS_METASPACE = 128
18
+ LENGTH_TABLE = bytes(range(HAS_METASPACE)) * 2
19
+
20
+
21
+ def _varint(number):
22
+ encoded = bytearray()
23
+ while number >= 128:
24
+ encoded.append((number & 127) | 128)
25
+ number >>= 7
26
+ encoded.append(number)
27
+ return bytes(encoded)
28
+
29
+
30
+ def _field(tag, contents):
31
+ return bytes([tag]) + _varint(len(contents)) + contents
32
+
33
+
34
+ def _byte_fallback():
35
+ # SentencePiece BYTE messages are the same except for the hex spelling.
36
+ return b"".join(b"\x0a\x0f\x0a\x06<0x%02X>\x15\0\0\0\0\x18\x06" % value
37
+ for value in range(256))
38
+
39
+
40
+ def _restore(data):
41
+ if len(data) < HEADER.size:
42
+ raise ValueError("Missing compact tokenizer header")
43
+ magic, prefix_size, suffix_size, count = HEADER.unpack_from(data)
44
+ prefix_end = HEADER.size + prefix_size
45
+ suffix_end = prefix_end + suffix_size
46
+ lengths_end = suffix_end + count
47
+ descriptors = data[suffix_end:lengths_end]
48
+ if magic not in (MAGIC, LEGACY_MAGIC) or count == 0 or len(descriptors) != count:
49
+ raise ValueError("Invalid compact tokenizer layout")
50
+ bucketed = magic == MAGIC
51
+ lengths = descriptors.translate(LENGTH_TABLE) if bucketed else descriptors
52
+ if sum(lengths) != len(data) - lengths_end:
53
+ raise ValueError("Invalid compact tokenizer layout")
54
+ original = bytearray(data[HEADER.size:prefix_end])
55
+ # The outer length is piece length plus the two string bytes and five score bytes.
56
+ prefixes = [None] * 256
57
+ for desc in set(descriptors):
58
+ marker = METASPACE if bucketed and desc & HAS_METASPACE else b""
59
+ length = (LENGTH_TABLE[desc] if bucketed else desc) + len(marker)
60
+ if not 1 <= length <= MAX_SHORT_PIECE:
61
+ raise ValueError("Invalid compact tokenizer piece length")
62
+ prefixes[desc] = bytes([10, length + 7, 10, length]) + marker
63
+ scores = struct.pack("<%df" % count, *(-float(rank) for rank in range(count)))
64
+ offset = lengths_end
65
+ score_offset = 0
66
+ # NORMAL is the protobuf default. Rank zero has the original -0.0 bit pattern.
67
+ if bucketed:
68
+ original.extend(_byte_fallback())
69
+ positions = [0] * HAS_METASPACE
70
+ for length, amount in sorted(Counter(lengths).items()):
71
+ positions[length] = offset
72
+ offset += length * amount
73
+ for desc in descriptors:
74
+ length = desc & (HAS_METASPACE - 1)
75
+ start = positions[length]
76
+ end = start + length
77
+ positions[length] = end
78
+ original.extend(prefixes[desc] + data[start:end] + b"\x15" + scores[score_offset:score_offset + 4])
79
+ score_offset += 4
80
+ else:
81
+ for length in lengths:
82
+ end = offset + length
83
+ original.extend(prefixes[length] + data[offset:end] + b"\x15" + scores[score_offset:score_offset + 4])
84
+ offset = end
85
+ score_offset += 4
86
+ original.extend(data[prefix_end:suffix_end])
87
+ return bytes(original)
88
+
89
+
90
+ def read_tokenizer(path):
91
+ data = path.read_bytes()
92
+ if path.suffix == ".xz":
93
+ data = lzma.decompress(data)
94
+ if data.startswith((MAGIC, LEGACY_MAGIC)):
95
+ data = _restore(data)
96
+ if hashlib.sha256(data).hexdigest() != TOKENIZER_HASH:
97
+ raise ValueError("Unexpected Needle 3 tokenizer hash")
98
+ return data
99
+
100
+
101
+ def pack_tokenizer(original):
102
+ # Only the build tool uses protobuf. Runtime reconstruction is stdlib-only.
103
+ from sentencepiece import sentencepiece_model_pb2
104
+
105
+ if hashlib.sha256(original).hexdigest() != TOKENIZER_HASH:
106
+ raise ValueError("Expected the pinned Needle 3 tokenizer")
107
+ model = sentencepiece_model_pb2.ModelProto.FromString(original)
108
+ prefix = b"".join(_field(10, piece.SerializeToString(deterministic=True))
109
+ for piece in model.pieces[:SPECIAL_PIECES])
110
+ fallback = _byte_fallback()
111
+ if not prefix.endswith(fallback):
112
+ raise ValueError("Unexpected Needle 3 byte fallback ordering")
113
+ prefix = prefix[:-len(fallback)]
114
+ words = []
115
+ descriptors = bytearray()
116
+ for piece in model.pieces[SPECIAL_PIECES:]:
117
+ word = piece.piece.encode("utf8")
118
+ has_metaspace = word.startswith(METASPACE)
119
+ if has_metaspace:
120
+ word = word[len(METASPACE):]
121
+ words.append(word)
122
+ descriptors.append(len(word) | (HAS_METASPACE if has_metaspace else 0))
123
+ del model.pieces[:]
124
+ suffix = model.SerializeToString(deterministic=True)
125
+ header = HEADER.pack(MAGIC, len(prefix), len(suffix), len(words))
126
+ # Stable grouping by length keeps each bucket in vocabulary rank order.
127
+ packed = header + prefix + suffix + descriptors + b"".join(sorted(words, key=len))
128
+ if _restore(packed) != original:
129
+ raise ValueError("Compact format failed to reproduce the exact SentencePiece bytes")
130
+ filters = [{"id": lzma.FILTER_LZMA2, "preset": 9, "dict_size": 65536, "pb": 0}]
131
+ return lzma.compress(packed, filters=filters)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ parser = argparse.ArgumentParser(description=__doc__)
136
+ parser.add_argument("source", type=Path)
137
+ parser.add_argument("output", type=Path)
138
+ args = parser.parse_args()
139
+ original = read_tokenizer(args.source)
140
+ compressed = pack_tokenizer(original)
141
+ args.output.write_bytes(compressed)
142
+ print("%d original bytes, %d compact bytes" % (len(original), len(compressed)))
labs/shave_models/boolean/industries/frontline/bundle/model.json ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "magiceightball",
3
+ "variant": "gather",
4
+ "decisions": "v0",
5
+ "default_bank": "dealership",
6
+ "banks": {
7
+ "dealership": {
8
+ "policy": {
9
+ "name": "dealership",
10
+ "rules": {
11
+ "service": "\"service requested\" OR \"maintenance enquiry\"",
12
+ "inspection": "\"inspection requested\" OR \"inspection referral\"",
13
+ "intake": "@service OR @inspection",
14
+ "ready": "@intake AND \"intake approved\" AND NOT (\"do not queue\" OR \"customer declined\")"
15
+ },
16
+ "answers": {
17
+ "may_route": "@ready"
18
+ },
19
+ "categories": {
20
+ "combined_intake": "@service AND @inspection",
21
+ "service": "@service",
22
+ "inspection": "@inspection"
23
+ },
24
+ "actions": {
25
+ "review_combined_intake": "@ready AND @service AND @inspection",
26
+ "review_service_intake": "@ready AND @service",
27
+ "review_inspection_intake": "@ready AND @inspection"
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
+ "manufacturing": {
108
+ "policy": {
109
+ "name": "manufacturing",
110
+ "rules": {
111
+ "mechanical": "\"vibration alert\" OR \"bearing overheat\"",
112
+ "service": "\"filter differential high\" OR \"lubrication low\"",
113
+ "intake": "@mechanical OR @service",
114
+ "ready": "@intake AND \"maintenance review approved\" AND NOT (\"maintenance hold\" OR \"work order blocked\")"
115
+ },
116
+ "answers": {
117
+ "may_route": "@ready"
118
+ },
119
+ "categories": {
120
+ "combined_maintenance": "@mechanical AND @service",
121
+ "mechanical": "@mechanical",
122
+ "service": "@service"
123
+ },
124
+ "actions": {
125
+ "review_combined_maintenance": "@ready AND @mechanical AND @service",
126
+ "review_mechanical_alert": "@ready AND @mechanical",
127
+ "review_service_alert": "@ready AND @service"
128
+ }
129
+ },
130
+ "bank_offset": 0,
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
+ "store_security": {
208
+ "policy": {
209
+ "name": "store-security",
210
+ "rules": {
211
+ "access": "\"door forced\" OR \"door held open\"",
212
+ "camera": "\"camera offline\" OR \"video feed lost\"",
213
+ "intake": "@access OR @camera",
214
+ "ready": "@intake AND \"security review approved\" AND NOT (\"drill active\" OR \"alert cleared\")"
215
+ },
216
+ "answers": {
217
+ "may_route": "@ready"
218
+ },
219
+ "categories": {
220
+ "combined_alert": "@access AND @camera",
221
+ "access_alert": "@access",
222
+ "camera_alert": "@camera"
223
+ },
224
+ "actions": {
225
+ "review_combined_alert": "@ready AND @access AND @camera",
226
+ "review_access_alert": "@ready AND @access",
227
+ "review_camera_alert": "@ready AND @camera"
228
+ }
229
+ },
230
+ "bank_offset": 0,
231
+ "codebook": [
232
+ [
233
+ 0,
234
+ 0,
235
+ 0,
236
+ 0,
237
+ 0,
238
+ 0,
239
+ 0
240
+ ],
241
+ [
242
+ 0,
243
+ 0,
244
+ 0,
245
+ 1,
246
+ 0,
247
+ 0,
248
+ 0
249
+ ],
250
+ [
251
+ 0,
252
+ 0,
253
+ 1,
254
+ 0,
255
+ 0,
256
+ 0,
257
+ 0
258
+ ],
259
+ [
260
+ 0,
261
+ 1,
262
+ 1,
263
+ 1,
264
+ 0,
265
+ 0,
266
+ 0
267
+ ],
268
+ [
269
+ 1,
270
+ 0,
271
+ 0,
272
+ 1,
273
+ 0,
274
+ 0,
275
+ 1
276
+ ],
277
+ [
278
+ 1,
279
+ 0,
280
+ 1,
281
+ 0,
282
+ 0,
283
+ 1,
284
+ 0
285
+ ],
286
+ [
287
+ 1,
288
+ 1,
289
+ 1,
290
+ 1,
291
+ 1,
292
+ 1,
293
+ 1
294
+ ]
295
+ ],
296
+ "radix_digits": 8,
297
+ "pair_fact_order": [
298
+ 4,
299
+ 5,
300
+ 6,
301
+ 0,
302
+ 1,
303
+ 2,
304
+ 3
305
+ ]
306
+ }
307
+ },
308
+ "input_shapes": {
309
+ "features": [
310
+ 128
311
+ ]
312
+ },
313
+ "onnx_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
314
+ "fp16_coefficient_bytes": 32,
315
+ "learned_parameters": 0
316
+ }
labs/shave_models/boolean/industries/frontline/bundle/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5
3
+ size 192
labs/shave_models/boolean/industries/frontline/bundle/ncs1-native.blob ADDED
Binary file (512 Bytes). View file
 
labs/shave_models/boolean/needle3-tokenizer.m8t.xz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9
3
+ size 23412
labs/shave_models/boolean/policy.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Boolean expressions, evidence extraction and a reference independent of OpenVINO."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+ from collections import Counter, OrderedDict
6
+
7
+ import numpy as np
8
+
9
+ from compact_tokenizer import read_tokenizer
10
+
11
+
12
+ LIMIT = 131072
13
+ PARTS = re.compile(r'"(?:[^"\\]|\\.)*"|@[a-zA-Z_][a-zA-Z_0-9]*|AND\b|OR\b|NOT\b|[()]')
14
+ LEXEME = re.compile(r"\w+|[^\w\s]", re.UNICODE)
15
+ GROUPS = ("answers", "categories", "actions")
16
+ RULE_NAME = re.compile(r"[a-zA-Z_][a-zA-Z_0-9]*")
17
+
18
+
19
+ class Expression:
20
+ def __init__(self, text, named):
21
+ self.tokens = []
22
+ self.named = named
23
+ pos = 0
24
+ while pos < len(text):
25
+ if text[pos].isspace():
26
+ pos += 1
27
+ continue
28
+ match = PARTS.match(text, pos)
29
+ if not match:
30
+ raise ValueError("Unrecognized expression near %r" % text[pos:pos+20])
31
+ self.tokens.append(match.group())
32
+ pos = match.end()
33
+ self.i = 0
34
+
35
+ def take(self, token):
36
+ if self.i < len(self.tokens) and self.tokens[self.i] == token:
37
+ self.i += 1
38
+ return True
39
+ return False
40
+
41
+ def parse(self):
42
+ expr = self.either()
43
+ if self.i != len(self.tokens):
44
+ raise ValueError("Unexpected trailing expression")
45
+ return expr
46
+
47
+ def either(self):
48
+ expr = self.both()
49
+ while self.take("OR"):
50
+ expr = ("or", expr, self.both())
51
+ return expr
52
+
53
+ def both(self):
54
+ expr = self.term()
55
+ while self.take("AND"):
56
+ expr = ("and", expr, self.term())
57
+ return expr
58
+
59
+ def term(self):
60
+ if self.take("NOT"):
61
+ return ("not", self.term())
62
+ if self.take("("):
63
+ expr = self.either()
64
+ if not self.take(")"):
65
+ raise ValueError("Missing closing parenthesis")
66
+ return expr
67
+ if self.i >= len(self.tokens):
68
+ raise ValueError("Missing expression")
69
+ token = self.tokens[self.i]
70
+ self.i += 1
71
+ if token.startswith("@") and token[1:] in self.named:
72
+ return self.named[token[1:]]
73
+ if token.startswith('"'):
74
+ words = tuple(LEXEME.findall(json.loads(token).casefold()))
75
+ if words:
76
+ return ("literal", words)
77
+ raise ValueError("Expected a nonempty literal or earlier rule: " + token)
78
+
79
+
80
+ def value(node, facts):
81
+ op = node[0]
82
+ if op == "literal":
83
+ return facts[node[1]]
84
+ if op == "not":
85
+ return not value(node[1], facts)
86
+ if op == "and":
87
+ return value(node[1], facts) and value(node[2], facts)
88
+ return value(node[1], facts) or value(node[2], facts)
89
+
90
+
91
+ def word_character(character):
92
+ return character == "_" or character.isalnum()
93
+
94
+
95
+ def token_at(text, token, start):
96
+ if start < 0 or not text.startswith(token, start):
97
+ return False
98
+ if not word_character(token[0]):
99
+ return True
100
+ end = start + len(token)
101
+ return ((start == 0 or not word_character(text[start - 1]))
102
+ and (end == len(text) or not word_character(text[end])))
103
+
104
+
105
+ def anchored_match(text, phrase, anchor):
106
+ offset = 0
107
+ word = phrase[anchor]
108
+ # A dense adversarial anchor is cheaper to check with the full projection.
109
+ for _ in range(64):
110
+ match = text.find(word, offset)
111
+ if match < 0:
112
+ return False
113
+ offset = match + 1
114
+ if not token_at(text, word, match):
115
+ continue
116
+ left = match
117
+ for token in reversed(phrase[:anchor]):
118
+ while left and text[left - 1].isspace():
119
+ left -= 1
120
+ left -= len(token)
121
+ if not token_at(text, token, left):
122
+ break
123
+ else:
124
+ right = match + len(word)
125
+ for token in phrase[anchor + 1:]:
126
+ while right < len(text) and text[right].isspace():
127
+ right += 1
128
+ if not token_at(text, token, right):
129
+ break
130
+ right += len(token)
131
+ else:
132
+ return True
133
+ return None
134
+
135
+
136
+ class Policy:
137
+ def __init__(self, spec):
138
+ if not isinstance(spec, dict):
139
+ raise ValueError("Expected a JSON policy object")
140
+ for group in ("rules",) + GROUPS:
141
+ items = spec.get(group, {})
142
+ if not isinstance(items, dict) or any(not isinstance(expr, str) for expr in items.values()):
143
+ raise ValueError("Expected an object of Boolean strings for " + group)
144
+ rules = {}
145
+ for name, expression in spec.get("rules", {}).items():
146
+ if not RULE_NAME.fullmatch(name):
147
+ raise ValueError("Invalid rule name: " + name)
148
+ rules[name] = Expression(expression, rules).parse()
149
+ self.rules = rules
150
+ self.names, self.outputs = [], []
151
+ self.literals = []
152
+ def visit(node, found):
153
+ if node[0] == "literal":
154
+ if node[1] not in found:
155
+ found.append(node[1])
156
+ else:
157
+ for child in node[1:]:
158
+ visit(child, found)
159
+ for group in GROUPS:
160
+ for name, expression in spec.get(group, {}).items():
161
+ node = Expression(expression, rules).parse()
162
+ self.names.append((group, name))
163
+ self.outputs.append(node)
164
+ visit(node, self.literals)
165
+ if not self.literals:
166
+ raise ValueError("At least one evidence literal is required")
167
+ words = sorted({w for phrase in self.literals for w in phrase})
168
+ if len(words) > 255:
169
+ raise ValueError("The byte projection supports up to 255 different literal lexemes")
170
+ self.word_ids = {w: i+1 for i, w in enumerate(words)}
171
+ self.patterns = [bytes(self.word_ids[w] for w in p) for p in self.literals]
172
+ self.text_patterns = [self.literal_regex(words) for words in self.literals]
173
+ self.anchors = [max(range(len(words)), key=lambda i: len(words[i])) for words in self.literals]
174
+ explained = list(self.literals)
175
+ for node in self.rules.values():
176
+ visit(node, explained)
177
+ self.explanation_patterns = {words: self.literal_regex(words)
178
+ for words in explained[len(self.literals):]}
179
+
180
+ @staticmethod
181
+ def literal_regex(words):
182
+ # Place the left boundary check after the fixed prefix so the regex
183
+ # engine can use its native substring search on long documents.
184
+ first = re.escape(words[0])
185
+ def is_word(w):
186
+ return bool(re.fullmatch(r"\w+", w))
187
+ expr = first + (r"(?<!\w" + first + ")" if is_word(words[0]) else "")
188
+ for left, right in zip(words, words[1:]):
189
+ expr += (r"\s+" if is_word(left) and is_word(right) else r"\s*") + re.escape(right)
190
+ if is_word(words[-1]):
191
+ expr += r"(?!\w)"
192
+ return re.compile(expr)
193
+
194
+ def text_atoms(self, text):
195
+ folded = text.casefold()
196
+ return np.array([pattern.search(folded) is not None for pattern in self.text_patterns],
197
+ dtype=np.float32)
198
+
199
+ def anchored_atoms(self, text):
200
+ """Independently verify literal evidence, with a bounded projection fallback."""
201
+ folded = text.casefold()
202
+ flags = []
203
+ for phrase, anchor in zip(self.literals, self.anchors):
204
+ matched = anchored_match(folded, phrase, anchor)
205
+ if matched is None:
206
+ return self.atoms(self.project(text))
207
+ flags.append(matched)
208
+ return np.asarray(flags, dtype=np.float32)
209
+
210
+ def project(self, text):
211
+ # 0 represents every lexeme unused by this policy. Preserve occurrences
212
+ # and their order, including punctuation between adjacent phrase words.
213
+ return bytes(self.word_ids.get(w, 0) for w in LEXEME.findall(text.casefold()))
214
+
215
+ def atoms(self, encoded):
216
+ return np.array([p in encoded for p in self.patterns], dtype=np.float32)
217
+
218
+ def reference(self, atoms):
219
+ facts = dict(zip(self.literals, map(bool, atoms)))
220
+ return np.array([value(node, facts) for node in self.outputs], dtype=np.float32)
221
+
222
+ def result(self, bits):
223
+ out = {"answers": {}, "category": None, "action": None}
224
+ singular = {"categories": "category", "actions": "action"}
225
+ for (group, name), bit in zip(self.names, bits):
226
+ if group == "answers":
227
+ out[group][name] = bool(bit)
228
+ elif bit and out[singular[group]] is None:
229
+ out[singular[group]] = name
230
+ return out
231
+
232
+ def explain(self, text, atoms):
233
+ facts = dict(zip(self.literals, map(bool, atoms)))
234
+ if self.explanation_patterns:
235
+ folded = text.casefold()
236
+ facts.update({words: pattern.search(folded) is not None
237
+ for words, pattern in self.explanation_patterns.items()})
238
+ return {"matched": [" ".join(p) for p, present in facts.items() if present],
239
+ "named_rules": {key: bool(value(node, facts)) for key,node in self.rules.items()}}
240
+
241
+
242
+ def load_tokenizer(path=None):
243
+ import sentencepiece as spm
244
+ path = Path(path) if path else Path(__file__).with_name("needle3-tokenizer.m8t.xz")
245
+ return spm.SentencePieceProcessor(model_proto=read_tokenizer(path))
246
+
247
+
248
+ def needle_count(tokenizer, text, fast=True, memo=None):
249
+ if not fast or len(text) < 4096 or " " not in text:
250
+ return len(tokenizer.encode(text, out_type=int))
251
+ # The SHA-pinned BPE has identity normalization, no added leading space,
252
+ # byte fallback, and no regular piece with a non-initial metaspace. No
253
+ # user-defined symbol spans ASCII space. Thus merges cannot span these
254
+ # boundaries. Count each distinct space-prefixed segment once per request.
255
+ first, _, rest = text.partition(" ")
256
+ frequency = Counter(rest.split(" "))
257
+ total = len(tokenizer.encode(first, out_type=int))
258
+ if memo is not None:
259
+ missing = {}
260
+ for segment, repetitions in frequency.items():
261
+ count = memo.prior.get(segment)
262
+ if count is None:
263
+ count = memo.counts.get(segment)
264
+ if count is None:
265
+ missing[segment] = repetitions
266
+ else:
267
+ total += repetitions * count
268
+ frequency = missing
269
+ if not frequency:
270
+ return total
271
+ segments = list(frequency)
272
+ encodings = tokenizer.encode([" " + s for s in segments], out_type=int, num_threads=4)
273
+ for segment, ids in zip(segments, encodings):
274
+ count = len(ids)
275
+ total += frequency[segment] * count
276
+ if memo is not None and len(segment) <= 96:
277
+ memo.counts[segment] = count
278
+ if len(memo.counts) > memo.capacity:
279
+ memo.counts.popitem(last=False)
280
+ return total
281
+
282
+
283
+ class SegmentMemo:
284
+ """Bounded, process-local counts of exact space-prefixed segments."""
285
+
286
+ def __init__(self, capacity=8192, prior=None):
287
+ self.counts = OrderedDict()
288
+ self.capacity = capacity
289
+ self.prior = prior if prior is not None else {}
290
+
291
+
292
+ def tokenizer_prior(tokenizer):
293
+ """Seed reusable counts from the pinned vocabulary itself."""
294
+ metaspace = "\u2581"
295
+ words = (tokenizer.id_to_piece(i) for i in range(tokenizer.get_piece_size()))
296
+ # The pinned model encodes each of these 4,200 segments as one token.
297
+ # The differential test checks the entire set against SentencePiece.
298
+ return {word[1:]: 1 for word in words if word.startswith(metaspace)}
299
+
300
+
301
+ def validate_count(count):
302
+ if count > LIMIT:
303
+ raise ValueError("Input has %d Needle tokens; maximum is %d" % (count, LIMIT))
304
+ return count
305
+
306
+
307
+ def count_tokens(tokenizer, text, fast=False):
308
+ return validate_count(needle_count(tokenizer, text, fast=fast))
labs/shave_models/boolean/portable_runtime.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the MagicEightBall portable ONNX or GGUF profile on CPU."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+
10
+ from policy import LIMIT, load_tokenizer
11
+ from runtime import Runtime
12
+
13
+
14
+ ARCHITECTURE = "magiceightball"
15
+ PROFILE_REVISION = 1
16
+ TABLE = "decision.table"
17
+
18
+
19
+ class OnnxRequest:
20
+ def __init__(self, model):
21
+ from onnxruntime import InferenceSession, SessionOptions
22
+
23
+ options = SessionOptions()
24
+ options.intra_op_num_threads = 1
25
+ self.session = InferenceSession(model, sess_options=options, providers=["CPUExecutionProvider"])
26
+ self.outputs = [item.name for item in self.session.get_outputs()]
27
+
28
+ def infer(self, tensors):
29
+ return dict(zip(self.outputs, self.session.run(self.outputs, tensors)))
30
+
31
+
32
+ def read_gguf(path):
33
+ from gguf import GGMLQuantizationType, GGUFReader
34
+
35
+ model = GGUFReader(path)
36
+
37
+ def metadata(key):
38
+ field = model.get_field(key)
39
+ if field is None:
40
+ raise ValueError("Missing MagicEightBall GGUF metadata: " + key)
41
+ return field.contents()
42
+
43
+ if (metadata("general.architecture") != ARCHITECTURE
44
+ or metadata("magiceightball.profile_revision") != PROFILE_REVISION
45
+ or metadata("magiceightball.max_tokens") != LIMIT):
46
+ raise ValueError("Unsupported MagicEightBall GGUF profile")
47
+ manifest = {"name": ARCHITECTURE, "variant": "gguf",
48
+ "policy": json.loads(metadata("magiceightball.policy_json"))}
49
+ if len(model.tensors) != 1:
50
+ raise ValueError("MagicEightBall GGUF needs exactly one decision tensor")
51
+ tensor = model.tensors[0]
52
+ if tensor.name != TABLE or tensor.tensor_type != GGMLQuantizationType.I8 or tensor.data.ndim != 1:
53
+ raise ValueError("Expected a rank-one I8 decision.table tensor")
54
+ return manifest, tensor.data.copy()
55
+
56
+
57
+ class PortableRuntime(Runtime):
58
+ def __init__(self, artifact):
59
+ path = Path(artifact).resolve()
60
+ self.folder = path.parent
61
+ self.lane = "cpu"
62
+ self.target = "CPU"
63
+ self.fast_count = True
64
+ self.tokenizer = load_tokenizer()
65
+ suffix = path.suffix.lower()
66
+ if suffix == ".gguf":
67
+ self.bundle_info, self.table = read_gguf(path)
68
+ self._use_bank(None)
69
+ outputs = len(self.policy.outputs)
70
+ if (not 1 <= outputs <= 7 or len(self.table) != 1 << len(self.policy.literals)
71
+ or np.any(self.table < 0) or np.any(self.table >= 1 << outputs)):
72
+ raise ValueError("Decision tensor does not match the embedded policy")
73
+ elif suffix == ".onnx":
74
+ self.bundle_info = json.loads(path.with_name("model.json").read_text(encoding="utf8"))
75
+ self._use_bank(None)
76
+ model = path.read_bytes()
77
+ if self.info["variant"] not in ("gather", "dense") or (
78
+ hashlib.sha256(model).hexdigest() != self.info["onnx_sha256"]):
79
+ raise ValueError("Unexpected MagicEightBall ONNX artifact")
80
+ self.output = self.info["decisions"]
81
+ self.request = OnnxRequest(model)
82
+ else:
83
+ raise ValueError("Choose a MagicEightBall .onnx or .gguf file")
84
+
85
+ def head(self, atoms):
86
+ if self.info["variant"] != "gguf":
87
+ return super().head(atoms)
88
+ address = sum(int(bit) << index for index, bit in enumerate(atoms))
89
+ word = int(self.table[address])
90
+ return np.array([(word >> index) & 1 for index in range(len(self.policy.outputs))], dtype=np.float32)
91
+
92
+
93
+ def main():
94
+ parser = argparse.ArgumentParser(description=__doc__)
95
+ parser.add_argument("artifact", type=Path)
96
+ parser.add_argument("--explain", action="store_true")
97
+ source = parser.add_mutually_exclusive_group(required=True)
98
+ source.add_argument("--text")
99
+ source.add_argument("--file", type=Path)
100
+ args = parser.parse_args()
101
+ text = args.text if args.file is None else args.file.read_bytes().decode("utf-8-sig")
102
+ runtime = PortableRuntime(args.artifact)
103
+ try:
104
+ outcome = runtime.decide(text, explain=args.explain)
105
+ except ValueError as error:
106
+ parser.error(str(error))
107
+ print(json.dumps(dict(outcome, backend=runtime.target, format=args.artifact.suffix.lower()[1:])))
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
labs/shave_models/boolean/radix.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lossless integer words stored in the normal finite FP16 encodings."""
2
+ import numpy as np
3
+
4
+
5
+ SIGN_BIT = 0x8000
6
+ FIRST_NORMAL = 0x0400
7
+ NORMAL_PER_SIGN = 0x7800
8
+ CAPACITY = 2 * NORMAL_PER_SIGN
9
+
10
+
11
+ def encode_ranks(ranks):
12
+ ranks = np.asarray(ranks, dtype=np.int32)
13
+ if np.any((ranks < 0) | (ranks >= CAPACITY)):
14
+ raise ValueError("Radix word is outside the finite FP16 code space")
15
+ bits = FIRST_NORMAL + ranks + np.where(ranks < NORMAL_PER_SIGN, 0, SIGN_BIT - NORMAL_PER_SIGN)
16
+ return bits.astype(np.uint16).view(np.float16)
17
+
18
+
19
+ def decode_ranks(words):
20
+ halves = words
21
+ if words.dtype != np.float16:
22
+ if not np.isfinite(words).all() or np.any(np.abs(words) > 65504):
23
+ raise RuntimeError("Radix head returned an invalid FP16 word")
24
+ halves = words.astype(np.float16)
25
+ if not np.array_equal(halves, words):
26
+ raise RuntimeError("Radix head returned an inexact FP16 word")
27
+ bits = halves.view(np.uint16).astype(np.int32)
28
+ magnitude = bits & (SIGN_BIT - 1)
29
+ if np.any((magnitude < FIRST_NORMAL) | (magnitude >= FIRST_NORMAL + NORMAL_PER_SIGN)):
30
+ raise RuntimeError("Radix head returned a non-normal FP16 word")
31
+ return magnitude - FIRST_NORMAL + np.where(bits & SIGN_BIT, NORMAL_PER_SIGN, 0)
labs/shave_models/boolean/release.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transport a Gather manifest and both native 2020.3 blobs losslessly."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import struct
6
+ import zlib
7
+
8
+ from blob_layout import compact_gather_blob, inspect_blob
9
+
10
+
11
+ MAGIC = b"M8B1"
12
+ HEADER = struct.Struct("<4s3I")
13
+ TARGETS = {"ncs1": ("ncs1-native.blob", "VPU_MYRIAD_2450"),
14
+ "ncs2": ("ncs2-2020.3.blob", "VPU_MYRIAD_2480")}
15
+
16
+
17
+ def _validate(manifest, blobs):
18
+ if not isinstance(manifest, dict) or manifest.get("variant") != "gather":
19
+ raise ValueError("Release requires a Gather manifest")
20
+ inputs = manifest.get("input_shapes")
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
+
44
+
45
+ def read_release(path):
46
+ try:
47
+ data = zlib.decompress(path.read_bytes())
48
+ except zlib.error as exc:
49
+ raise ValueError("Unreadable MagicEightBall release") from exc
50
+ if len(data) < HEADER.size:
51
+ raise ValueError("Missing MagicEightBall release header")
52
+ magic, manifest_size, ncs1_size, ncs2_size = HEADER.unpack_from(data)
53
+ boundary = HEADER.size + manifest_size
54
+ split = boundary + ncs1_size
55
+ if magic != MAGIC or split + ncs2_size != len(data):
56
+ raise ValueError("Invalid MagicEightBall release layout")
57
+ manifest = json.loads(data[HEADER.size:boundary])
58
+ blobs = {"ncs1": data[boundary:split], "ncs2": data[split:]}
59
+ _validate(manifest, blobs)
60
+ return manifest, blobs
61
+
62
+
63
+ if __name__ == "__main__":
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))
labs/shave_models/boolean/runtime.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent MYRIAD runner for document-wide Boolean policies."""
2
+ import argparse
3
+ from copy import copy
4
+ from dataclasses import dataclass
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from typing import Optional
14
+
15
+ import numpy as np
16
+ from policy import Policy, count_tokens, load_tokenizer, validate_count
17
+ from radix import decode_ranks
18
+ from release import TARGETS, read_release
19
+
20
+
21
+ @dataclass
22
+ class Prepared:
23
+ tokens: int
24
+ atoms: Optional[np.ndarray]
25
+ projected: Optional[bytes]
26
+ started: float
27
+ counted: float
28
+ ready: float
29
+
30
+
31
+ class Runtime:
32
+ def __init__(self, bundle, toolchain=None, fast_count=True, lane="ncs1", target=None, blob=None, bank=None,
33
+ release_stick="ncs1"):
34
+ self.folder = Path(bundle).resolve()
35
+ native_release = None
36
+ if self.folder.suffix.lower() == ".m8b":
37
+ if lane != "ncs1" or blob is not None:
38
+ raise ValueError("Release archives use the 2020.3 runtime and contain their own native blobs")
39
+ if release_stick not in TARGETS:
40
+ raise ValueError("Choose ncs1 or ncs2 for the native release")
41
+ self.bundle_info, blobs = read_release(self.folder)
42
+ native_release = blobs[release_stick]
43
+ else:
44
+ self.bundle_info = json.loads((self.folder/"model.json").read_text(encoding="utf8"))
45
+ self._use_bank(bank)
46
+ self.tokenizer = load_tokenizer()
47
+ self.fast_count = fast_count
48
+ self.lane = lane
49
+ self.output = self.info["decisions"]
50
+ if lane == "ncs1":
51
+ if toolchain is None:
52
+ toolchain = Path(__file__).resolve().parents[3] / "tools" / "ncs1"
53
+ sys.path.insert(0, str(Path(toolchain).resolve()))
54
+ import ncs1_paths
55
+ ncs1_paths.setup()
56
+ from openvino.inference_engine import IECore, get_version
57
+ self.core = IECore()
58
+ elif lane == "ncs2":
59
+ from openvino.runtime import Core, get_version
60
+ self.core = Core()
61
+ else:
62
+ raise ValueError("Unknown MYRIAD lane: " + lane)
63
+ self.openvino_version = get_version()
64
+ self.devices = list(self.core.available_devices)
65
+ myriad = [name for name in self.devices if name.split(".", 1)[0] == "MYRIAD"]
66
+ if not myriad:
67
+ raise RuntimeError("No physical MYRIAD device visible to %s (%s)" % (lane, self.openvino_version))
68
+ if target is None and len(myriad) != 1:
69
+ raise ValueError("Choose --target from %s" % myriad)
70
+ self.target = target if target is not None else myriad[0]
71
+ if self.target not in myriad:
72
+ raise ValueError("Expected a visible MYRIAD device from %s" % myriad)
73
+
74
+ self.ir = None if blob is not None or native_release is not None else self.resolve_ir()
75
+ start = time.perf_counter()
76
+ if lane == "ncs1":
77
+ if native_release is not None:
78
+ platform = TARGETS[release_stick][1]
79
+ config = {"VPU_MYRIAD_PLATFORM": platform, "VPU_MYRIAD_PROTOCOL": "VPU_MYRIAD_USB"}
80
+ with tempfile.TemporaryDirectory(prefix="magiceightball-") as directory:
81
+ native = Path(directory) / "network.blob"
82
+ native.write_bytes(native_release)
83
+ self.compiled = self.core.import_network(str(native), self.target, config=config, num_requests=1)
84
+ elif blob is not None:
85
+ self.compiled = self.core.import_network(str(blob), self.target, num_requests=1)
86
+ else:
87
+ net = self.core.read_network(model=str(self.ir), weights=str(self.ir.with_suffix(".bin")))
88
+ if self.output not in net.outputs and not (self.info["variant"] == "gather" and len(net.outputs) == 1):
89
+ raise ValueError("Unexpected IR outputs: %s" % list(net.outputs))
90
+ if self.info["variant"] == "gather":
91
+ net.outputs[next(iter(net.outputs))].precision = "FP16"
92
+ self.compiled = self.core.load_network(network=net, device_name=self.target, num_requests=1)
93
+ self.request = self.compiled
94
+ else:
95
+ self.compiled = (self.core.import_model(blob.read_bytes(), self.target) if blob is not None
96
+ else self.core.compile_model(str(self.ir), self.target))
97
+ self.output = self.compiled.output(0 if self.info["variant"] == "gather" else self.output)
98
+ self.request = self.compiled.create_infer_request()
99
+ self.load_ms = 1000*(time.perf_counter()-start)
100
+
101
+ def _use_bank(self, bank):
102
+ banks = self.bundle_info.get("banks", {})
103
+ self.bank = self.bundle_info.get("default_bank") if bank is None else bank
104
+ if self.bank is not None and (not isinstance(self.bank, str) or self.bank not in banks):
105
+ raise ValueError("Unknown policy bank: %r" % (self.bank,))
106
+ self.info = dict(self.bundle_info, **banks.get(self.bank, {}))
107
+ self.policy = Policy(self.info["policy"])
108
+ self.model_name = self.bundle_info.get("name", self.info["policy"].get("name", self.folder.name))
109
+
110
+ def policy_view(self, bank):
111
+ if bank is None or bank == self.bank:
112
+ return self
113
+ view = copy(self)
114
+ view._use_bank(bank)
115
+ return view
116
+
117
+ def resolve_ir(self):
118
+ source = self.folder/"model.onnx"
119
+ model_hash = hashlib.sha256(source.read_bytes()).hexdigest()
120
+ if model_hash != self.info["onnx_sha256"]:
121
+ raise ValueError("Unexpected ONNX artifact")
122
+ ir = self.folder/"ir"/model_hash
123
+ xml = ir/"model.xml"
124
+ binary = ir/"model.bin"
125
+ if not xml.exists() or not binary.exists():
126
+ if self.lane == "ncs1":
127
+ import ncs1_paths
128
+ ir.mkdir(exist_ok=True, parents=True)
129
+ subprocess.run([sys.executable, str(ncs1_paths.MO/"mo_onnx.py"),
130
+ "--input_model", str(source), "--data_type", "FP16",
131
+ "--output_dir", str(ir)], timeout=120, check=True,
132
+ env=dict(os.environ, PYTHONPATH=str(ncs1_paths.MO)))
133
+ else:
134
+ from openvino.runtime import serialize
135
+ from openvino.tools.mo import convert_model
136
+ # Cache separately so a new toolchain never overwrites the IR10 pair.
137
+ xml = ir / "2022.3" / "model.xml"
138
+ if not xml.exists() or not xml.with_suffix(".bin").exists():
139
+ xml.parent.mkdir(exist_ok=True, parents=True)
140
+ serialize(convert_model(str(source), compress_to_fp16=True), str(xml))
141
+ return xml
142
+
143
+ def export_blob(self, path):
144
+ if self.lane == "ncs1":
145
+ self.compiled.export(str(path))
146
+ else:
147
+ path.write_bytes(self.compiled.export_model())
148
+
149
+ def head(self, atoms):
150
+ variant = self.info["variant"]
151
+ if variant == "gather":
152
+ return self.gather_heads([atoms])[0]
153
+ if variant in ("lookup", "packed"):
154
+ mask = sum(int(bit) << j for j, bit in enumerate(atoms))
155
+ features = np.zeros(self.info["input_shapes"]["features"], dtype=np.float32)
156
+ features[0, mask >> self.info.get("lane_bits", 0), 0, 0] = 1
157
+ packed = self.request.infer({"features": features})[self.output].reshape(-1)
158
+ self.validate_words(packed)
159
+ if variant == "packed":
160
+ return self.unpack(packed[0], mask)
161
+ return np.array([(int(packed[k//10]) >> (k%10)) & 1
162
+ for k in range(len(self.policy.outputs))],dtype=np.float32)
163
+ result = self.request.infer({"features": atoms.reshape(1,-1,1,1)})
164
+ return result[self.output].reshape(-1).copy()
165
+
166
+ @property
167
+ def batch_capacity(self):
168
+ return self.info["input_shapes"]["features"][0] if self.info["variant"] == "gather" else 1
169
+
170
+ @staticmethod
171
+ def validate_words(packed):
172
+ if not np.isfinite(packed).all() or not np.array_equal(packed, packed.round()):
173
+ raise RuntimeError("Invalid output from exact lookup head")
174
+
175
+ def unpack(self, number, mask):
176
+ lane = mask & ((1 << self.info["lane_bits"]) - 1)
177
+ width = self.info["code_width"]
178
+ offset = self.info["offset"]
179
+ word = int(number) + offset
180
+ code = (word >> (lane * width)) & ((1 << width) - 1)
181
+ codebook = self.info["codebook"]
182
+ if not 0 <= word < 2 * offset or code >= len(codebook):
183
+ raise RuntimeError("Invalid codeword from exact packed head")
184
+ return np.asarray(codebook[code], dtype=np.float32)
185
+
186
+ def _gather_indices(self, facts):
187
+ pair_order = self.info.get("pair_fact_order")
188
+ if pair_order is None:
189
+ masks = [sum(int(bit) << j for j, bit in enumerate(row)) for row in facts]
190
+ else:
191
+ masks = [sum(int(row[fact]) << bit for bit, fact in enumerate(pair_order)) for row in facts]
192
+ radix_digits = self.info.get("radix_digits")
193
+ offset = self.info.get("bank_offset", 0)
194
+ if radix_digits is None:
195
+ addresses = [offset + (mask >> self.info["lane_bits"]) for mask in masks]
196
+ else:
197
+ addresses = [offset + mask // radix_digits for mask in masks]
198
+ return addresses, masks
199
+
200
+ def _gather_words(self, addresses):
201
+ if not 1 <= len(addresses) <= self.batch_capacity:
202
+ raise ValueError("Gather needs 1–%d decisions per request" % self.batch_capacity)
203
+ features = np.zeros(self.batch_capacity, dtype=np.int32)
204
+ features[:len(addresses)] = addresses
205
+ outputs = self.request.infer({"features": features})
206
+ # The legacy ONNX converter renames the sole Gather output.
207
+ if len(outputs) != 1:
208
+ raise RuntimeError("Expected exactly one packed Gather result")
209
+ words = next(iter(outputs.values())).reshape(-1)
210
+ if words.size != self.batch_capacity:
211
+ raise RuntimeError("Unexpected Gather result width")
212
+ if self.lane == "ncs1" and words.dtype == np.int16:
213
+ # IECore 2020.3 exposes native FP16 buffers as signed words.
214
+ words = words.view(np.float16)
215
+ return words[:len(addresses)]
216
+
217
+ def _gather_decode(self, used, masks):
218
+ radix_digits = self.info.get("radix_digits")
219
+ if radix_digits is not None:
220
+ ranks = decode_ranks(used)
221
+ codebook = np.asarray(self.info["codebook"], dtype=np.float32)
222
+ base = len(codebook)
223
+ if "pair_fact_order" in self.info:
224
+ if np.any(ranks >= base * base * 256):
225
+ raise RuntimeError("Radix head returned an invalid policy pair")
226
+ results = []
227
+ for rank, mask in zip(ranks, masks):
228
+ pair, selectors = divmod(int(rank), 256)
229
+ low, high = divmod(pair, base)
230
+ if high < low:
231
+ raise RuntimeError("Radix head returned an unordered policy pair")
232
+ results.append(codebook[high if selectors & (1 << (mask & 7)) else low])
233
+ return results
234
+ if np.any(ranks >= base ** radix_digits):
235
+ raise RuntimeError("Radix head returned an invalid policy word")
236
+ return [codebook[(int(rank) // base ** (mask % radix_digits)) % base]
237
+ for rank, mask in zip(ranks, masks)]
238
+ self.validate_words(used)
239
+ return [self.unpack(word, mask) for word, mask in zip(used, masks)]
240
+
241
+ def gather_heads(self, facts):
242
+ addresses, masks = self._gather_indices(facts)
243
+ return self._gather_decode(self._gather_words(addresses), masks)
244
+
245
+ def scan(self, projected):
246
+ side = self.info["tile_side"]
247
+ halo = max(map(len, self.policy.patterns))-1
248
+ count = max(1, (len(projected)+side*side-1)//(side*side))
249
+ storage = np.zeros(halo + count*side*side, dtype=np.float32)
250
+ storage[halo:halo+len(projected)] = np.frombuffer(projected, dtype=np.uint8)
251
+ prior = np.zeros((1,len(self.policy.literals),1,1), dtype=np.float32)
252
+ # Each row includes the real preceding lexemes. A phrase can cross either
253
+ # a row or a USB request boundary. Padding code 0 matches no literal.
254
+ rows = np.lib.stride_tricks.as_strided(storage, shape=(count*side, side+halo),
255
+ strides=(side*storage.itemsize,storage.itemsize),
256
+ writeable=False)
257
+ for i in range(count):
258
+ tile = np.ascontiguousarray(rows[i*side:(i+1)*side])[None,None]
259
+ result = self.request.infer({"lexemes": tile, "prior": prior})
260
+ values = result[self.output].reshape(-1)
261
+ n = self.info["state_channels"]
262
+ prior = values[:n].reshape(1,n,1,1).copy()
263
+ return values[n:].copy(), prior.reshape(-1), count
264
+
265
+ def prepare_decision(self, text, prepare=None):
266
+ start = time.perf_counter()
267
+ projected = atoms = None
268
+ scanning = self.info["variant"] == "scan"
269
+ if prepare is not None:
270
+ if scanning:
271
+ raise ValueError("Batch lane selection needs a decision head that accepts fact bits")
272
+ tokens, atoms, counted = prepare(text)
273
+ validate_count(tokens)
274
+ else:
275
+ tokens = count_tokens(self.tokenizer, text, fast=self.fast_count)
276
+ counted = time.perf_counter()
277
+ if scanning or not self.fast_count:
278
+ projected = self.policy.project(text)
279
+ if not scanning:
280
+ atoms = self.policy.atoms(projected)
281
+ else:
282
+ atoms = self.policy.text_atoms(text)
283
+ return Prepared(tokens, atoms, projected, start, counted, time.perf_counter())
284
+
285
+ def decide_prepared(self, documents):
286
+ if not 1 <= len(documents) <= self.batch_capacity:
287
+ raise ValueError("Unexpected number of prepared documents")
288
+ start = time.perf_counter()
289
+ variant = self.info["variant"]
290
+ if variant == "scan":
291
+ document = documents[0]
292
+ bits, atoms, calls = self.scan(document.projected)
293
+ decisions = [(bits, atoms)]
294
+ elif variant == "gather":
295
+ facts = [document.atoms for document in documents]
296
+ decisions = list(zip(self.gather_heads(facts), facts))
297
+ calls = 1
298
+ else:
299
+ atoms = documents[0].atoms
300
+ decisions = [(self.head(atoms), atoms)]
301
+ calls = 1
302
+ return [self._record(doc, bits, atoms, calls, len(documents), start)
303
+ for doc, (bits, atoms) in zip(documents, decisions)]
304
+
305
+ def _record(self, doc, bits, atoms, calls, group_size, start):
306
+ result = self.policy.result(bits > 0.5)
307
+ end = time.perf_counter()
308
+ record = dict(
309
+ model=self.model_name, result=result, bits=bits.tolist(), atoms=atoms.tolist(),
310
+ needle_tokens=doc.tokens, lexemes=len(doc.projected) if doc.projected is not None else None,
311
+ requests=calls, request_documents=group_size, tokenization_ms=(doc.counted-doc.started)*1000,
312
+ host_projection_ms=(doc.ready-doc.counted)*1000,
313
+ inference_path_ms=(end-start)*1000, total_ms=(end-doc.started)*1000,
314
+ )
315
+ if getattr(self, "bank", None) is not None:
316
+ record["bank"] = self.bank
317
+ return record
318
+
319
+ def decide_mixed(self, documents, explain=False):
320
+ """Submit documents from several policy banks in the same Gather request."""
321
+ if self.info["variant"] != "gather" or not isinstance(documents, list) or not documents:
322
+ raise ValueError("A Gather batch needs a nonempty documents array")
323
+ results, pending, views = [None] * len(documents), [], {}
324
+ requests = 0
325
+
326
+ def flush():
327
+ nonlocal requests
328
+ if not pending:
329
+ return
330
+ start = time.perf_counter()
331
+ groups = {}
332
+ for position, (_, view, _, doc) in enumerate(pending):
333
+ groups.setdefault(view, []).append((position, doc.atoms))
334
+ addresses = np.empty(len(pending), dtype=np.int32)
335
+ indices = {}
336
+ for view, entries in groups.items():
337
+ positions, facts = zip(*entries)
338
+ bank_addresses, masks = view._gather_indices(facts)
339
+ addresses[list(positions)] = bank_addresses
340
+ indices[view] = (list(positions), masks)
341
+ words = self._gather_words(addresses)
342
+ requests += 1
343
+ for view, (positions, masks) in indices.items():
344
+ for position, bits in zip(positions, view._gather_decode(words[positions], masks)):
345
+ index, _, text, doc = pending[position]
346
+ record = view._record(doc, bits, doc.atoms, 1, len(pending), start)
347
+ if explain:
348
+ record["explanation"] = view.policy.explain(text, doc.atoms)
349
+ results[index] = dict(record, id=documents[index].get("id"))
350
+ pending.clear()
351
+
352
+ for index, row in enumerate(documents):
353
+ request_id = row.get("id") if isinstance(row, dict) else None
354
+ try:
355
+ if not isinstance(row, dict) or not isinstance(row.get("text"), str):
356
+ raise ValueError("Each document needs a text string")
357
+ bank = row.get("bank")
358
+ if bank is not None and not isinstance(bank, str):
359
+ raise ValueError("Policy bank must be a string")
360
+ if bank not in views:
361
+ views[bank] = self.policy_view(bank)
362
+ view = views[bank]
363
+ pending.append((index, view, row["text"], view.prepare_decision(row["text"])))
364
+ except ValueError as exc:
365
+ results[index] = {"id": request_id, "error": str(exc)}
366
+ continue
367
+ if len(pending) == self.batch_capacity:
368
+ flush()
369
+ flush()
370
+ return {"documents": results, "device_requests": requests}
371
+
372
+ def decide(self, text, explain=False, prepare=None):
373
+ record = self.decide_prepared([self.prepare_decision(text, prepare)])[0]
374
+ if explain:
375
+ record["explanation"] = self.policy.explain(text, record["atoms"])
376
+ return record
377
+
378
+
379
+ def json_output_stream():
380
+ # Legacy MYRIAD prints firmware messages to native stdout, including
381
+ # during teardown. Save the caller's stream and redirect diagnostics
382
+ # before loading the plugin so stdout remains a clean JSON protocol.
383
+ sys.stdout.flush()
384
+ stdout_fd = sys.stdout.fileno()
385
+ output = os.fdopen(os.dup(stdout_fd), "w", encoding="utf8")
386
+ os.dup2(sys.stderr.fileno(), stdout_fd)
387
+ if os.name == "nt":
388
+ import ctypes
389
+ from ctypes import wintypes
390
+ import msvcrt
391
+ set_handle = ctypes.windll.kernel32.SetStdHandle
392
+ set_handle.argtypes = (wintypes.DWORD, wintypes.HANDLE)
393
+ set_handle.restype = wintypes.BOOL
394
+ if not set_handle(0xFFFFFFF5, msvcrt.get_osfhandle(stdout_fd)): # STD_OUTPUT_HANDLE
395
+ output.close()
396
+ raise OSError("Could not redirect native stdout")
397
+ return output
398
+
399
+
400
+ def main():
401
+ parser = argparse.ArgumentParser(description=__doc__)
402
+ parser.add_argument("bundle", type=Path)
403
+ parser.add_argument("--toolchain", type=Path, help="Override the NCS1 toolchain directory")
404
+ parser.add_argument("--lane", choices=["ncs1", "ncs2"], default="ncs1")
405
+ parser.add_argument("--target", help="Explicit OpenVINO name when several MYRIAD devices are visible")
406
+ parser.add_argument("--blob", type=Path, help="Load a binary exported by the matching device/toolchain")
407
+ parser.add_argument("--bank", help="Default policy bank for a banked bundle")
408
+ parser.add_argument("--release-stick", choices=list(TARGETS), default="ncs1",
409
+ help="Physical target for a .m8b archive on OpenVINO 2020.3")
410
+ parser.add_argument("--explain", action="store_true")
411
+ source = parser.add_mutually_exclusive_group(required=True)
412
+ source.add_argument("--text")
413
+ source.add_argument("--file", type=Path)
414
+ source.add_argument("--serve", action="store_true", help="Read one JSON request with text and optional id per line")
415
+ source.add_argument("--stream", action="store_true", help="Append JSONL fragments to one resident document")
416
+ args = parser.parse_args()
417
+ with json_output_stream() as output:
418
+ engine = Runtime(args.bundle, args.toolchain, lane=args.lane, target=args.target, blob=args.blob, bank=args.bank,
419
+ release_stick=args.release_stick)
420
+ if args.serve or args.stream:
421
+ stream = None
422
+ if args.stream:
423
+ from stream import DecisionStream
424
+ stream = DecisionStream(engine, args.explain)
425
+ for line in sys.stdin.buffer:
426
+ request_id = None
427
+ try:
428
+ request = json.loads(line)
429
+ if not isinstance(request, dict):
430
+ raise ValueError("Expected an object with a text string")
431
+ request_id = request.get("id")
432
+ if stream is not None:
433
+ if "append" not in request and request.get("reset") is not True:
434
+ raise ValueError("Expected an append string or reset=true")
435
+ response = stream.append(request.get("append", ""), request.get("reset", False))
436
+ elif "documents" in request:
437
+ response = engine.decide_mixed(request["documents"], args.explain)
438
+ elif not isinstance(request.get("text"), str):
439
+ raise ValueError("Expected an object with a text string")
440
+ else:
441
+ response = engine.policy_view(request.get("bank")).decide(request["text"], args.explain)
442
+ except ValueError as exc:
443
+ response = {"error": str(exc)}
444
+ except RuntimeError as exc:
445
+ if stream is None:
446
+ raise
447
+ response = {"error": str(exc)}
448
+ print(json.dumps(dict(response, id=request_id)), file=output, flush=True)
449
+ else:
450
+ document = args.text if args.text is not None else args.file.read_bytes().decode("utf8")
451
+ print(json.dumps(engine.decide(document, args.explain)), file=output)
452
+
453
+
454
+ if __name__ == "__main__":
455
+ main()
labs/shave_models/boolean/stream.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental evidence and Needle token counts for one append-only document."""
2
+ from dataclasses import dataclass
3
+ import time
4
+
5
+ import numpy as np
6
+
7
+ from policy import SegmentMemo, needle_count, validate_count
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class StreamState:
12
+ tokens: int
13
+ suffix: str
14
+ halo: bytes
15
+ stable_facts: np.ndarray
16
+ explanation_text: str
17
+
18
+
19
+ class DecisionStream:
20
+ def __init__(self, engine, explain=False):
21
+ if engine.info["variant"] == "scan":
22
+ raise ValueError("Streaming requires a decision head that accepts fact bits")
23
+ self.engine = engine
24
+ self.explain = explain
25
+ self.memo = SegmentMemo()
26
+ self.halo_size = max(map(len, engine.policy.patterns)) - 1
27
+ self.state = self.empty_state()
28
+
29
+ def empty_state(self):
30
+ facts = np.zeros(len(self.engine.policy.literals), dtype=np.float32)
31
+ return StreamState(0, "", b"", facts, "")
32
+
33
+ def _initial_halo(self, text):
34
+ if not self.halo_size:
35
+ return b""
36
+ width = 256
37
+ while width < len(text):
38
+ begin = text.find(" ", len(text) - width)
39
+ if begin >= 0:
40
+ encoded = self.engine.policy.project(text[begin:])
41
+ if len(encoded) >= self.halo_size:
42
+ return encoded[-self.halo_size:]
43
+ width *= 2
44
+ return self.engine.policy.project(text)[-self.halo_size:]
45
+
46
+ def append(self, fragment, reset=False):
47
+ if not isinstance(fragment, str) or type(reset) is not bool:
48
+ raise ValueError("Append must be a string and reset must be a Boolean")
49
+ current = self.empty_state() if reset else self.state
50
+ next_state = None
51
+ policy = self.engine.policy
52
+
53
+ def prepare(delta):
54
+ nonlocal next_state
55
+ pending = current.suffix + delta
56
+ split = pending.rfind(" ")
57
+ committed = pending[:split] if split > 0 else ""
58
+ suffix = pending[split:] if split > 0 else pending
59
+
60
+ # The pinned Needle model cannot merge across an ASCII space. Keep
61
+ # that space with the uncommitted segment so its prefix is exact.
62
+ stable_tokens = current.tokens + needle_count(self.engine.tokenizer, committed, memo=self.memo)
63
+ tokens = validate_count(stable_tokens + needle_count(self.engine.tokenizer, suffix, memo=self.memo))
64
+ counted = time.perf_counter()
65
+
66
+ if not current.halo and len(committed) >= 4096:
67
+ stable_facts = np.maximum(current.stable_facts, policy.text_atoms(committed))
68
+ halo = self._initial_halo(committed)
69
+ else:
70
+ text = current.halo + policy.project(committed)
71
+ stable_facts = np.maximum(current.stable_facts, policy.atoms(text))
72
+ halo = text[-self.halo_size:] if self.halo_size else b""
73
+ tail_facts = policy.atoms(halo + policy.project(suffix)) if halo else policy.text_atoms(suffix)
74
+ facts = np.maximum(stable_facts, tail_facts)
75
+ explanation_text = current.explanation_text + delta if self.explain else ""
76
+ next_state = StreamState(stable_tokens, suffix, halo, stable_facts, explanation_text)
77
+ return tokens, facts, counted
78
+
79
+ prepared = self.engine.prepare_decision(fragment, prepare=prepare)
80
+ result = self.engine.decide_prepared([prepared])[0]
81
+ if self.explain:
82
+ result["explanation"] = policy.explain(next_state.explanation_text, prepared.atoms)
83
+ # A rejected append or a failed inference leaves the previous stream intact.
84
+ self.state = next_state
85
+ return result
labs/shave_models/boolean/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()
measurements/industry-results.json ADDED
@@ -0,0 +1,1973 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "railshot.industry-replay/1",
3
+ "ranges": [
4
+ {
5
+ "bank": "dealership",
6
+ "backend": "cpu",
7
+ "passes": 8,
8
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
9
+ "identity": {
10
+ "adapter": "magiceightball/1",
11
+ "artifact_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
12
+ "bank": "dealership",
13
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
14
+ },
15
+ "process_1": {
16
+ "requests": [
17
+ {
18
+ "stream_id": "active",
19
+ "seq": 1,
20
+ "append": "Service requested. Intake ",
21
+ "reset": false
22
+ },
23
+ {
24
+ "stream_id": "active",
25
+ "seq": 3,
26
+ "append": "Skipped",
27
+ "reset": false
28
+ },
29
+ {
30
+ "stream_id": "active",
31
+ "seq": 2,
32
+ "append": "approved.",
33
+ "reset": false
34
+ },
35
+ {
36
+ "stream_id": "unrelated",
37
+ "seq": 1,
38
+ "append": "Routine note only.",
39
+ "reset": false
40
+ }
41
+ ],
42
+ "responses": [
43
+ {
44
+ "decision": {
45
+ "atoms": [
46
+ 1.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0
53
+ ],
54
+ "bank": "dealership",
55
+ "bits": [
56
+ 0.0,
57
+ 0.0,
58
+ 1.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.0
63
+ ],
64
+ "lexemes": null,
65
+ "model": "magiceightball",
66
+ "needle_tokens": 8,
67
+ "request_documents": 1,
68
+ "requests": 1,
69
+ "result": {
70
+ "action": null,
71
+ "answers": {
72
+ "may_route": false
73
+ },
74
+ "category": "service"
75
+ }
76
+ },
77
+ "ok": true,
78
+ "schema": "railshot.result/1",
79
+ "seq": 1,
80
+ "stream_id": "active"
81
+ },
82
+ {
83
+ "error": {
84
+ "code": "out_of_order",
85
+ "expected_seq": 2,
86
+ "message": "Expected the next contiguous seq"
87
+ },
88
+ "ok": false,
89
+ "schema": "railshot.result/1",
90
+ "seq": 3,
91
+ "stream_id": "active"
92
+ },
93
+ {
94
+ "decision": {
95
+ "atoms": [
96
+ 1.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 1.0,
101
+ 0.0,
102
+ 0.0
103
+ ],
104
+ "bank": "dealership",
105
+ "bits": [
106
+ 1.0,
107
+ 0.0,
108
+ 1.0,
109
+ 0.0,
110
+ 0.0,
111
+ 1.0,
112
+ 0.0
113
+ ],
114
+ "lexemes": null,
115
+ "model": "magiceightball",
116
+ "needle_tokens": 10,
117
+ "request_documents": 1,
118
+ "requests": 1,
119
+ "result": {
120
+ "action": "review_service_intake",
121
+ "answers": {
122
+ "may_route": true
123
+ },
124
+ "category": "service"
125
+ }
126
+ },
127
+ "ok": true,
128
+ "schema": "railshot.result/1",
129
+ "seq": 2,
130
+ "stream_id": "active"
131
+ },
132
+ {
133
+ "decision": {
134
+ "atoms": [
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0
142
+ ],
143
+ "bank": "dealership",
144
+ "bits": [
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0,
149
+ 0.0,
150
+ 0.0,
151
+ 0.0
152
+ ],
153
+ "lexemes": null,
154
+ "model": "magiceightball",
155
+ "needle_tokens": 6,
156
+ "request_documents": 1,
157
+ "requests": 1,
158
+ "result": {
159
+ "action": null,
160
+ "answers": {
161
+ "may_route": false
162
+ },
163
+ "category": null
164
+ }
165
+ },
166
+ "ok": true,
167
+ "schema": "railshot.result/1",
168
+ "seq": 1,
169
+ "stream_id": "unrelated"
170
+ }
171
+ ]
172
+ },
173
+ "process_2": {
174
+ "requests": [
175
+ {
176
+ "stream_id": "active",
177
+ "seq": 2,
178
+ "append": "approved.",
179
+ "reset": false
180
+ },
181
+ {
182
+ "stream_id": "active",
183
+ "seq": 3,
184
+ "append": " Customer declined.",
185
+ "reset": false
186
+ },
187
+ {
188
+ "stream_id": "active",
189
+ "seq": 2,
190
+ "append": "Conflicting approval",
191
+ "reset": false
192
+ },
193
+ {
194
+ "stream_id": "active",
195
+ "seq": 4,
196
+ "append": "Service requested. Intake approved.",
197
+ "reset": true
198
+ }
199
+ ],
200
+ "responses": [
201
+ {
202
+ "decision": {
203
+ "atoms": [
204
+ 1.0,
205
+ 0.0,
206
+ 0.0,
207
+ 0.0,
208
+ 1.0,
209
+ 0.0,
210
+ 0.0
211
+ ],
212
+ "bank": "dealership",
213
+ "bits": [
214
+ 1.0,
215
+ 0.0,
216
+ 1.0,
217
+ 0.0,
218
+ 0.0,
219
+ 1.0,
220
+ 0.0
221
+ ],
222
+ "lexemes": null,
223
+ "model": "magiceightball",
224
+ "needle_tokens": 10,
225
+ "request_documents": 1,
226
+ "requests": 1,
227
+ "result": {
228
+ "action": "review_service_intake",
229
+ "answers": {
230
+ "may_route": true
231
+ },
232
+ "category": "service"
233
+ }
234
+ },
235
+ "ok": true,
236
+ "schema": "railshot.result/1",
237
+ "seq": 2,
238
+ "stream_id": "active"
239
+ },
240
+ {
241
+ "decision": {
242
+ "atoms": [
243
+ 1.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 1.0,
248
+ 0.0,
249
+ 1.0
250
+ ],
251
+ "bank": "dealership",
252
+ "bits": [
253
+ 0.0,
254
+ 0.0,
255
+ 1.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0
260
+ ],
261
+ "lexemes": null,
262
+ "model": "magiceightball",
263
+ "needle_tokens": 16,
264
+ "request_documents": 1,
265
+ "requests": 1,
266
+ "result": {
267
+ "action": null,
268
+ "answers": {
269
+ "may_route": false
270
+ },
271
+ "category": "service"
272
+ }
273
+ },
274
+ "ok": true,
275
+ "schema": "railshot.result/1",
276
+ "seq": 3,
277
+ "stream_id": "active"
278
+ },
279
+ {
280
+ "error": {
281
+ "code": "conflicting_retry",
282
+ "message": "This seq already has a different request"
283
+ },
284
+ "ok": false,
285
+ "schema": "railshot.result/1",
286
+ "seq": 2,
287
+ "stream_id": "active"
288
+ },
289
+ {
290
+ "decision": {
291
+ "atoms": [
292
+ 1.0,
293
+ 0.0,
294
+ 0.0,
295
+ 0.0,
296
+ 1.0,
297
+ 0.0,
298
+ 0.0
299
+ ],
300
+ "bank": "dealership",
301
+ "bits": [
302
+ 1.0,
303
+ 0.0,
304
+ 1.0,
305
+ 0.0,
306
+ 0.0,
307
+ 1.0,
308
+ 0.0
309
+ ],
310
+ "lexemes": null,
311
+ "model": "magiceightball",
312
+ "needle_tokens": 10,
313
+ "request_documents": 1,
314
+ "requests": 1,
315
+ "result": {
316
+ "action": "review_service_intake",
317
+ "answers": {
318
+ "may_route": true
319
+ },
320
+ "category": "service"
321
+ }
322
+ },
323
+ "ok": true,
324
+ "schema": "railshot.result/1",
325
+ "seq": 4,
326
+ "stream_id": "active"
327
+ }
328
+ ]
329
+ }
330
+ },
331
+ {
332
+ "bank": "manufacturing",
333
+ "backend": "cpu",
334
+ "passes": 8,
335
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
336
+ "identity": {
337
+ "adapter": "magiceightball/1",
338
+ "artifact_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
339
+ "bank": "manufacturing",
340
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
341
+ },
342
+ "process_1": {
343
+ "requests": [
344
+ {
345
+ "stream_id": "active",
346
+ "seq": 1,
347
+ "append": "Vibration alert. Maintenance review ",
348
+ "reset": false
349
+ },
350
+ {
351
+ "stream_id": "active",
352
+ "seq": 3,
353
+ "append": "Skipped",
354
+ "reset": false
355
+ },
356
+ {
357
+ "stream_id": "active",
358
+ "seq": 2,
359
+ "append": "approved.",
360
+ "reset": false
361
+ },
362
+ {
363
+ "stream_id": "unrelated",
364
+ "seq": 1,
365
+ "append": "Routine note only.",
366
+ "reset": false
367
+ }
368
+ ],
369
+ "responses": [
370
+ {
371
+ "decision": {
372
+ "atoms": [
373
+ 1.0,
374
+ 0.0,
375
+ 0.0,
376
+ 0.0,
377
+ 0.0,
378
+ 0.0,
379
+ 0.0
380
+ ],
381
+ "bank": "manufacturing",
382
+ "bits": [
383
+ 0.0,
384
+ 0.0,
385
+ 1.0,
386
+ 0.0,
387
+ 0.0,
388
+ 0.0,
389
+ 0.0
390
+ ],
391
+ "lexemes": null,
392
+ "model": "magiceightball",
393
+ "needle_tokens": 9,
394
+ "request_documents": 1,
395
+ "requests": 1,
396
+ "result": {
397
+ "action": null,
398
+ "answers": {
399
+ "may_route": false
400
+ },
401
+ "category": "mechanical"
402
+ }
403
+ },
404
+ "ok": true,
405
+ "schema": "railshot.result/1",
406
+ "seq": 1,
407
+ "stream_id": "active"
408
+ },
409
+ {
410
+ "error": {
411
+ "code": "out_of_order",
412
+ "expected_seq": 2,
413
+ "message": "Expected the next contiguous seq"
414
+ },
415
+ "ok": false,
416
+ "schema": "railshot.result/1",
417
+ "seq": 3,
418
+ "stream_id": "active"
419
+ },
420
+ {
421
+ "decision": {
422
+ "atoms": [
423
+ 1.0,
424
+ 0.0,
425
+ 0.0,
426
+ 0.0,
427
+ 1.0,
428
+ 0.0,
429
+ 0.0
430
+ ],
431
+ "bank": "manufacturing",
432
+ "bits": [
433
+ 1.0,
434
+ 0.0,
435
+ 1.0,
436
+ 0.0,
437
+ 0.0,
438
+ 1.0,
439
+ 0.0
440
+ ],
441
+ "lexemes": null,
442
+ "model": "magiceightball",
443
+ "needle_tokens": 11,
444
+ "request_documents": 1,
445
+ "requests": 1,
446
+ "result": {
447
+ "action": "review_mechanical_alert",
448
+ "answers": {
449
+ "may_route": true
450
+ },
451
+ "category": "mechanical"
452
+ }
453
+ },
454
+ "ok": true,
455
+ "schema": "railshot.result/1",
456
+ "seq": 2,
457
+ "stream_id": "active"
458
+ },
459
+ {
460
+ "decision": {
461
+ "atoms": [
462
+ 0.0,
463
+ 0.0,
464
+ 0.0,
465
+ 0.0,
466
+ 0.0,
467
+ 0.0,
468
+ 0.0
469
+ ],
470
+ "bank": "manufacturing",
471
+ "bits": [
472
+ 0.0,
473
+ 0.0,
474
+ 0.0,
475
+ 0.0,
476
+ 0.0,
477
+ 0.0,
478
+ 0.0
479
+ ],
480
+ "lexemes": null,
481
+ "model": "magiceightball",
482
+ "needle_tokens": 6,
483
+ "request_documents": 1,
484
+ "requests": 1,
485
+ "result": {
486
+ "action": null,
487
+ "answers": {
488
+ "may_route": false
489
+ },
490
+ "category": null
491
+ }
492
+ },
493
+ "ok": true,
494
+ "schema": "railshot.result/1",
495
+ "seq": 1,
496
+ "stream_id": "unrelated"
497
+ }
498
+ ]
499
+ },
500
+ "process_2": {
501
+ "requests": [
502
+ {
503
+ "stream_id": "active",
504
+ "seq": 2,
505
+ "append": "approved.",
506
+ "reset": false
507
+ },
508
+ {
509
+ "stream_id": "active",
510
+ "seq": 3,
511
+ "append": " Maintenance hold.",
512
+ "reset": false
513
+ },
514
+ {
515
+ "stream_id": "active",
516
+ "seq": 2,
517
+ "append": "Conflicting approval",
518
+ "reset": false
519
+ },
520
+ {
521
+ "stream_id": "active",
522
+ "seq": 4,
523
+ "append": "Vibration alert. Maintenance review approved.",
524
+ "reset": true
525
+ }
526
+ ],
527
+ "responses": [
528
+ {
529
+ "decision": {
530
+ "atoms": [
531
+ 1.0,
532
+ 0.0,
533
+ 0.0,
534
+ 0.0,
535
+ 1.0,
536
+ 0.0,
537
+ 0.0
538
+ ],
539
+ "bank": "manufacturing",
540
+ "bits": [
541
+ 1.0,
542
+ 0.0,
543
+ 1.0,
544
+ 0.0,
545
+ 0.0,
546
+ 1.0,
547
+ 0.0
548
+ ],
549
+ "lexemes": null,
550
+ "model": "magiceightball",
551
+ "needle_tokens": 11,
552
+ "request_documents": 1,
553
+ "requests": 1,
554
+ "result": {
555
+ "action": "review_mechanical_alert",
556
+ "answers": {
557
+ "may_route": true
558
+ },
559
+ "category": "mechanical"
560
+ }
561
+ },
562
+ "ok": true,
563
+ "schema": "railshot.result/1",
564
+ "seq": 2,
565
+ "stream_id": "active"
566
+ },
567
+ {
568
+ "decision": {
569
+ "atoms": [
570
+ 1.0,
571
+ 0.0,
572
+ 0.0,
573
+ 0.0,
574
+ 1.0,
575
+ 1.0,
576
+ 0.0
577
+ ],
578
+ "bank": "manufacturing",
579
+ "bits": [
580
+ 0.0,
581
+ 0.0,
582
+ 1.0,
583
+ 0.0,
584
+ 0.0,
585
+ 0.0,
586
+ 0.0
587
+ ],
588
+ "lexemes": null,
589
+ "model": "magiceightball",
590
+ "needle_tokens": 16,
591
+ "request_documents": 1,
592
+ "requests": 1,
593
+ "result": {
594
+ "action": null,
595
+ "answers": {
596
+ "may_route": false
597
+ },
598
+ "category": "mechanical"
599
+ }
600
+ },
601
+ "ok": true,
602
+ "schema": "railshot.result/1",
603
+ "seq": 3,
604
+ "stream_id": "active"
605
+ },
606
+ {
607
+ "error": {
608
+ "code": "conflicting_retry",
609
+ "message": "This seq already has a different request"
610
+ },
611
+ "ok": false,
612
+ "schema": "railshot.result/1",
613
+ "seq": 2,
614
+ "stream_id": "active"
615
+ },
616
+ {
617
+ "decision": {
618
+ "atoms": [
619
+ 1.0,
620
+ 0.0,
621
+ 0.0,
622
+ 0.0,
623
+ 1.0,
624
+ 0.0,
625
+ 0.0
626
+ ],
627
+ "bank": "manufacturing",
628
+ "bits": [
629
+ 1.0,
630
+ 0.0,
631
+ 1.0,
632
+ 0.0,
633
+ 0.0,
634
+ 1.0,
635
+ 0.0
636
+ ],
637
+ "lexemes": null,
638
+ "model": "magiceightball",
639
+ "needle_tokens": 11,
640
+ "request_documents": 1,
641
+ "requests": 1,
642
+ "result": {
643
+ "action": "review_mechanical_alert",
644
+ "answers": {
645
+ "may_route": true
646
+ },
647
+ "category": "mechanical"
648
+ }
649
+ },
650
+ "ok": true,
651
+ "schema": "railshot.result/1",
652
+ "seq": 4,
653
+ "stream_id": "active"
654
+ }
655
+ ]
656
+ }
657
+ },
658
+ {
659
+ "bank": "store_security",
660
+ "backend": "cpu",
661
+ "passes": 8,
662
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
663
+ "identity": {
664
+ "adapter": "magiceightball/1",
665
+ "artifact_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
666
+ "bank": "store_security",
667
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
668
+ },
669
+ "process_1": {
670
+ "requests": [
671
+ {
672
+ "stream_id": "active",
673
+ "seq": 1,
674
+ "append": "Camera offline. Security review ",
675
+ "reset": false
676
+ },
677
+ {
678
+ "stream_id": "active",
679
+ "seq": 3,
680
+ "append": "Skipped",
681
+ "reset": false
682
+ },
683
+ {
684
+ "stream_id": "active",
685
+ "seq": 2,
686
+ "append": "approved.",
687
+ "reset": false
688
+ },
689
+ {
690
+ "stream_id": "unrelated",
691
+ "seq": 1,
692
+ "append": "Routine note only.",
693
+ "reset": false
694
+ }
695
+ ],
696
+ "responses": [
697
+ {
698
+ "decision": {
699
+ "atoms": [
700
+ 0.0,
701
+ 0.0,
702
+ 1.0,
703
+ 0.0,
704
+ 0.0,
705
+ 0.0,
706
+ 0.0
707
+ ],
708
+ "bank": "store_security",
709
+ "bits": [
710
+ 0.0,
711
+ 0.0,
712
+ 0.0,
713
+ 1.0,
714
+ 0.0,
715
+ 0.0,
716
+ 0.0
717
+ ],
718
+ "lexemes": null,
719
+ "model": "magiceightball",
720
+ "needle_tokens": 10,
721
+ "request_documents": 1,
722
+ "requests": 1,
723
+ "result": {
724
+ "action": null,
725
+ "answers": {
726
+ "may_route": false
727
+ },
728
+ "category": "camera_alert"
729
+ }
730
+ },
731
+ "ok": true,
732
+ "schema": "railshot.result/1",
733
+ "seq": 1,
734
+ "stream_id": "active"
735
+ },
736
+ {
737
+ "error": {
738
+ "code": "out_of_order",
739
+ "expected_seq": 2,
740
+ "message": "Expected the next contiguous seq"
741
+ },
742
+ "ok": false,
743
+ "schema": "railshot.result/1",
744
+ "seq": 3,
745
+ "stream_id": "active"
746
+ },
747
+ {
748
+ "decision": {
749
+ "atoms": [
750
+ 0.0,
751
+ 0.0,
752
+ 1.0,
753
+ 0.0,
754
+ 1.0,
755
+ 0.0,
756
+ 0.0
757
+ ],
758
+ "bank": "store_security",
759
+ "bits": [
760
+ 1.0,
761
+ 0.0,
762
+ 0.0,
763
+ 1.0,
764
+ 0.0,
765
+ 0.0,
766
+ 1.0
767
+ ],
768
+ "lexemes": null,
769
+ "model": "magiceightball",
770
+ "needle_tokens": 12,
771
+ "request_documents": 1,
772
+ "requests": 1,
773
+ "result": {
774
+ "action": "review_camera_alert",
775
+ "answers": {
776
+ "may_route": true
777
+ },
778
+ "category": "camera_alert"
779
+ }
780
+ },
781
+ "ok": true,
782
+ "schema": "railshot.result/1",
783
+ "seq": 2,
784
+ "stream_id": "active"
785
+ },
786
+ {
787
+ "decision": {
788
+ "atoms": [
789
+ 0.0,
790
+ 0.0,
791
+ 0.0,
792
+ 0.0,
793
+ 0.0,
794
+ 0.0,
795
+ 0.0
796
+ ],
797
+ "bank": "store_security",
798
+ "bits": [
799
+ 0.0,
800
+ 0.0,
801
+ 0.0,
802
+ 0.0,
803
+ 0.0,
804
+ 0.0,
805
+ 0.0
806
+ ],
807
+ "lexemes": null,
808
+ "model": "magiceightball",
809
+ "needle_tokens": 6,
810
+ "request_documents": 1,
811
+ "requests": 1,
812
+ "result": {
813
+ "action": null,
814
+ "answers": {
815
+ "may_route": false
816
+ },
817
+ "category": null
818
+ }
819
+ },
820
+ "ok": true,
821
+ "schema": "railshot.result/1",
822
+ "seq": 1,
823
+ "stream_id": "unrelated"
824
+ }
825
+ ]
826
+ },
827
+ "process_2": {
828
+ "requests": [
829
+ {
830
+ "stream_id": "active",
831
+ "seq": 2,
832
+ "append": "approved.",
833
+ "reset": false
834
+ },
835
+ {
836
+ "stream_id": "active",
837
+ "seq": 3,
838
+ "append": " Alert cleared.",
839
+ "reset": false
840
+ },
841
+ {
842
+ "stream_id": "active",
843
+ "seq": 2,
844
+ "append": "Conflicting approval",
845
+ "reset": false
846
+ },
847
+ {
848
+ "stream_id": "active",
849
+ "seq": 4,
850
+ "append": "Camera offline. Security review approved.",
851
+ "reset": true
852
+ }
853
+ ],
854
+ "responses": [
855
+ {
856
+ "decision": {
857
+ "atoms": [
858
+ 0.0,
859
+ 0.0,
860
+ 1.0,
861
+ 0.0,
862
+ 1.0,
863
+ 0.0,
864
+ 0.0
865
+ ],
866
+ "bank": "store_security",
867
+ "bits": [
868
+ 1.0,
869
+ 0.0,
870
+ 0.0,
871
+ 1.0,
872
+ 0.0,
873
+ 0.0,
874
+ 1.0
875
+ ],
876
+ "lexemes": null,
877
+ "model": "magiceightball",
878
+ "needle_tokens": 12,
879
+ "request_documents": 1,
880
+ "requests": 1,
881
+ "result": {
882
+ "action": "review_camera_alert",
883
+ "answers": {
884
+ "may_route": true
885
+ },
886
+ "category": "camera_alert"
887
+ }
888
+ },
889
+ "ok": true,
890
+ "schema": "railshot.result/1",
891
+ "seq": 2,
892
+ "stream_id": "active"
893
+ },
894
+ {
895
+ "decision": {
896
+ "atoms": [
897
+ 0.0,
898
+ 0.0,
899
+ 1.0,
900
+ 0.0,
901
+ 1.0,
902
+ 0.0,
903
+ 1.0
904
+ ],
905
+ "bank": "store_security",
906
+ "bits": [
907
+ 0.0,
908
+ 0.0,
909
+ 0.0,
910
+ 1.0,
911
+ 0.0,
912
+ 0.0,
913
+ 0.0
914
+ ],
915
+ "lexemes": null,
916
+ "model": "magiceightball",
917
+ "needle_tokens": 18,
918
+ "request_documents": 1,
919
+ "requests": 1,
920
+ "result": {
921
+ "action": null,
922
+ "answers": {
923
+ "may_route": false
924
+ },
925
+ "category": "camera_alert"
926
+ }
927
+ },
928
+ "ok": true,
929
+ "schema": "railshot.result/1",
930
+ "seq": 3,
931
+ "stream_id": "active"
932
+ },
933
+ {
934
+ "error": {
935
+ "code": "conflicting_retry",
936
+ "message": "This seq already has a different request"
937
+ },
938
+ "ok": false,
939
+ "schema": "railshot.result/1",
940
+ "seq": 2,
941
+ "stream_id": "active"
942
+ },
943
+ {
944
+ "decision": {
945
+ "atoms": [
946
+ 0.0,
947
+ 0.0,
948
+ 1.0,
949
+ 0.0,
950
+ 1.0,
951
+ 0.0,
952
+ 0.0
953
+ ],
954
+ "bank": "store_security",
955
+ "bits": [
956
+ 1.0,
957
+ 0.0,
958
+ 0.0,
959
+ 1.0,
960
+ 0.0,
961
+ 0.0,
962
+ 1.0
963
+ ],
964
+ "lexemes": null,
965
+ "model": "magiceightball",
966
+ "needle_tokens": 12,
967
+ "request_documents": 1,
968
+ "requests": 1,
969
+ "result": {
970
+ "action": "review_camera_alert",
971
+ "answers": {
972
+ "may_route": true
973
+ },
974
+ "category": "camera_alert"
975
+ }
976
+ },
977
+ "ok": true,
978
+ "schema": "railshot.result/1",
979
+ "seq": 4,
980
+ "stream_id": "active"
981
+ }
982
+ ]
983
+ }
984
+ },
985
+ {
986
+ "bank": "dealership",
987
+ "backend": "ncs1",
988
+ "passes": 8,
989
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
990
+ "identity": {
991
+ "adapter": "magiceightball/1",
992
+ "artifact_sha256": "812c8f393db056c68cbca7f42fe7ac72ec9570d18f4e15f8e6eac2460ca04e46",
993
+ "bank": "dealership",
994
+ "boot_usb_id": "03E7:2150",
995
+ "stick": "ncs1",
996
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
997
+ },
998
+ "process_1": {
999
+ "requests": [
1000
+ {
1001
+ "stream_id": "active",
1002
+ "seq": 1,
1003
+ "append": "Service requested. Intake ",
1004
+ "reset": false
1005
+ },
1006
+ {
1007
+ "stream_id": "active",
1008
+ "seq": 3,
1009
+ "append": "Skipped",
1010
+ "reset": false
1011
+ },
1012
+ {
1013
+ "stream_id": "active",
1014
+ "seq": 2,
1015
+ "append": "approved.",
1016
+ "reset": false
1017
+ },
1018
+ {
1019
+ "stream_id": "unrelated",
1020
+ "seq": 1,
1021
+ "append": "Routine note only.",
1022
+ "reset": false
1023
+ }
1024
+ ],
1025
+ "responses": [
1026
+ {
1027
+ "decision": {
1028
+ "atoms": [
1029
+ 1.0,
1030
+ 0.0,
1031
+ 0.0,
1032
+ 0.0,
1033
+ 0.0,
1034
+ 0.0,
1035
+ 0.0
1036
+ ],
1037
+ "bank": "dealership",
1038
+ "bits": [
1039
+ 0.0,
1040
+ 0.0,
1041
+ 1.0,
1042
+ 0.0,
1043
+ 0.0,
1044
+ 0.0,
1045
+ 0.0
1046
+ ],
1047
+ "lexemes": null,
1048
+ "model": "magiceightball",
1049
+ "needle_tokens": 8,
1050
+ "request_documents": 1,
1051
+ "requests": 1,
1052
+ "result": {
1053
+ "action": null,
1054
+ "answers": {
1055
+ "may_route": false
1056
+ },
1057
+ "category": "service"
1058
+ }
1059
+ },
1060
+ "ok": true,
1061
+ "schema": "railshot.result/1",
1062
+ "seq": 1,
1063
+ "stream_id": "active"
1064
+ },
1065
+ {
1066
+ "error": {
1067
+ "code": "out_of_order",
1068
+ "expected_seq": 2,
1069
+ "message": "Expected the next contiguous seq"
1070
+ },
1071
+ "ok": false,
1072
+ "schema": "railshot.result/1",
1073
+ "seq": 3,
1074
+ "stream_id": "active"
1075
+ },
1076
+ {
1077
+ "decision": {
1078
+ "atoms": [
1079
+ 1.0,
1080
+ 0.0,
1081
+ 0.0,
1082
+ 0.0,
1083
+ 1.0,
1084
+ 0.0,
1085
+ 0.0
1086
+ ],
1087
+ "bank": "dealership",
1088
+ "bits": [
1089
+ 1.0,
1090
+ 0.0,
1091
+ 1.0,
1092
+ 0.0,
1093
+ 0.0,
1094
+ 1.0,
1095
+ 0.0
1096
+ ],
1097
+ "lexemes": null,
1098
+ "model": "magiceightball",
1099
+ "needle_tokens": 10,
1100
+ "request_documents": 1,
1101
+ "requests": 1,
1102
+ "result": {
1103
+ "action": "review_service_intake",
1104
+ "answers": {
1105
+ "may_route": true
1106
+ },
1107
+ "category": "service"
1108
+ }
1109
+ },
1110
+ "ok": true,
1111
+ "schema": "railshot.result/1",
1112
+ "seq": 2,
1113
+ "stream_id": "active"
1114
+ },
1115
+ {
1116
+ "decision": {
1117
+ "atoms": [
1118
+ 0.0,
1119
+ 0.0,
1120
+ 0.0,
1121
+ 0.0,
1122
+ 0.0,
1123
+ 0.0,
1124
+ 0.0
1125
+ ],
1126
+ "bank": "dealership",
1127
+ "bits": [
1128
+ 0.0,
1129
+ 0.0,
1130
+ 0.0,
1131
+ 0.0,
1132
+ 0.0,
1133
+ 0.0,
1134
+ 0.0
1135
+ ],
1136
+ "lexemes": null,
1137
+ "model": "magiceightball",
1138
+ "needle_tokens": 6,
1139
+ "request_documents": 1,
1140
+ "requests": 1,
1141
+ "result": {
1142
+ "action": null,
1143
+ "answers": {
1144
+ "may_route": false
1145
+ },
1146
+ "category": null
1147
+ }
1148
+ },
1149
+ "ok": true,
1150
+ "schema": "railshot.result/1",
1151
+ "seq": 1,
1152
+ "stream_id": "unrelated"
1153
+ }
1154
+ ]
1155
+ },
1156
+ "process_2": {
1157
+ "requests": [
1158
+ {
1159
+ "stream_id": "active",
1160
+ "seq": 2,
1161
+ "append": "approved.",
1162
+ "reset": false
1163
+ },
1164
+ {
1165
+ "stream_id": "active",
1166
+ "seq": 3,
1167
+ "append": " Customer declined.",
1168
+ "reset": false
1169
+ },
1170
+ {
1171
+ "stream_id": "active",
1172
+ "seq": 2,
1173
+ "append": "Conflicting approval",
1174
+ "reset": false
1175
+ },
1176
+ {
1177
+ "stream_id": "active",
1178
+ "seq": 4,
1179
+ "append": "Service requested. Intake approved.",
1180
+ "reset": true
1181
+ }
1182
+ ],
1183
+ "responses": [
1184
+ {
1185
+ "decision": {
1186
+ "atoms": [
1187
+ 1.0,
1188
+ 0.0,
1189
+ 0.0,
1190
+ 0.0,
1191
+ 1.0,
1192
+ 0.0,
1193
+ 0.0
1194
+ ],
1195
+ "bank": "dealership",
1196
+ "bits": [
1197
+ 1.0,
1198
+ 0.0,
1199
+ 1.0,
1200
+ 0.0,
1201
+ 0.0,
1202
+ 1.0,
1203
+ 0.0
1204
+ ],
1205
+ "lexemes": null,
1206
+ "model": "magiceightball",
1207
+ "needle_tokens": 10,
1208
+ "request_documents": 1,
1209
+ "requests": 1,
1210
+ "result": {
1211
+ "action": "review_service_intake",
1212
+ "answers": {
1213
+ "may_route": true
1214
+ },
1215
+ "category": "service"
1216
+ }
1217
+ },
1218
+ "ok": true,
1219
+ "schema": "railshot.result/1",
1220
+ "seq": 2,
1221
+ "stream_id": "active"
1222
+ },
1223
+ {
1224
+ "decision": {
1225
+ "atoms": [
1226
+ 1.0,
1227
+ 0.0,
1228
+ 0.0,
1229
+ 0.0,
1230
+ 1.0,
1231
+ 0.0,
1232
+ 1.0
1233
+ ],
1234
+ "bank": "dealership",
1235
+ "bits": [
1236
+ 0.0,
1237
+ 0.0,
1238
+ 1.0,
1239
+ 0.0,
1240
+ 0.0,
1241
+ 0.0,
1242
+ 0.0
1243
+ ],
1244
+ "lexemes": null,
1245
+ "model": "magiceightball",
1246
+ "needle_tokens": 16,
1247
+ "request_documents": 1,
1248
+ "requests": 1,
1249
+ "result": {
1250
+ "action": null,
1251
+ "answers": {
1252
+ "may_route": false
1253
+ },
1254
+ "category": "service"
1255
+ }
1256
+ },
1257
+ "ok": true,
1258
+ "schema": "railshot.result/1",
1259
+ "seq": 3,
1260
+ "stream_id": "active"
1261
+ },
1262
+ {
1263
+ "error": {
1264
+ "code": "conflicting_retry",
1265
+ "message": "This seq already has a different request"
1266
+ },
1267
+ "ok": false,
1268
+ "schema": "railshot.result/1",
1269
+ "seq": 2,
1270
+ "stream_id": "active"
1271
+ },
1272
+ {
1273
+ "decision": {
1274
+ "atoms": [
1275
+ 1.0,
1276
+ 0.0,
1277
+ 0.0,
1278
+ 0.0,
1279
+ 1.0,
1280
+ 0.0,
1281
+ 0.0
1282
+ ],
1283
+ "bank": "dealership",
1284
+ "bits": [
1285
+ 1.0,
1286
+ 0.0,
1287
+ 1.0,
1288
+ 0.0,
1289
+ 0.0,
1290
+ 1.0,
1291
+ 0.0
1292
+ ],
1293
+ "lexemes": null,
1294
+ "model": "magiceightball",
1295
+ "needle_tokens": 10,
1296
+ "request_documents": 1,
1297
+ "requests": 1,
1298
+ "result": {
1299
+ "action": "review_service_intake",
1300
+ "answers": {
1301
+ "may_route": true
1302
+ },
1303
+ "category": "service"
1304
+ }
1305
+ },
1306
+ "ok": true,
1307
+ "schema": "railshot.result/1",
1308
+ "seq": 4,
1309
+ "stream_id": "active"
1310
+ }
1311
+ ]
1312
+ }
1313
+ },
1314
+ {
1315
+ "bank": "manufacturing",
1316
+ "backend": "ncs1",
1317
+ "passes": 8,
1318
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
1319
+ "identity": {
1320
+ "adapter": "magiceightball/1",
1321
+ "artifact_sha256": "812c8f393db056c68cbca7f42fe7ac72ec9570d18f4e15f8e6eac2460ca04e46",
1322
+ "bank": "manufacturing",
1323
+ "boot_usb_id": "03E7:2150",
1324
+ "stick": "ncs1",
1325
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
1326
+ },
1327
+ "process_1": {
1328
+ "requests": [
1329
+ {
1330
+ "stream_id": "active",
1331
+ "seq": 1,
1332
+ "append": "Vibration alert. Maintenance review ",
1333
+ "reset": false
1334
+ },
1335
+ {
1336
+ "stream_id": "active",
1337
+ "seq": 3,
1338
+ "append": "Skipped",
1339
+ "reset": false
1340
+ },
1341
+ {
1342
+ "stream_id": "active",
1343
+ "seq": 2,
1344
+ "append": "approved.",
1345
+ "reset": false
1346
+ },
1347
+ {
1348
+ "stream_id": "unrelated",
1349
+ "seq": 1,
1350
+ "append": "Routine note only.",
1351
+ "reset": false
1352
+ }
1353
+ ],
1354
+ "responses": [
1355
+ {
1356
+ "decision": {
1357
+ "atoms": [
1358
+ 1.0,
1359
+ 0.0,
1360
+ 0.0,
1361
+ 0.0,
1362
+ 0.0,
1363
+ 0.0,
1364
+ 0.0
1365
+ ],
1366
+ "bank": "manufacturing",
1367
+ "bits": [
1368
+ 0.0,
1369
+ 0.0,
1370
+ 1.0,
1371
+ 0.0,
1372
+ 0.0,
1373
+ 0.0,
1374
+ 0.0
1375
+ ],
1376
+ "lexemes": null,
1377
+ "model": "magiceightball",
1378
+ "needle_tokens": 9,
1379
+ "request_documents": 1,
1380
+ "requests": 1,
1381
+ "result": {
1382
+ "action": null,
1383
+ "answers": {
1384
+ "may_route": false
1385
+ },
1386
+ "category": "mechanical"
1387
+ }
1388
+ },
1389
+ "ok": true,
1390
+ "schema": "railshot.result/1",
1391
+ "seq": 1,
1392
+ "stream_id": "active"
1393
+ },
1394
+ {
1395
+ "error": {
1396
+ "code": "out_of_order",
1397
+ "expected_seq": 2,
1398
+ "message": "Expected the next contiguous seq"
1399
+ },
1400
+ "ok": false,
1401
+ "schema": "railshot.result/1",
1402
+ "seq": 3,
1403
+ "stream_id": "active"
1404
+ },
1405
+ {
1406
+ "decision": {
1407
+ "atoms": [
1408
+ 1.0,
1409
+ 0.0,
1410
+ 0.0,
1411
+ 0.0,
1412
+ 1.0,
1413
+ 0.0,
1414
+ 0.0
1415
+ ],
1416
+ "bank": "manufacturing",
1417
+ "bits": [
1418
+ 1.0,
1419
+ 0.0,
1420
+ 1.0,
1421
+ 0.0,
1422
+ 0.0,
1423
+ 1.0,
1424
+ 0.0
1425
+ ],
1426
+ "lexemes": null,
1427
+ "model": "magiceightball",
1428
+ "needle_tokens": 11,
1429
+ "request_documents": 1,
1430
+ "requests": 1,
1431
+ "result": {
1432
+ "action": "review_mechanical_alert",
1433
+ "answers": {
1434
+ "may_route": true
1435
+ },
1436
+ "category": "mechanical"
1437
+ }
1438
+ },
1439
+ "ok": true,
1440
+ "schema": "railshot.result/1",
1441
+ "seq": 2,
1442
+ "stream_id": "active"
1443
+ },
1444
+ {
1445
+ "decision": {
1446
+ "atoms": [
1447
+ 0.0,
1448
+ 0.0,
1449
+ 0.0,
1450
+ 0.0,
1451
+ 0.0,
1452
+ 0.0,
1453
+ 0.0
1454
+ ],
1455
+ "bank": "manufacturing",
1456
+ "bits": [
1457
+ 0.0,
1458
+ 0.0,
1459
+ 0.0,
1460
+ 0.0,
1461
+ 0.0,
1462
+ 0.0,
1463
+ 0.0
1464
+ ],
1465
+ "lexemes": null,
1466
+ "model": "magiceightball",
1467
+ "needle_tokens": 6,
1468
+ "request_documents": 1,
1469
+ "requests": 1,
1470
+ "result": {
1471
+ "action": null,
1472
+ "answers": {
1473
+ "may_route": false
1474
+ },
1475
+ "category": null
1476
+ }
1477
+ },
1478
+ "ok": true,
1479
+ "schema": "railshot.result/1",
1480
+ "seq": 1,
1481
+ "stream_id": "unrelated"
1482
+ }
1483
+ ]
1484
+ },
1485
+ "process_2": {
1486
+ "requests": [
1487
+ {
1488
+ "stream_id": "active",
1489
+ "seq": 2,
1490
+ "append": "approved.",
1491
+ "reset": false
1492
+ },
1493
+ {
1494
+ "stream_id": "active",
1495
+ "seq": 3,
1496
+ "append": " Maintenance hold.",
1497
+ "reset": false
1498
+ },
1499
+ {
1500
+ "stream_id": "active",
1501
+ "seq": 2,
1502
+ "append": "Conflicting approval",
1503
+ "reset": false
1504
+ },
1505
+ {
1506
+ "stream_id": "active",
1507
+ "seq": 4,
1508
+ "append": "Vibration alert. Maintenance review approved.",
1509
+ "reset": true
1510
+ }
1511
+ ],
1512
+ "responses": [
1513
+ {
1514
+ "decision": {
1515
+ "atoms": [
1516
+ 1.0,
1517
+ 0.0,
1518
+ 0.0,
1519
+ 0.0,
1520
+ 1.0,
1521
+ 0.0,
1522
+ 0.0
1523
+ ],
1524
+ "bank": "manufacturing",
1525
+ "bits": [
1526
+ 1.0,
1527
+ 0.0,
1528
+ 1.0,
1529
+ 0.0,
1530
+ 0.0,
1531
+ 1.0,
1532
+ 0.0
1533
+ ],
1534
+ "lexemes": null,
1535
+ "model": "magiceightball",
1536
+ "needle_tokens": 11,
1537
+ "request_documents": 1,
1538
+ "requests": 1,
1539
+ "result": {
1540
+ "action": "review_mechanical_alert",
1541
+ "answers": {
1542
+ "may_route": true
1543
+ },
1544
+ "category": "mechanical"
1545
+ }
1546
+ },
1547
+ "ok": true,
1548
+ "schema": "railshot.result/1",
1549
+ "seq": 2,
1550
+ "stream_id": "active"
1551
+ },
1552
+ {
1553
+ "decision": {
1554
+ "atoms": [
1555
+ 1.0,
1556
+ 0.0,
1557
+ 0.0,
1558
+ 0.0,
1559
+ 1.0,
1560
+ 1.0,
1561
+ 0.0
1562
+ ],
1563
+ "bank": "manufacturing",
1564
+ "bits": [
1565
+ 0.0,
1566
+ 0.0,
1567
+ 1.0,
1568
+ 0.0,
1569
+ 0.0,
1570
+ 0.0,
1571
+ 0.0
1572
+ ],
1573
+ "lexemes": null,
1574
+ "model": "magiceightball",
1575
+ "needle_tokens": 16,
1576
+ "request_documents": 1,
1577
+ "requests": 1,
1578
+ "result": {
1579
+ "action": null,
1580
+ "answers": {
1581
+ "may_route": false
1582
+ },
1583
+ "category": "mechanical"
1584
+ }
1585
+ },
1586
+ "ok": true,
1587
+ "schema": "railshot.result/1",
1588
+ "seq": 3,
1589
+ "stream_id": "active"
1590
+ },
1591
+ {
1592
+ "error": {
1593
+ "code": "conflicting_retry",
1594
+ "message": "This seq already has a different request"
1595
+ },
1596
+ "ok": false,
1597
+ "schema": "railshot.result/1",
1598
+ "seq": 2,
1599
+ "stream_id": "active"
1600
+ },
1601
+ {
1602
+ "decision": {
1603
+ "atoms": [
1604
+ 1.0,
1605
+ 0.0,
1606
+ 0.0,
1607
+ 0.0,
1608
+ 1.0,
1609
+ 0.0,
1610
+ 0.0
1611
+ ],
1612
+ "bank": "manufacturing",
1613
+ "bits": [
1614
+ 1.0,
1615
+ 0.0,
1616
+ 1.0,
1617
+ 0.0,
1618
+ 0.0,
1619
+ 1.0,
1620
+ 0.0
1621
+ ],
1622
+ "lexemes": null,
1623
+ "model": "magiceightball",
1624
+ "needle_tokens": 11,
1625
+ "request_documents": 1,
1626
+ "requests": 1,
1627
+ "result": {
1628
+ "action": "review_mechanical_alert",
1629
+ "answers": {
1630
+ "may_route": true
1631
+ },
1632
+ "category": "mechanical"
1633
+ }
1634
+ },
1635
+ "ok": true,
1636
+ "schema": "railshot.result/1",
1637
+ "seq": 4,
1638
+ "stream_id": "active"
1639
+ }
1640
+ ]
1641
+ }
1642
+ },
1643
+ {
1644
+ "bank": "store_security",
1645
+ "backend": "ncs1",
1646
+ "passes": 8,
1647
+ "source": "authored simulation of structured workflow records, with actual inference and SQLite commits",
1648
+ "identity": {
1649
+ "adapter": "magiceightball/1",
1650
+ "artifact_sha256": "812c8f393db056c68cbca7f42fe7ac72ec9570d18f4e15f8e6eac2460ca04e46",
1651
+ "bank": "store_security",
1652
+ "boot_usb_id": "03E7:2150",
1653
+ "stick": "ncs1",
1654
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
1655
+ },
1656
+ "process_1": {
1657
+ "requests": [
1658
+ {
1659
+ "stream_id": "active",
1660
+ "seq": 1,
1661
+ "append": "Camera offline. Security review ",
1662
+ "reset": false
1663
+ },
1664
+ {
1665
+ "stream_id": "active",
1666
+ "seq": 3,
1667
+ "append": "Skipped",
1668
+ "reset": false
1669
+ },
1670
+ {
1671
+ "stream_id": "active",
1672
+ "seq": 2,
1673
+ "append": "approved.",
1674
+ "reset": false
1675
+ },
1676
+ {
1677
+ "stream_id": "unrelated",
1678
+ "seq": 1,
1679
+ "append": "Routine note only.",
1680
+ "reset": false
1681
+ }
1682
+ ],
1683
+ "responses": [
1684
+ {
1685
+ "decision": {
1686
+ "atoms": [
1687
+ 0.0,
1688
+ 0.0,
1689
+ 1.0,
1690
+ 0.0,
1691
+ 0.0,
1692
+ 0.0,
1693
+ 0.0
1694
+ ],
1695
+ "bank": "store_security",
1696
+ "bits": [
1697
+ 0.0,
1698
+ 0.0,
1699
+ 0.0,
1700
+ 1.0,
1701
+ 0.0,
1702
+ 0.0,
1703
+ 0.0
1704
+ ],
1705
+ "lexemes": null,
1706
+ "model": "magiceightball",
1707
+ "needle_tokens": 10,
1708
+ "request_documents": 1,
1709
+ "requests": 1,
1710
+ "result": {
1711
+ "action": null,
1712
+ "answers": {
1713
+ "may_route": false
1714
+ },
1715
+ "category": "camera_alert"
1716
+ }
1717
+ },
1718
+ "ok": true,
1719
+ "schema": "railshot.result/1",
1720
+ "seq": 1,
1721
+ "stream_id": "active"
1722
+ },
1723
+ {
1724
+ "error": {
1725
+ "code": "out_of_order",
1726
+ "expected_seq": 2,
1727
+ "message": "Expected the next contiguous seq"
1728
+ },
1729
+ "ok": false,
1730
+ "schema": "railshot.result/1",
1731
+ "seq": 3,
1732
+ "stream_id": "active"
1733
+ },
1734
+ {
1735
+ "decision": {
1736
+ "atoms": [
1737
+ 0.0,
1738
+ 0.0,
1739
+ 1.0,
1740
+ 0.0,
1741
+ 1.0,
1742
+ 0.0,
1743
+ 0.0
1744
+ ],
1745
+ "bank": "store_security",
1746
+ "bits": [
1747
+ 1.0,
1748
+ 0.0,
1749
+ 0.0,
1750
+ 1.0,
1751
+ 0.0,
1752
+ 0.0,
1753
+ 1.0
1754
+ ],
1755
+ "lexemes": null,
1756
+ "model": "magiceightball",
1757
+ "needle_tokens": 12,
1758
+ "request_documents": 1,
1759
+ "requests": 1,
1760
+ "result": {
1761
+ "action": "review_camera_alert",
1762
+ "answers": {
1763
+ "may_route": true
1764
+ },
1765
+ "category": "camera_alert"
1766
+ }
1767
+ },
1768
+ "ok": true,
1769
+ "schema": "railshot.result/1",
1770
+ "seq": 2,
1771
+ "stream_id": "active"
1772
+ },
1773
+ {
1774
+ "decision": {
1775
+ "atoms": [
1776
+ 0.0,
1777
+ 0.0,
1778
+ 0.0,
1779
+ 0.0,
1780
+ 0.0,
1781
+ 0.0,
1782
+ 0.0
1783
+ ],
1784
+ "bank": "store_security",
1785
+ "bits": [
1786
+ 0.0,
1787
+ 0.0,
1788
+ 0.0,
1789
+ 0.0,
1790
+ 0.0,
1791
+ 0.0,
1792
+ 0.0
1793
+ ],
1794
+ "lexemes": null,
1795
+ "model": "magiceightball",
1796
+ "needle_tokens": 6,
1797
+ "request_documents": 1,
1798
+ "requests": 1,
1799
+ "result": {
1800
+ "action": null,
1801
+ "answers": {
1802
+ "may_route": false
1803
+ },
1804
+ "category": null
1805
+ }
1806
+ },
1807
+ "ok": true,
1808
+ "schema": "railshot.result/1",
1809
+ "seq": 1,
1810
+ "stream_id": "unrelated"
1811
+ }
1812
+ ]
1813
+ },
1814
+ "process_2": {
1815
+ "requests": [
1816
+ {
1817
+ "stream_id": "active",
1818
+ "seq": 2,
1819
+ "append": "approved.",
1820
+ "reset": false
1821
+ },
1822
+ {
1823
+ "stream_id": "active",
1824
+ "seq": 3,
1825
+ "append": " Alert cleared.",
1826
+ "reset": false
1827
+ },
1828
+ {
1829
+ "stream_id": "active",
1830
+ "seq": 2,
1831
+ "append": "Conflicting approval",
1832
+ "reset": false
1833
+ },
1834
+ {
1835
+ "stream_id": "active",
1836
+ "seq": 4,
1837
+ "append": "Camera offline. Security review approved.",
1838
+ "reset": true
1839
+ }
1840
+ ],
1841
+ "responses": [
1842
+ {
1843
+ "decision": {
1844
+ "atoms": [
1845
+ 0.0,
1846
+ 0.0,
1847
+ 1.0,
1848
+ 0.0,
1849
+ 1.0,
1850
+ 0.0,
1851
+ 0.0
1852
+ ],
1853
+ "bank": "store_security",
1854
+ "bits": [
1855
+ 1.0,
1856
+ 0.0,
1857
+ 0.0,
1858
+ 1.0,
1859
+ 0.0,
1860
+ 0.0,
1861
+ 1.0
1862
+ ],
1863
+ "lexemes": null,
1864
+ "model": "magiceightball",
1865
+ "needle_tokens": 12,
1866
+ "request_documents": 1,
1867
+ "requests": 1,
1868
+ "result": {
1869
+ "action": "review_camera_alert",
1870
+ "answers": {
1871
+ "may_route": true
1872
+ },
1873
+ "category": "camera_alert"
1874
+ }
1875
+ },
1876
+ "ok": true,
1877
+ "schema": "railshot.result/1",
1878
+ "seq": 2,
1879
+ "stream_id": "active"
1880
+ },
1881
+ {
1882
+ "decision": {
1883
+ "atoms": [
1884
+ 0.0,
1885
+ 0.0,
1886
+ 1.0,
1887
+ 0.0,
1888
+ 1.0,
1889
+ 0.0,
1890
+ 1.0
1891
+ ],
1892
+ "bank": "store_security",
1893
+ "bits": [
1894
+ 0.0,
1895
+ 0.0,
1896
+ 0.0,
1897
+ 1.0,
1898
+ 0.0,
1899
+ 0.0,
1900
+ 0.0
1901
+ ],
1902
+ "lexemes": null,
1903
+ "model": "magiceightball",
1904
+ "needle_tokens": 18,
1905
+ "request_documents": 1,
1906
+ "requests": 1,
1907
+ "result": {
1908
+ "action": null,
1909
+ "answers": {
1910
+ "may_route": false
1911
+ },
1912
+ "category": "camera_alert"
1913
+ }
1914
+ },
1915
+ "ok": true,
1916
+ "schema": "railshot.result/1",
1917
+ "seq": 3,
1918
+ "stream_id": "active"
1919
+ },
1920
+ {
1921
+ "error": {
1922
+ "code": "conflicting_retry",
1923
+ "message": "This seq already has a different request"
1924
+ },
1925
+ "ok": false,
1926
+ "schema": "railshot.result/1",
1927
+ "seq": 2,
1928
+ "stream_id": "active"
1929
+ },
1930
+ {
1931
+ "decision": {
1932
+ "atoms": [
1933
+ 0.0,
1934
+ 0.0,
1935
+ 1.0,
1936
+ 0.0,
1937
+ 1.0,
1938
+ 0.0,
1939
+ 0.0
1940
+ ],
1941
+ "bank": "store_security",
1942
+ "bits": [
1943
+ 1.0,
1944
+ 0.0,
1945
+ 0.0,
1946
+ 1.0,
1947
+ 0.0,
1948
+ 0.0,
1949
+ 1.0
1950
+ ],
1951
+ "lexemes": null,
1952
+ "model": "magiceightball",
1953
+ "needle_tokens": 12,
1954
+ "request_documents": 1,
1955
+ "requests": 1,
1956
+ "result": {
1957
+ "action": "review_camera_alert",
1958
+ "answers": {
1959
+ "may_route": true
1960
+ },
1961
+ "category": "camera_alert"
1962
+ }
1963
+ },
1964
+ "ok": true,
1965
+ "schema": "railshot.result/1",
1966
+ "seq": 4,
1967
+ "stream_id": "active"
1968
+ }
1969
+ ]
1970
+ }
1971
+ }
1972
+ ]
1973
+ }
measurements/physical-replay.json ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "railshot.physical-replay/1",
3
+ "identity": {
4
+ "adapter": "magiceightball/1",
5
+ "artifact_sha256": "1a8c1a021f62d89e236ebea379f9c69c9e4ffebe925c6bca49bb70df07d7cf61",
6
+ "boot_usb_id": "03E7:2150",
7
+ "manifest": {
8
+ "codebook": [
9
+ [
10
+ 0,
11
+ 0,
12
+ 0,
13
+ 0,
14
+ 0,
15
+ 0,
16
+ 0
17
+ ],
18
+ [
19
+ 0,
20
+ 0,
21
+ 0,
22
+ 1,
23
+ 0,
24
+ 0,
25
+ 0
26
+ ],
27
+ [
28
+ 0,
29
+ 0,
30
+ 1,
31
+ 0,
32
+ 0,
33
+ 0,
34
+ 0
35
+ ],
36
+ [
37
+ 0,
38
+ 1,
39
+ 1,
40
+ 1,
41
+ 0,
42
+ 0,
43
+ 0
44
+ ],
45
+ [
46
+ 1,
47
+ 0,
48
+ 0,
49
+ 1,
50
+ 0,
51
+ 0,
52
+ 1
53
+ ],
54
+ [
55
+ 1,
56
+ 0,
57
+ 1,
58
+ 0,
59
+ 0,
60
+ 1,
61
+ 0
62
+ ],
63
+ [
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 1,
69
+ 1,
70
+ 1
71
+ ]
72
+ ],
73
+ "decisions": "v0",
74
+ "fp16_coefficient_bytes": 32,
75
+ "input_shapes": {
76
+ "features": [
77
+ 128
78
+ ]
79
+ },
80
+ "learned_parameters": 0,
81
+ "onnx_sha256": "9d8bb1854edfbdc43d36084fb858e76b72d23fd46d63e1c86ae1845d8f582ce5",
82
+ "pair_fact_order": [
83
+ 4,
84
+ 5,
85
+ 6,
86
+ 0,
87
+ 1,
88
+ 2,
89
+ 3
90
+ ],
91
+ "policy": {
92
+ "actions": {
93
+ "review_billing": "@ready AND @billing",
94
+ "review_delivery": "@ready AND @delivery",
95
+ "triage_mixed": "@ready AND @billing AND @delivery"
96
+ },
97
+ "answers": {
98
+ "may_route": "@ready"
99
+ },
100
+ "categories": {
101
+ "billing": "@billing",
102
+ "delivery": "@delivery",
103
+ "mixed": "@billing AND @delivery"
104
+ },
105
+ "name": "magiceightball",
106
+ "rules": {
107
+ "billing": "\"charged twice\" OR \"duplicate charge\"",
108
+ "case_found": "@billing OR @delivery",
109
+ "delivery": "\"package missing\" OR \"parcel missing\"",
110
+ "hold": "\"do not route\" OR \"review cancelled\"",
111
+ "permission": "\"review authorized\"",
112
+ "ready": "@case_found AND @permission AND NOT @hold"
113
+ }
114
+ },
115
+ "radix_digits": 8,
116
+ "state_channels": 0,
117
+ "tile_side": 64,
118
+ "variant": "gather"
119
+ },
120
+ "stick": "ncs1",
121
+ "tokenizer_sha256": "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
122
+ },
123
+ "first_process": [
124
+ {
125
+ "decision": {
126
+ "atoms": [
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0,
132
+ 0.0,
133
+ 0.0
134
+ ],
135
+ "bits": [
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0
143
+ ],
144
+ "lexemes": null,
145
+ "model": "magiceightball",
146
+ "needle_tokens": 7,
147
+ "request_documents": 1,
148
+ "requests": 1,
149
+ "result": {
150
+ "action": null,
151
+ "answers": {
152
+ "may_route": false
153
+ },
154
+ "category": null
155
+ }
156
+ },
157
+ "ok": true,
158
+ "schema": "railshot.result/1",
159
+ "seq": 1,
160
+ "stream_id": "billing"
161
+ },
162
+ {
163
+ "decision": {
164
+ "atoms": [
165
+ 0.0,
166
+ 1.0,
167
+ 0.0,
168
+ 0.0,
169
+ 1.0,
170
+ 0.0,
171
+ 0.0
172
+ ],
173
+ "bits": [
174
+ 1.0,
175
+ 0.0,
176
+ 1.0,
177
+ 0.0,
178
+ 0.0,
179
+ 1.0,
180
+ 0.0
181
+ ],
182
+ "lexemes": null,
183
+ "model": "magiceightball",
184
+ "needle_tokens": 12,
185
+ "request_documents": 1,
186
+ "requests": 1,
187
+ "result": {
188
+ "action": "review_billing",
189
+ "answers": {
190
+ "may_route": true
191
+ },
192
+ "category": "billing"
193
+ }
194
+ },
195
+ "ok": true,
196
+ "schema": "railshot.result/1",
197
+ "seq": 2,
198
+ "stream_id": "billing"
199
+ },
200
+ {
201
+ "decision": {
202
+ "atoms": [
203
+ 0.0,
204
+ 0.0,
205
+ 1.0,
206
+ 0.0,
207
+ 1.0,
208
+ 0.0,
209
+ 0.0
210
+ ],
211
+ "bits": [
212
+ 1.0,
213
+ 0.0,
214
+ 0.0,
215
+ 1.0,
216
+ 0.0,
217
+ 0.0,
218
+ 1.0
219
+ ],
220
+ "lexemes": null,
221
+ "model": "magiceightball",
222
+ "needle_tokens": 10,
223
+ "request_documents": 1,
224
+ "requests": 1,
225
+ "result": {
226
+ "action": "review_delivery",
227
+ "answers": {
228
+ "may_route": true
229
+ },
230
+ "category": "delivery"
231
+ }
232
+ },
233
+ "ok": true,
234
+ "schema": "railshot.result/1",
235
+ "seq": 1,
236
+ "stream_id": "delivery"
237
+ },
238
+ {
239
+ "decision": {
240
+ "atoms": [
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0
248
+ ],
249
+ "bits": [
250
+ 0.0,
251
+ 0.0,
252
+ 0.0,
253
+ 0.0,
254
+ 0.0,
255
+ 0.0,
256
+ 0.0
257
+ ],
258
+ "lexemes": null,
259
+ "model": "magiceightball",
260
+ "needle_tokens": 131072,
261
+ "request_documents": 1,
262
+ "requests": 1,
263
+ "result": {
264
+ "action": null,
265
+ "answers": {
266
+ "may_route": false
267
+ },
268
+ "category": null
269
+ }
270
+ },
271
+ "ok": true,
272
+ "schema": "railshot.result/1",
273
+ "seq": 1,
274
+ "stream_id": "max"
275
+ }
276
+ ],
277
+ "second_process": [
278
+ {
279
+ "decision": {
280
+ "atoms": [
281
+ 0.0,
282
+ 1.0,
283
+ 0.0,
284
+ 0.0,
285
+ 1.0,
286
+ 0.0,
287
+ 0.0
288
+ ],
289
+ "bits": [
290
+ 1.0,
291
+ 0.0,
292
+ 1.0,
293
+ 0.0,
294
+ 0.0,
295
+ 1.0,
296
+ 0.0
297
+ ],
298
+ "lexemes": null,
299
+ "model": "magiceightball",
300
+ "needle_tokens": 12,
301
+ "request_documents": 1,
302
+ "requests": 1,
303
+ "result": {
304
+ "action": "review_billing",
305
+ "answers": {
306
+ "may_route": true
307
+ },
308
+ "category": "billing"
309
+ }
310
+ },
311
+ "ok": true,
312
+ "schema": "railshot.result/1",
313
+ "seq": 2,
314
+ "stream_id": "billing"
315
+ },
316
+ {
317
+ "error": {
318
+ "code": "out_of_order",
319
+ "expected_seq": 3,
320
+ "message": "Expected the next contiguous seq"
321
+ },
322
+ "ok": false,
323
+ "schema": "railshot.result/1",
324
+ "seq": 4,
325
+ "stream_id": "billing"
326
+ },
327
+ {
328
+ "decision": {
329
+ "atoms": [
330
+ 0.0,
331
+ 1.0,
332
+ 0.0,
333
+ 0.0,
334
+ 1.0,
335
+ 1.0,
336
+ 0.0
337
+ ],
338
+ "bits": [
339
+ 0.0,
340
+ 0.0,
341
+ 1.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0
346
+ ],
347
+ "lexemes": null,
348
+ "model": "magiceightball",
349
+ "needle_tokens": 16,
350
+ "request_documents": 1,
351
+ "requests": 1,
352
+ "result": {
353
+ "action": null,
354
+ "answers": {
355
+ "may_route": false
356
+ },
357
+ "category": "billing"
358
+ }
359
+ },
360
+ "ok": true,
361
+ "schema": "railshot.result/1",
362
+ "seq": 3,
363
+ "stream_id": "billing"
364
+ },
365
+ {
366
+ "error": {
367
+ "code": "invalid_append",
368
+ "expected_seq": 2,
369
+ "message": "Input has 131073 Needle tokens; maximum is 131072"
370
+ },
371
+ "ok": false,
372
+ "schema": "railshot.result/1",
373
+ "seq": 2,
374
+ "stream_id": "max"
375
+ },
376
+ {
377
+ "decision": {
378
+ "atoms": [
379
+ 0.0,
380
+ 0.0,
381
+ 0.0,
382
+ 0.0,
383
+ 0.0,
384
+ 0.0,
385
+ 0.0
386
+ ],
387
+ "bits": [
388
+ 0.0,
389
+ 0.0,
390
+ 0.0,
391
+ 0.0,
392
+ 0.0,
393
+ 0.0,
394
+ 0.0
395
+ ],
396
+ "lexemes": null,
397
+ "model": "magiceightball",
398
+ "needle_tokens": 0,
399
+ "request_documents": 1,
400
+ "requests": 1,
401
+ "result": {
402
+ "action": null,
403
+ "answers": {
404
+ "may_route": false
405
+ },
406
+ "category": null
407
+ }
408
+ },
409
+ "ok": true,
410
+ "schema": "railshot.result/1",
411
+ "seq": 2,
412
+ "stream_id": "max"
413
+ },
414
+ {
415
+ "error": {
416
+ "code": "conflicting_retry",
417
+ "message": "This seq already has a different request"
418
+ },
419
+ "ok": false,
420
+ "schema": "railshot.result/1",
421
+ "seq": 2,
422
+ "stream_id": "billing"
423
+ }
424
+ ],
425
+ "accepted_per_stream": {
426
+ "billing": 3,
427
+ "delivery": 1,
428
+ "max": 2
429
+ },
430
+ "process_wall_ms_including_setup_and_replay": [
431
+ 3584.57,
432
+ 3493.9
433
+ ]
434
+ }