Spaces:
Running

WideChaos commited on
Commit
a2bd61d
·
verified ·
1 Parent(s): 029601a

Publish Tiny Hash Intent with model and experiment records

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ training-curves.png filter=lfs diff=lfs merge=lfs -text
CONFIG.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "0.1.0",
3
+ "feature_bins": 4096,
4
+ "ngram_lengths": [3, 4, 5],
5
+ "hidden_size": 64,
6
+ "classes": 77,
7
+ "init_seed": 123,
8
+ "shuffle_seed_base": 2026,
9
+ "init_std": 0.05,
10
+ "epochs": 30,
11
+ "batch_size": 128,
12
+ "learning_rate": 0.003,
13
+ "beta1": 0.9,
14
+ "beta2": 0.999,
15
+ "epsilon": 1e-8,
16
+ "l2": 0.0001,
17
+ "temperature_grid": [0.5, 0.75, 1, 1.25, 1.5, 2, 3],
18
+ "input_utf16_limit": 2048,
19
+ "arithmetic": "float64",
20
+ "split": "sha256(feature-normalized-text) integer modulo10 ==0 validation; else train",
21
+ "model_identity": "work:tiny-hash-intent:v1"
22
+ }
EVALUATION-FREEZE.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "phase": "before evaluate.py first loads/scored official test for this model",
3
+ "sha256": {
4
+ "evaluate.py": "ceca9bfe01afc4d6fa4c61d9bcf56a2fcf8b2887bf649f5292f4ed54c380b2fe",
5
+ "run-001/PRETEST.json": "cce143034b86135c978e28c0e54160324635b38f2ef5be5bcacc6fe34cffd435"
6
+ }
7
+ }
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.
LICENSES.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # License scope
2
+
3
+ Original Python/JavaScript/HTML/CSS implementation and authored documentation: Apache License2.0, Copyright2026 Renchao Wu; full text in LICENSE.
4
+
5
+ Original BANKING77 train/test/category artifacts: PolyAI / Casanueva et al.2020, CC BY4.0. Original full license in data/LICENSE-CC-BY-4.0 and exact origin/commit/byte hashes in data/SOURCE.json. Those source files are unmodified.
6
+
7
+ Saved learned weights and derived fit/validation/calibration/quantization/prediction/figure artifacts under run-001/, evaluation-001/ and training-curves.png are distributed with CC BY4.0 attribution to BANKING77 and identification of the changes in README.md. This license choice does not claim original dataset ownership or source-author endorsement.
8
+
9
+ No pretrained model, third-party runtime library code, employer or private material is bundled. NumPy and optional Matplotlib are external dependencies installed separately. References are citations, not vendored paper text or implementations.
MANIFEST.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "work_identity": "work:tiny-hash-intent:v1",
4
+ "sha256": {
5
+ "CONFIG.json": "f456a31e948ae14ae393f9c9d55f8f11d7bf286e7cc05d16ce067fbfecb19813",
6
+ "EVALUATION-FREEZE.json": "099d0a6de7c5934cde57f46387b27dac68039b0402b6e4ffc80e3d902d1b16ad",
7
+ "LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
8
+ "LICENSES.md": "23da219031e4d1b3a7168e714041fd82dc6c50b4d7ab0bbc7c6e32d0ad795862",
9
+ "NOTICE": "6a4085ddb1afd130ea9e0e34a6906e1f8fd6297b7667bb2f2ba9a85de7a83236",
10
+ "PROTOCOL-FREEZE.json": "763f25b39349a0c9182da7d2397d1fb1b2f4d895a9c99c53d77b0afd58d54df1",
11
+ "PROTOCOL.md": "c13007155e43c71acc6b7858674f2a437ddd69782390b3a2023ceef087957cda",
12
+ "README.md": "cd82ef95aa18dfe60d4d9b135b3d696e782cf97744fe3d47d9d073c49370f8a7",
13
+ "SOURCE.json": "9cb616c9672752ff3ee54538acad4402f0885bfff69efdd3be934e09c4995a9a",
14
+ "app.mjs": "696b1f30a72ec33586ad30209c80515272ac243311e9e3f472823ccca4a3df12",
15
+ "data/LICENSE-CC-BY-4.0": "7e7170e3cebf88a9f60c7b8421418323c09304da1af4d5e90f4da1dc1c8a2661",
16
+ "data/SOURCE.json": "ba102337aed5ebb33c1a3d739b7e63ad015d681795d296fdc4e63eb5b60a8080",
17
+ "data/categories.json": "53261da888122daf2d120d925458631d9619e15d82e56052e7a42e535ce32b63",
18
+ "data/test.csv": "d12d6e3bc4c3103966ae786dc435913c0c563dfa328f5a3646d0e62cfeeb474d",
19
+ "data/train.csv": "b06e26ac675513959a63135f11b94ea7786ed02da65db93a5650d8838cbc664b",
20
+ "evaluate.py": "ceca9bfe01afc4d6fa4c61d9bcf56a2fcf8b2887bf649f5292f4ed54c380b2fe",
21
+ "evaluation-001/data-audit.json": "d04ef2adfc8391897a93df78e4695d05fcb4e3acd05df798c9f43981b2a1fd97",
22
+ "evaluation-001/float64-raw.csv": "c42f3b61645bdca0bd470f2b6af1a4af49a7ae3e67a5e08e87af99c229a20416",
23
+ "evaluation-001/float64-validation_temperature.csv": "f5c5000d6f9a1f7e3b4d90c07c650c3267403e152196d8abe78dd5e7c6760f63",
24
+ "evaluation-001/int8-raw.csv": "f86699896d75e2a33a7acad337c1cecb696ffe7af6f9b8eed6e184b78178dd88",
25
+ "evaluation-001/int8-validation_temperature.csv": "4907c756b722d23462cf77ae872cdeb936aa2302bb60e7e9bd0c42325fd00a1c",
26
+ "evaluation-001/results.json": "8a6fb12566d67754feb6ff794e34a68c727ee1020d8dcb8cda20518ab71582f2",
27
+ "evaluation-001/test-logits.npz": "cc5832dd29a6bc3254898a7ee572a21d4b371d49374fafcc639586d1441946db",
28
+ "index.html": "889fefdacb6e3d7501d163e1666f4d19b4353fbd06ba31807f19176e989f0552",
29
+ "infer.py": "d6d6321691a5dde732a531c885652350b2f8bc10cfac4d3889a8a096483d136c",
30
+ "inference.mjs": "befc1da4db88892e4fda0591f092e9756d1943afc92cfb2d178868e669f1face",
31
+ "model.py": "a6b4e59b61e5e9276bd2c29b23580966e813af19d482d7f193ff1f3b58e63e77",
32
+ "plot_training.py": "7b68da3c2d7533de3288d4c58972494b53a4d1e23a2c8f314c6355eeac56a819",
33
+ "portable-reference-results.json": "401083204e13e1b8acd759f06e34e5f9b54df0a9d799f70a6278819f915f8dd8",
34
+ "predict_driver.mjs": "f9bdf67657bac8e0069e925aa349262f87b5cc80610b74f557a2b102863405dc",
35
+ "requirements-plot.txt": "de950d3b75e4ad1a760c121533e06390c84574f7dd0b53c0eaa742ab6d5c2f38",
36
+ "requirements.txt": "738071c1d9633f276433ad6738de256d2bf0d22f66dc4bd3179012bebb63bdd1",
37
+ "run-001/PREFIT.json": "bad33e33120df6d7ad03452547dc7aa30b1e1e7fcf6ad1f3de0a599d2e498d68",
38
+ "run-001/PRETEST.json": "cce143034b86135c978e28c0e54160324635b38f2ef5be5bcacc6fe34cffd435",
39
+ "run-001/calibration.json": "09de1745929953e2138777af3270e7b618f99a9c388a60964186f26d7af28c90",
40
+ "run-001/initial-statistics.json": "b688717eba3f9b5f90e7e470b5fc29dde8c17b68c1b5ee25a619461c7f363e66",
41
+ "run-001/model-float64.npz": "fcfb60826d8d251b9b2e9f42765e3157e06e7292f0107151e99a4fcf3737d8d1",
42
+ "run-001/model-int8.json": "b9b8081ed0026d315574b7e2f1ff1b6de472a9d4724b23e6e1980618724388c4",
43
+ "run-001/trace.json": "65046cc2f7f1ed82339d65e707ccfc6ca5299967718e8312bc037afae6e5175f",
44
+ "run-001/validation-logits.npz": "e203e9aedfdbf5083891a40f689411d85a57dd2bf1ec0fff585a6b5b6e0ed666",
45
+ "style.css": "5ea86818f9f6583f8a818d3631e99cf85b5bb5e0c1519550fd128c44fde9e22b",
46
+ "test_inference.mjs": "b6a5ab3f122357c5c24fa0921ae3205e69b04326ea608f864270784013f1089c",
47
+ "test_model.py": "74a87872a3b190243cb95949969e8296bbfb59f0be84ad5f5cbd3bbbcb6dac4f",
48
+ "train.py": "e390575bf31202abda205668c95c3cdc609c0317609e522137b318008956832f",
49
+ "training-curves.png": "f894f54c008148927bc3e86e90fdaafb6033267680fe4b98c7d8c342a0e6ae23",
50
+ "verify_portable.py": "3b5ea58745573def208d6efc3447e89c931379af7ff38394f2070a936bb2b442",
51
+ "verify_results.py": "0eabbf616a5b44c74afe0182db7ae49f5c895555df5543556b8897b7bb24e949"
52
+ }
53
+ }
NOTICE ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tiny Hash Intent
2
+ Original implementation: Copyright2026 Renchao Wu, Apache-2.0.
3
+ BANKING77 original data: PolyAI, CC-BY-4.0.
4
+ Casanueva, Temcinas, Gerz, Henderson and Vulic (2020).
5
+ Efficient Intent Detection with Dual Sentence Encoders.
6
+ https://arxiv.org/abs/2003.04807
7
+ https://github.com/PolyAI-LDN/task-specific-datasets
8
+
9
+ Changes: from-scratch CPU character-hash neural fitting, validation selection,
10
+ temperature grid, post-training weight quantization, metrics and browser demo.
11
+ Saved model and experimental artifacts retain CC-BY-4.0 attribution.
12
+ See LICENSES.md and data/SOURCE.json for scope and exact provenance.
PROTOCOL-FREEZE.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "phase": "before model implementation or fitting; source known from earlier benchmark study",
3
+ "sha256": {
4
+ "PROTOCOL.md": "c13007155e43c71acc6b7858674f2a437ddd69782390b3a2023ceef087957cda",
5
+ "CONFIG.json": "f456a31e948ae14ae393f9c9d55f8f11d7bf286e7cc05d16ce067fbfecb19813",
6
+ "data/SOURCE.json": "ba102337aed5ebb33c1a3d739b7e63ad015d681795d296fdc4e63eb5b60a8080"
7
+ }
8
+ }
PROTOCOL.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tiny Hash Intent · fixed model protocol0.1
2
+
3
+ 2026-11-04, before implementing or fitting this model. Work identity `work:tiny-hash-intent:v1`. One from-scratch character-hash, one-hidden-layer classifier for the 77 closed-set English BANKING77 intents, with portable int8 browser inference. It is a real new fit, not a recount of the earlier Label Budget study. Source data is reused, not newly collected or independent. The earlier study has already viewed this benchmark's test results; this protocol fixes new-model choices before evaluating the new fit, not historical blindness to BANKING77.
4
+
5
+ ## Data and split freeze
6
+
7
+ Reuse exact unmodified PolyAI author CSV/category/license bytes already obtained through official CUA in `label-budget-lab-20261104/data`. Verify its SOURCE and each file hash, copy to this new directory, retain original commit links/CC BY4.0 license and Casanueva et al.2020 citation. Code Apache2; weights/data/derived experimental artifacts with CC BY4.0 attribution, not source ownership. Original category order, not HF alphabetic label ids.
8
+
9
+ The official train has10003 records and test3080. Only original train is used for fitting, validation selection and temperature choice. Trainer must not load the test CSV semantically; byte hashing for provenance is permitted. Preserve raw text/labels and every source row. Normalize for features and train/validation duplicate grouping as NFC, Unicode lowercase, then Python Unicode whitespace collapse. No stemming/translation/semantic duplicate detection. This limited text-equality grouping is not source-document/template-family metadata or an IID certificate.
10
+
11
+ For each original train row, group id=SHA256(UTF8 normalized text). Assign whole groups to validation when integer(full digest hex,16) modulo10 equals0, otherwise training. This fixed hash split is not tuned for class balance. Preserve all labels and ambiguous duplicate texts, report per-class supports and missing classes. Preflight requires at least one training example in each77class and nonempty validation; if it fails, record failure rather than silently resampling. Freeze exact membership/row ids/source hashes/config/implementation in PREFIT.json before any gradient update.
12
+
13
+ After PRETEST freeze, audit exact and normalized original train/test overlaps (both case-preserving NFC+whitespace for continuity with earlier study, and the feature-normalized lowercased form). Primary scores retain all3080officialrows. Also report a separate subset excluding feature-normalized matches to any original train row, including validation, with its actual denominator. Report actual fit/validation overlap counts separately. Never replace primary metrics or drop difficult examples.
14
+
15
+ ## Fixed features and architecture
16
+
17
+ Normalize as above, wrap with literal `^` and `$`, enumerate character/code-point ngrams of lengths3,4,5, UTF8 FNV-1a32 unsigned hash modulo4096. Collisions count together, feature ids sorted ascending. Feature values=tf/sqrt(sum(tf^2)); zero feature vector handled explicitly, no dropped input. No vocabulary fit/IDF/pretrained embeddings. Accept nonblank Unicode scalar input up to2048UTF16units; reject overlength, no silent truncation. Source rows must pass this cap or the preflight fails without silent filtering.
18
+
19
+ E shape4096x64, hidden bias64, output W64x77 and output bias77. `h=tanh(xE+bh)`, `z=hW+bo`, stable softmax. Total267213 learned scalar parameters. Counts/indices for hashing are fixed feature construction; E and W are actually learned through gradients. This is not an LLM or bilingual competence claim. Closed-set predictions always select one of77; no OOD detector or rejection threshold exists.
20
+
21
+ All training arithmetic float64. Initialize E and W with independent draws from NumPy default_rng(seed123), normal(0,.05), in that parameter order; biases0. One seed/config/run, no architecture or learning-rate search. CPU NumPy only, no GPU/backend model API. Threads capped1 where runtime exposes OPENBLAS/OMP/VECLIB thread environment variables; record actual runtime and walltimes without portable speed claims.
22
+
23
+ ## Optimizer and epoch selection
24
+
25
+ Minibatch128,30 complete epochs. At epoch e=1..30 shuffle training row ordinals with NumPy default_rng(2026+e). Last partial batch uses its actual size. Cross-entropy mean plus `.5*1e-4*(sum(E^2)+sum(W^2))`, no bias regularization. Add the L2 gradients before Adam (coupled L2, not AdamW).
26
+
27
+ Adam learning rate .003, beta1 .9, beta2 .999, epsilon1e-8, global step increments once per batch. `m=b1*m+(1-b1)*g`, `v=b2*v+(1-b2)*g^2`; bias-correct both by `1-beta^step`; subtract `lr*mhat/(sqrt(vhat)+epsilon)`. This explicit formula governs, not an assumed library variant. No clipping, dropout, warmup, adaptive schedule or restarts. Every parameter array and loss must remain finite; fail transparently on nonfinite values, do not silently change settings.
28
+
29
+ Each epoch record actual complete train-at-epoch-end cross-entropy and validation cross-entropy, fit steps and elapsed observations. Select lowest uncalibrated validation NLL; differences<=1e-12 tie to earliest epoch. Run all30 even if a later epoch worsens. Retain all trace points; save only the selected fit as the final model and document its selected epoch. No retraining on validation/test afterward.
30
+
31
+ Primary Adam reference inspected through its official arXiv abstract: Kingma and Ba, *Adam: A Method for Stochastic Optimization*, https://arxiv.org/abs/1412.6980 . The experimental HTML1412.6980v9 currently only references an embedded PDF and did not expose Algorithm1 text; do not claim that HTML supplied a full algorithm reproduction. This project defines/tests its own formula above, not the paper's benchmark experiments.
32
+
33
+ ## Validation-only temperature
34
+
35
+ With the selected float model, evaluate T in [.5,.75,1,1.25,1.5,2,3] on validation NLL `logsumexp(z/T)-z_gold/T`. Choose lowest NLL, within1e-12 tie to closestTto1 then smallerT. Save all candidate values/support. This is a finite grid, not an exact continuous optimum. No new training gradients for T. Same T inherited by quantized export; no test-guided temperature or abstention threshold selection.
36
+
37
+ Method reference: Guo, Pleiss, Sun and Weinberger2017, *On Calibration of Modern Neural Networks*, https://arxiv.org/abs/1706.04599 . Official abstract and available HTML inspected; no claim of reproducing its architectures or results. Temperature cannot establish OOD safety, correctness of individual probabilities or general calibration.
38
+
39
+ ## One post-training int8 representation
40
+
41
+ Quantize selected E per row and W per output column. Scale=max(abs(values))/127, or1 for all-zero slice. `q=clip(round-to-nearest-even(values/scale),-127,127).astype(int8)`. No -128, no QAT or new fit. Store int8 values as two's-complement bytes in base64, scales as finite float64 JSON numbers, biases unquantized float64. Keep exact dimensions/labels/preprocessor/T/version in portable JSON; validate lengths, all finite arrays, positive scales and supported schema. Never load pickle.
42
+
43
+ The browser performs code-point preprocessing/FNV/count-L2, dequantization and tanh/softmax locally using standard JS. Input editing clears stale results/exports, async initialization respects newer edits; initial fixed model asset GET only, no query network/storage/CDN/API. Show top3 labels with normalized known-class scores, explicit closed-set/English-only/OOD limitation. Export current input/config/model identity/predictions only after explicit action, warn that input is included. No financial advice, actual account operations or production routing decisions.
44
+
45
+ ## Model-specific test freeze and complete metrics
46
+
47
+ Before this model first scores official test, freeze selected float `.npz`, portable int8JSON, chosen epoch/T/validation log/implementation/config/source/membership hashes in PRETEST.json. Distinguish this from prefit and prior knowledge of the benchmark. One learned model, four representations/evaluation modes: float T1, float selectedT, int8 T1, int8 selectedT. These are not four independently trained models.
48
+
49
+ Evaluate every official test row in every mode: accuracy, macroF1 across77classes(0 for undefined class F1), NLL from stable logits, multiclass Brier=sum_c(p_c-onehot_c)^2, and descriptive top-confidence ECE10. Bins[0,.1),...,[.9,1], index=min(9,floor(confidence*10)); keep each bin's count/meanconfidence/accuracy, empty meansnull, ECE=sum(n_bin/N*abs(meanconfidence-accuracy)). ECE depends on these bins; no confidence interval/general guarantee. Argmax uses unscaled logits (T should not alter class), lowest id on actual float tie; float/int8 disagreement ids/count and all negative changes retained. Different floating algebra/platform may change near ties, no universal bit-identical prediction claim.
50
+
51
+ Save all row ids/gold/prediction/maxprob/p_gold/NLL/Brier for all4modes, full class support/confusions and actual nonoverlap subset scores. Save raw validation/test logits for float and int8 for independent metric reconstruction. Never count model reload/evaluation/calibration/quantization as another training run. Original train/test hashes/splits unchanged.
52
+
53
+ ## Acceptance and publication
54
+
55
+ Before fit: small finite-difference gradient check on an independent tiny D/H/C case over all parameters, hand forward/softmax/NLL cases, Adam scalar first-step/bias correction, feature/hash/Unicode/limits tests. After fit: actual reload identical saved model, independent parameter update/feature/forward/metric calculations and raw-row reconstruction, independent total-output actual re-fit if feasible, all negative/quantization/calibration outcomes kept.
56
+
57
+ Actual hidden official CUA browser inference and native report download required; compare floating outputs and class ids with the int8 Python representation over predefined ordinary/Unicode/empty/overlength/script-shaped examples. Bounded tolerance for scores and all discrepancies reported, not hidden by relabeling. Desktop/390layout, source network/log checks, no fake DOM-only model execution. Training traces/figures use saved actual data, no cherry-picked epoch deletion. Clean license/attribution, exact manifest, independent total review before later daily HF publish; today none. Public App/files/download/HTTPS/free conditions only proven on actual publication, local acceptance is not deployment/adoption.
README.md CHANGED
@@ -1,12 +1,151 @@
1
  ---
2
  title: Tiny Hash Intent
3
- emoji: 💻
4
- colorFrom: red
5
  colorTo: gray
6
  sdk: static
7
- pinned: false
8
  license: other
 
 
9
  short_description: A small from-scratch classifier with local browser inference
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Tiny Hash Intent
3
+ emoji: 🧠
4
+ colorFrom: blue
5
  colorTo: gray
6
  sdk: static
7
+ app_file: index.html
8
  license: other
9
+ license_name: apache-2.0-code-and-cc-by-4.0-artifacts
10
+ license_link: LICENSES.md
11
  short_description: A small from-scratch classifier with local browser inference
12
  ---
13
 
14
+ # Tiny Hash Intent
15
+
16
+ ## Why a small classifier?
17
+
18
+ Imagine two support messages: “The cash machine kept my card” and “The cash machine returned my card, but I did not receive the money.” Both mention a cash machine and a card. They describe different problems, and a support queue needs to keep them apart. These are illustrative requests, not a report of a customer deployment or measured predictions for these exact sentences.
19
+
20
+ An intent classifier assigns a short label to a message. It does not write an answer or fix the problem. I wanted a small, inspectable example that could learn those labels on a CPU and later run inside a browser. The public BANKING77 dataset provides 77 English request categories for that experiment.
21
+
22
+ I trained a network from random initialization, using short character patterns as its inputs. The model learns which patterns help distinguish the categories. Its 267,213 learned parameters are the adjustable numbers in that network; no pretrained language model is used. After the initial asset download, the demo computes predictions on the device. Try a message, then inspect or download all 77 class scores.
23
+
24
+ ## What the experiment taught me
25
+
26
+ I completed all 30 training epochs and chose epoch 28 using validation loss: a measure of how well the model predicts examples kept out of fitting. I then fixed the model and its score adjustment before this model's first test evaluation. The official 3,080-row test produced 2,779 correct labels and 301 errors. The full errors are part of the release, not discarded examples. I had used this benchmark before, so this is not a historically blind test.
27
+
28
+ Making the stored weights smaller did not change the number of correct labels, but it changed two individual predictions. Both were wrong before and after, with different wrong labels. A headline accuracy alone would hide that change. The browser uses the compact stored weights, then converts them to floating-point numbers for computation; this is not an integer-kernel speed result.
29
+
30
+ The most practical limit is visible if you enter an unrelated request. This model still chooses a banking label because it has no “none of the above” detector. A high class score does not establish that the message belongs here. The demo is a reproducible learning experiment, not a bank service, account operation or production routing system. The sections below keep the exact methods, full results and reproduction commands.
31
+
32
+ A 267,213-parameter character-hash neural classifier trained from scratch on BANKING77, with a portable weight-quantized browser demo. One CPU fit covers 77 English banking intents. The app runs locally after loading a fixed model asset and does not send input text to a model service.
33
+
34
+ This is a closed-set classifier. Every valid input receives one of the 77 labels, including unrelated requests. It has no OOD detector, abstention threshold, language-generation ability or banking decision authority. Other-language conformance tests verify implementation agreement, not multilingual task competence.
35
+
36
+ ## Result of this fit
37
+
38
+ All modes scored the same 3,080 official test rows. The validation-selected temperature is 0.75.
39
+
40
+ | Representation / temperature | Correct | Accuracy | Macro F1 | NLL | Brier | ECE10 |
41
+ | --- | --- | --- | --- | --- | --- | --- |
42
+ | Float64 / 1 | 2,779 | 90.2273% | 0.902346 | 0.385961 | 0.154635 | 0.060603 |
43
+ | Float64 / 0.75 | 2,779 | 90.2273% | 0.902346 | 0.355679 | 0.146271 | 0.011284 |
44
+ | Int8-stored weights / 1 | 2,779 | 90.2273% | 0.902383 | 0.385909 | 0.154600 | 0.060625 |
45
+ | Int8-stored weights / 0.75 | 2,779 | 90.2273% | 0.902383 | 0.355596 | 0.146231 | 0.011770 |
46
+
47
+ One model fit has four representation/post-processing evaluations, not four independent training runs. Quantization changed the predicted labels of test row ids 281 and 562; both were already wrong and remained wrong, with different wrong labels. The identical correct count does not imply identical predictions. All 301 errors, per-class outcomes, two disagreement ids and all 12,320 prediction/metric rows remain available in `evaluation-001/`.
48
+
49
+ Seven test texts match original training texts after the declared normalization. The complete official score retains them. The separately reported 3,073-row nonoverlap subset has 2,772 correct (90.2050%) in each mode. These literal/normalized checks do not rule out semantic or source-family overlap.
50
+
51
+ BANKING77 was already used in my earlier Label Budget study, so this is not a historically blind benchmark. This new model's configuration and selection rules were fixed before implementation/fitting, and its selected artifacts were frozen before this model's first test evaluation. The earlier study uses different label budgets; these are not controlled head-to-head scores against it. No significance, general calibration, OOD safety or SOTA claim is made.
52
+
53
+ ## Run the browser demo
54
+
55
+ ```sh
56
+ python3 -m http.server 8000 --bind 127.0.0.1
57
+ ```
58
+
59
+ Open the localhost address. Use a modern browser with ES modules, Unicode normalization, typed arrays, base64 decoding and Web Crypto. HTTPS or localhost is required for the model identity digest. There is no build step or client runtime dependency. Local preparation checks on 2026-11-04 do not include an HF cloud deployment.
60
+
61
+ The app shows three highest class scores and can switch between raw and validation-selected temperature. It always selects the class using unscaled logits; a positive temperature does not define a new classifier. Inputs over 2,048 UTF-16 units are rejected without truncation. Input edits and temperature changes clear previous results and download links.
62
+
63
+ The downloaded report includes the exact input text, model-file SHA-256, representation, temperature, logits and all 77 class scores. Review it before sharing. Initial loading fetches fixed local assets, including `run-001/model-int8.json`; subsequent inference does not fetch URLs, call APIs, write storage or send queries. Hosting still receives ordinary asset requests. The model does not operate any bank account or provide financial advice.
64
+
65
+ ## What is trained
66
+
67
+ Normalize text with NFC, Unicode lowercase and Python-style whitespace collapse; wrap it in literal `^` and `$`. Count code-point character ngrams of lengths 3, 4 and 5, hash UTF-8 ngrams with unsigned FNV-1a32 into 4,096 bins, and L2-normalize the count vector. Collisions share a feature; there is no vocabulary fit, pretrained tokenizer, IDF or pretrained embedding.
68
+
69
+ The sparse fixed feature vector feeds learned parameters:
70
+
71
+ ```text
72
+ E: 4096 × 64
73
+ bh: 64
74
+ W: 64 × 77
75
+ bo: 77
76
+ h = tanh(xE + bh)
77
+ z = hW + bo
78
+ p = stable_softmax(z / T)
79
+ ```
80
+
81
+ Training uses NumPy Float64 on CPU, seed 123, Gaussian std 0.05 for E then W, zero biases, 30 full epochs and batch size 128. Each epoch shuffles with seed 2026 + epoch. Cross-entropy is regularized by `0.5 * 1e-4 * (sum(E²) + sum(W²))`; biases are not regularized. Adam uses learning rate 0.003, betas 0.9/0.999, epsilon 1e-8 and explicit first/second-moment bias correction. L2 gradients are coupled into Adam; this is not AdamW. All steps and rows are retained.
82
+
83
+ The actual split has 8,998 fit rows and 1,005 validation rows. Whole normalized-text groups are assigned to validation when the integer SHA-256 group digest modulo ten equals zero. It is a fixed hash split, not inferred document-family metadata or an IID guarantee. All 77 classes have fitting support; full split row ids and per-class support are saved in `PREFIT.json`.
84
+
85
+ The fit performed 2,130 updates and 269,940 training-row visits. All 30 epochs completed; epoch 28 was selected by minimum uncalibrated validation NLL. The model was not refitted on validation or official test. The complete epoch trace and initial untrained parameter digest are retained. Wall times describe this host, not a portable speed benchmark.
86
+
87
+ ![All thirty epoch-end losses and the complete validation temperature grid](training-curves.png)
88
+
89
+ ## Calibration and quantization boundaries
90
+
91
+ After selecting the float model, the fixed grid `[0.5, 0.75, 1, 1.25, 1.5, 2, 3]` was evaluated on validation NLL. Temperature 0.75 won; ties would prefer closest to one, then smaller T. This is a finite grid, not an exact continuous optimum. The int8 representation inherits that temperature; neither the model nor T was tuned on its own test outputs.
92
+
93
+ The E matrix is symmetrically quantized per row and W per output column. Scales are max-absolute/127 (one for an all-zero slice); rounding is nearest-even, clipped to [-127,127]. Int8 values use base64 two's-complement bytes. Scales and biases remain floating point.
94
+
95
+ The browser dequantizes those stored weights and performs Float64 arithmetic. It does not use integer-only kernels, quantized activations, GPU acceleration or a faster-inference claim. The saved Float64 NPZ is 2,048,184 bytes; the portable int8 JSON is 473,507 bytes. These are different containers with metadata/compression differences, not a measurement of runtime memory or speed.
96
+
97
+ Calibration metrics describe these known classes on this one benchmark. NLL uses stable logits without probability clipping. Brier is the multiclass squared probability error. ECE10 uses ten equal-width top-confidence bins, with empty-bin means recorded as null. Its value depends on that binning and is not a correctness guarantee for an individual output or an unrelated request.
98
+
99
+ Method references: [Kingma and Ba, Adam](https://arxiv.org/abs/1412.6980), [Guo et al., On Calibration of Modern Neural Networks](https://arxiv.org/abs/1706.04599). The explicit formulas and finite grid in `PROTOCOL.md` define this implementation; this is not a reproduction of those papers' benchmark experiments.
100
+
101
+ ## Data and license
102
+
103
+ Original data belongs to PolyAI and the BANKING77 authors: Iñigo Casanueva, Tadas Temcinas, Daniela Gerz, Matthew Henderson and Ivan Vulić, 2020, [Efficient Intent Detection with Dual Sentence Encoders](https://arxiv.org/abs/2003.04807). Sources: [author repository](https://github.com/PolyAI-LDN/task-specific-datasets), [HF dataset card](https://huggingface.co/datasets/PolyAI/banking77).
104
+
105
+ The original 10,003/3,080 train/test CSVs, category list and CC BY 4.0 license are unmodified. Exact original commit/file hashes and reuse provenance are in `data/SOURCE.json`. This is the same public dataset used in the prior study, not a newly collected corpus. Category ids follow the original `categories.json` order, not HF's alphabetic encoding; row ids are zero-based CSV records after the header, not physical line numbers.
106
+
107
+ The code is Apache 2.0. Original data, saved weights and derived experimental artifacts retain CC BY 4.0 attribution as specified in `LICENSES.md`, `NOTICE` and the original bundled data license. No dataset ownership or PolyAI endorsement is claimed. No employer material, private records, external model weights or paid inference resources were used.
108
+
109
+ ## Reproduce
110
+
111
+ ```sh
112
+ python3 -m venv .venv
113
+ .venv/bin/python -m pip install -r requirements.txt
114
+ .venv/bin/python -m unittest test_model -v
115
+ OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 .venv/bin/python train.py --data data --output fresh-run
116
+ .venv/bin/python evaluate.py --data data --run fresh-run --output fresh-evaluation
117
+ .venv/bin/python infer.py 'Where is my card? It has not arrived.'
118
+ .venv/bin/python verify_results.py
119
+ node test_inference.mjs
120
+ .venv/bin/python verify_portable.py
121
+ ```
122
+
123
+ Use new output directories. Existing runs are not overwritten. The trainer semantically loads original train only; source test bytes may be hashed for provenance. `PREFIT.json` was written before the first update. `PRETEST.json` froze selected model/temperature/quantization/source/code hashes before this model first loaded and scored official test; `EVALUATION-FREEZE.json` records the evaluator and pretest hashes. These local records do not externally attest historical blindness.
124
+
125
+ The bundled experiment used Python 3.14.7 / NumPy 2.5.4 and capped numerical threads. Node checks used 24.19.0. Different floating algebra or runtime can change near ties; no universal byte-identical prediction promise is made. Keep frozen source/config files unchanged for the hash gates. Tests should run in a copy of a release candidate if regenerating their output fixtures.
126
+
127
+ The six prefit test groups include finite differences over all parameters of a small network, a hand forward pass, stable loss, Adam first-step correction, feature/Unicode/limits and quantization error bounds. The separate verifier independently rebuilds 22 float/int8 forward rows, twenty Adam steps from closed-form moment sums, and all 12,320 metric rows plus class/subset/ECE counts from saved logits. It retains both quantization disagreements.
128
+
129
+ Portable conformance tests cover twelve valid ordinary/Unicode/script-shaped/max-length vectors and three rejected inputs in both temperature modes. Actual native browser checks executed all thirty corresponding actions: 24 results and six rejected mode/input combinations, real report download, input-edit export clearing, 390-pixel layout and absence of query requests in the local server log. Browser and Python probabilities agreed within 1e-9; observed maximum difference was 6.67e-16. These are implementation conformance tests, not cross-language task-quality or external adoption evidence.
130
+
131
+ To regenerate the scientific figure, install `requirements-plot.txt` and run `plot_training.py` with a local `MPLCONFIGDIR`. It uses the noninteractive Agg backend and only saved trace/calibration data; no GUI window is opened. The optional plotting dependency is not needed for inference or training.
132
+
133
+ ## 中文:先从两条求助说起
134
+
135
+ 设想两个人分别说:“取款机把我的卡吞了”和“卡退回来了,但我没拿到钱”。两句话都提到取款机和银行卡,问题却不同。把它们分到合适的类别,就是这次实验要说明的“意图分类”。这是帮助理解的假设场景,不是真实客户案例,也不是对这两句原话的实测结果。
136
+
137
+ 我用公开BANKING77的77类英语请求,从随机初值开始,在CPU上训练了一个小网络。它把短字符片段变成可计算的特征,再学习这些特征与类别的关系。页面里的模型不用写回复;你输入一句话,它给出分类和分数,并允许下载完整结果。初次加载固定模型资源之后,分类计算在浏览器本地完成。
138
+
139
+ 训练共做完30轮,用留出的验证数据选择第28轮。随后固定模型及分数调整,再评测这个模型的测试结果:3080条中2779条分类正确,301条分错,全部错误保留。这个公开基准在前作里已经用过,不能把本次写成从未见过数据的盲测。
140
+
141
+ 一个值得看细节的结果是:把权重压缩为较小��存储形式后,正确总数没变,却有两条原本就分错的请求,换成了另一种错误标签。只看准确率,就看不到这件事。页面里的压缩权重仍会先还原成浮点数再计算,不能据文件变小就宣称推理更快。
142
+
143
+ 另一个限制更直接:输入天气或其他不相关内容,它也会硬选一个银行类别。模型没有“以上都不是”的判断,所以高分不等于请求适用,更不代表可以接入银行业务。这个作品交付的是可以检查、重训和试用的小模型实验;下面保留完整方法、失败和许可。
144
+
145
+ ## 中文说明
146
+
147
+ 这是在公开BANKING77上真实从零CPU训练的小型字符哈希神经分类器,267213个参数,浏览器可本地运行。完整3080条测试中浮点和量化都答对2779条,但两条错误记录换了另一种错误标签,因此不能说量化预测完全一样。完整错误、概率指标和3073条无规范化重复的子集结果均保留。
148
+
149
+ 同一训练得到浮点、量化以及不同温度的评测形式,不算四个独立模型。训练与验证方案先固定,30轮全部完成,以验证NLL选第28轮,再用验证集固定温度网格选0.75,之后才测这个模型的测试结果。数据集在前一项目中已用过,不冒称新盲测或新采集资料。
150
+
151
+ 模型只有77个英语闭集类别,没有域外拒答能力;中文等输入的一致性检查不代表跨语种分类能力。量化是权重存储形式,浏览器解量化后用浮点计算,不宣传纯整数内核、推理提速或银行业务决策能力。输入仅本地处理,下载报告含原文,分享前应检查。本包记录2026-11-04本地准备,云端公开运行另按实际发布回执核验。
SOURCE.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "work_identity": "work:tiny-hash-intent:v1",
3
+ "snapshot_date": "2026-11-04",
4
+ "origin": "Original from-scratch CPU fit and browser inference over the unchanged public BANKING77 source recorded in data/SOURCE.json",
5
+ "prefit_sha256": "bad33e33120df6d7ad03452547dc7aa30b1e1e7fcf6ad1f3de0a599d2e498d68",
6
+ "pretest_sha256": "cce143034b86135c978e28c0e54160324635b38f2ef5be5bcacc6fe34cffd435",
7
+ "evaluation_sha256": "8a6fb12566d67754feb6ff794e34a68c727ee1020d8dcb8cda20518ab71582f2",
8
+ "model_files": {
9
+ "model-float64.npz": "fcfb60826d8d251b9b2e9f42765e3157e06e7292f0107151e99a4fcf3737d8d1",
10
+ "model-int8.json": "b9b8081ed0026d315574b7e2f1ff1b6de472a9d4724b23e6e1980618724388c4"
11
+ },
12
+ "one_training_run": true,
13
+ "selected_epoch": 28,
14
+ "scope": "Same original dataset previously used by a separate study, not new independent data or historically blind benchmark. Float/int8 and temperature modes are one fit, not multiple training projects. No cloud run or user adoption implied."
15
+ }
app.mjs ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { parseModel, predict } from "./inference.mjs";
2
+ const $ = (id) => document.getElementById(id);
3
+ let model = null,
4
+ modelSHA = null,
5
+ url = null;
6
+ function clear(message = "Input changed. Classify again for current results.") {
7
+ if (url) URL.revokeObjectURL(url);
8
+ url = null;
9
+ $("downloads").replaceChildren();
10
+ $("report").textContent = "";
11
+ $("results").hidden = true;
12
+ $("placeholder").hidden = false;
13
+ $("error").hidden = true;
14
+ $("state").textContent = message;
15
+ }
16
+ for (const id of ["query", "calibrated"])
17
+ $(id).addEventListener("input", () => clear());
18
+ function fail(message) {
19
+ $("error").textContent = message;
20
+ $("error").hidden = false;
21
+ $("error").focus();
22
+ }
23
+ $("run").addEventListener("click", () => {
24
+ clear();
25
+ if (!model) {
26
+ fail("Model weights are not ready. Reload the page to retry.");
27
+ return;
28
+ }
29
+ try {
30
+ const input = $("query").value,
31
+ result = predict(model, input, $("calibrated").checked),
32
+ report = {
33
+ model_version: model.version,
34
+ work_identity: "work:tiny-hash-intent:v1",
35
+ model_file_sha256: modelSHA,
36
+ input,
37
+ representation:
38
+ "per-row/per-column int8 stored weights, dequantized Float64 inference",
39
+ ...result,
40
+ scope:
41
+ "closed-set English benchmark model; class scores do not establish correctness or OOD detection",
42
+ };
43
+ $("prediction").textContent = result.predicted_label;
44
+ $("condition").textContent =
45
+ `${result.feature_bins_used} hashed feature bins · temperature ${result.temperature} · 77 known classes`;
46
+ $("top3").replaceChildren();
47
+ for (const item of result.top3) {
48
+ const li = document.createElement("li"),
49
+ name = document.createElement("span"),
50
+ score = document.createElement("strong");
51
+ name.textContent = item.label;
52
+ score.textContent = (100 * item.score).toFixed(2) + "%";
53
+ li.append(name, score);
54
+ $("top3").append(li);
55
+ }
56
+ $("report").textContent = JSON.stringify(report, null, 2);
57
+ url = URL.createObjectURL(
58
+ new Blob([JSON.stringify(report, null, 2) + "\n"], {
59
+ type: "application/json;charset=utf-8",
60
+ }),
61
+ );
62
+ const a = document.createElement("a");
63
+ a.textContent = "Download current inference report";
64
+ a.href = url;
65
+ a.download = "tiny-hash-intent-report.json";
66
+ $("downloads").append(a);
67
+ $("placeholder").hidden = true;
68
+ $("results").hidden = false;
69
+ $("state").textContent =
70
+ "Inference completed locally for the current text.";
71
+ } catch (e) {
72
+ fail(e.message || "Inference failed.");
73
+ $("state").textContent = "No result for the current input.";
74
+ }
75
+ });
76
+ try {
77
+ const response = await fetch("run-001/model-int8.json", {
78
+ cache: "no-store",
79
+ });
80
+ if (!response.ok) throw Error("Fixed model asset could not load.");
81
+ const raw = await response.text();
82
+ model = parseModel(raw);
83
+ if (!crypto.subtle)
84
+ throw Error("Use HTTPS or localhost for model identity hashing.");
85
+ modelSHA = Array.from(
86
+ new Uint8Array(
87
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)),
88
+ ),
89
+ (b) => b.toString(16).padStart(2, "0"),
90
+ ).join("");
91
+ $("run").disabled = false;
92
+ $("state").textContent = "Fixed model ready. Your input stays local.";
93
+ } catch (e) {
94
+ model = null;
95
+ fail(e.message || "Model could not load.");
96
+ $("state").textContent =
97
+ "Model unavailable. Serve the complete release over HTTP(S) and reload.";
98
+ }
data/LICENSE-CC-BY-4.0 ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More_considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution 4.0 International Public License
58
+
59
+ By exercising the Licensed Rights (defined below), You accept and agree
60
+ to be bound by the terms and conditions of this Creative Commons
61
+ Attribution 4.0 International Public License ("Public License"). To the
62
+ extent this Public License may be interpreted as a contract, You are
63
+ granted the Licensed Rights in consideration of Your acceptance of
64
+ these terms and conditions, and the Licensor grants You such rights in
65
+ consideration of benefits the Licensor receives from making the
66
+ Licensed Material available under these terms and conditions.
67
+
68
+
69
+ Section 1 -- Definitions.
70
+
71
+ a. Adapted Material means material subject to Copyright and Similar
72
+ Rights that is derived from or based upon the Licensed Material
73
+ and in which the Licensed Material is translated, altered,
74
+ arranged, transformed, or otherwise modified in a manner requiring
75
+ permission under the Copyright and Similar Rights held by the
76
+ Licensor. For purposes of this Public License, where the Licensed
77
+ Material is a musical work, performance, or sound recording,
78
+ Adapted Material is always produced where the Licensed Material is
79
+ synched in timed relation with a moving image.
80
+
81
+ b. Adapter's License means the license You apply to Your Copyright
82
+ and Similar Rights in Your contributions to Adapted Material in
83
+ accordance with the terms and conditions of this Public License.
84
+
85
+ c. Copyright and Similar Rights means copyright and/or similar rights
86
+ closely related to copyright including, without limitation,
87
+ performance, broadcast, sound recording, and Sui Generis Database
88
+ Rights, without regard to how the rights are labeled or
89
+ categorized. For purposes of this Public License, the rights
90
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
91
+ Rights.
92
+
93
+ d. Effective Technological Measures means those measures that, in the
94
+ absence of proper authority, may not be circumvented under laws
95
+ fulfilling obligations under Article 11 of the WIPO Copyright
96
+ Treaty adopted on December 20, 1996, and/or similar international
97
+ agreements.
98
+
99
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
100
+ any other exception or limitation to Copyright and Similar Rights
101
+ that applies to Your use of the Licensed Material.
102
+
103
+ f. Licensed Material means the artistic or literary work, database,
104
+ or other material to which the Licensor applied this Public
105
+ License.
106
+
107
+ g. Licensed Rights means the rights granted to You subject to the
108
+ terms and conditions of this Public License, which are limited to
109
+ all Copyright and Similar Rights that apply to Your use of the
110
+ Licensed Material and that the Licensor has authority to license.
111
+
112
+ h. Licensor means the individual(s) or entity(ies) granting rights
113
+ under this Public License.
114
+
115
+ i. Share means to provide material to the public by any means or
116
+ process that requires permission under the Licensed Rights, such
117
+ as reproduction, public display, public performance, distribution,
118
+ dissemination, communication, or importation, and to make material
119
+ available to the public including in ways that members of the
120
+ public may access the material from a place and at a time
121
+ individually chosen by them.
122
+
123
+ j. Sui Generis Database Rights means rights other than copyright
124
+ resulting from Directive 96/9/EC of the European Parliament and of
125
+ the Council of 11 March 1996 on the legal protection of databases,
126
+ as amended and/or succeeded, as well as other essentially
127
+ equivalent rights anywhere in the world.
128
+
129
+ k. You means the individual or entity exercising the Licensed Rights
130
+ under this Public License. Your has a corresponding meaning.
131
+
132
+
133
+ Section 2 -- Scope.
134
+
135
+ a. License grant.
136
+
137
+ 1. Subject to the terms and conditions of this Public License,
138
+ the Licensor hereby grants You a worldwide, royalty-free,
139
+ non-sublicensable, non-exclusive, irrevocable license to
140
+ exercise the Licensed Rights in the Licensed Material to:
141
+
142
+ a. reproduce and Share the Licensed Material, in whole or
143
+ in part; and
144
+
145
+ b. produce, reproduce, and Share Adapted Material.
146
+
147
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
148
+ Exceptions and Limitations apply to Your use, this Public
149
+ License does not apply, and You do not need to comply with
150
+ its terms and conditions.
151
+
152
+ 3. Term. The term of this Public License is specified in Section
153
+ 6(a).
154
+
155
+ 4. Media and formats; technical modifications allowed. The
156
+ Licensor authorizes You to exercise the Licensed Rights in
157
+ all media and formats whether now known or hereafter created,
158
+ and to make technical modifications necessary to do so. The
159
+ Licensor waives and/or agrees not to assert any right or
160
+ authority to forbid You from making technical modifications
161
+ necessary to exercise the Licensed Rights, including
162
+ technical modifications necessary to circumvent Effective
163
+ Technological Measures. For purposes of this Public License,
164
+ simply making modifications authorized by this Section 2(a)
165
+ (4) never produces Adapted Material.
166
+
167
+ 5. Downstream recipients.
168
+
169
+ a. Offer from the Licensor -- Licensed Material. Every
170
+ recipient of the Licensed Material automatically
171
+ receives an offer from the Licensor to exercise the
172
+ Licensed Rights under the terms and conditions of this
173
+ Public License.
174
+
175
+ b. No downstream restrictions. You may not offer or impose
176
+ any additional or different terms or conditions on, or
177
+ apply any Effective Technological Measures to, the
178
+ Licensed Material if doing so restricts exercise of the
179
+ Licensed Rights by any recipient of the Licensed
180
+ Material.
181
+
182
+ 6. No endorsement. Nothing in this Public License constitutes or
183
+ may be construed as permission to assert or imply that You
184
+ are, or that Your use of the Licensed Material is, connected
185
+ with, or sponsored, endorsed, or granted official status by,
186
+ the Licensor or others designated to receive attribution as
187
+ provided in Section 3(a)(1)(A)(i).
188
+
189
+ b. Other rights.
190
+
191
+ 1. Moral rights, such as the right of integrity, are not
192
+ licensed under this Public License, nor are publicity,
193
+ privacy, and/or other similar personality rights; however, to
194
+ the extent possible, the Licensor waives and/or agrees not to
195
+ assert any such rights held by the Licensor to the limited
196
+ extent necessary to allow You to exercise the Licensed
197
+ Rights, but not otherwise.
198
+
199
+ 2. Patent and trademark rights are not licensed under this
200
+ Public License.
201
+
202
+ 3. To the extent possible, the Licensor waives any right to
203
+ collect royalties from You for the exercise of the Licensed
204
+ Rights, whether directly or through a collecting society
205
+ under any voluntary or waivable statutory or compulsory
206
+ licensing scheme. In all other cases the Licensor expressly
207
+ reserves any right to collect such royalties.
208
+
209
+
210
+ Section 3 -- License Conditions.
211
+
212
+ Your exercise of the Licensed Rights is expressly made subject to the
213
+ following conditions.
214
+
215
+ a. Attribution.
216
+
217
+ 1. If You Share the Licensed Material (including in modified
218
+ form), You must:
219
+
220
+ a. retain the following if it is supplied by the Licensor
221
+ with the Licensed Material:
222
+
223
+ i. identification of the creator(s) of the Licensed
224
+ Material and any others designated to receive
225
+ attribution, in any reasonable manner requested by
226
+ the Licensor (including by pseudonym if
227
+ designated);
228
+
229
+ ii. a copyright notice;
230
+
231
+ iii. a notice that refers to this Public License;
232
+
233
+ iv. a notice that refers to the disclaimer of
234
+ warranties;
235
+
236
+ v. a URI or hyperlink to the Licensed Material to the
237
+ extent reasonably practicable;
238
+
239
+ b. indicate if You modified the Licensed Material and
240
+ retain an indication of any previous modifications; and
241
+
242
+ c. indicate the Licensed Material is licensed under this
243
+ Public License, and include the text of, or the URI or
244
+ hyperlink to, this Public License.
245
+
246
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
247
+ reasonable manner based on the medium, means, and context in
248
+ which You Share the Licensed Material. For example, it may be
249
+ reasonable to satisfy the conditions by providing a URI or
250
+ hyperlink to a resource that includes the required
251
+ information.
252
+
253
+ 3. If requested by the Licensor, You must remove any of the
254
+ information required by Section 3(a)(1)(A) to the extent
255
+ reasonably practicable.
256
+
257
+ 4. If You Share Adapted Material You produce, the Adapter's
258
+ License You apply must not prevent recipients of the Adapted
259
+ Material from complying with this Public License.
260
+
261
+
262
+ Section 4 -- Sui Generis Database Rights.
263
+
264
+ Where the Licensed Rights include Sui Generis Database Rights that
265
+ apply to Your use of the Licensed Material:
266
+
267
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
268
+ to extract, reuse, reproduce, and Share all or a substantial
269
+ portion of the contents of the database;
270
+
271
+ b. if You include all or a substantial portion of the database
272
+ contents in a database in which You have Sui Generis Database
273
+ Rights, then the database in which You have Sui Generis Database
274
+ Rights (but not its individual contents) is Adapted Material; and
275
+
276
+ c. You must comply with the conditions in Section 3(a) if You Share
277
+ all or a substantial portion of the contents of the database.
278
+
279
+ For the avoidance of doubt, this Section 4 supplements and does not
280
+ replace Your obligations under this Public License where the Licensed
281
+ Rights include other Copyright and Similar Rights.
282
+
283
+
284
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
285
+
286
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
287
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
288
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
289
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
290
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
291
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
292
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
293
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
294
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
295
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
296
+
297
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
298
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
299
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
300
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
301
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
302
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
303
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
304
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
305
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
306
+
307
+ c. The disclaimer of warranties and limitation of liability provided
308
+ above shall be interpreted in a manner that, to the extent
309
+ possible, most closely approximates an absolute disclaimer and
310
+ waiver of all liability.
311
+
312
+
313
+ Section 6 -- Term and Termination.
314
+
315
+ a. This Public License applies for the term of the Copyright and
316
+ Similar Rights licensed here. However, if You fail to comply with
317
+ this Public License, then Your rights under this Public License
318
+ terminate automatically.
319
+
320
+ b. Where Your right to use the Licensed Material has terminated under
321
+ Section 6(a), it reinstates:
322
+
323
+ 1. automatically as of the date the violation is cured, provided
324
+ it is cured within 30 days of Your discovery of the
325
+ violation; or
326
+
327
+ 2. upon express reinstatement by the Licensor.
328
+
329
+ For the avoidance of doubt, this Section 6(b) does not affect any
330
+ right the Licensor may have to seek remedies for Your violations
331
+ of this Public License.
332
+
333
+ c. For the avoidance of doubt, the Licensor may also offer the
334
+ Licensed Material under separate terms or conditions or stop
335
+ distributing the Licensed Material at any time; however, doing so
336
+ will not terminate this Public License.
337
+
338
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
339
+ License.
340
+
341
+
342
+ Section 7 -- Other Terms and Conditions.
343
+
344
+ a. The Licensor shall not be bound by any additional or different
345
+ terms or conditions communicated by You unless expressly agreed.
346
+
347
+ b. Any arrangements, understandings, or agreements regarding the
348
+ Licensed Material not stated herein are separate from and
349
+ independent of the terms and conditions of this Public License.
350
+
351
+
352
+ Section 8 -- Interpretation.
353
+
354
+ a. For the avoidance of doubt, this Public License does not, and
355
+ shall not be interpreted to, reduce, limit, restrict, or impose
356
+ conditions on any use of the Licensed Material that could lawfully
357
+ be made without permission under this Public License.
358
+
359
+ b. To the extent possible, if any provision of this Public License is
360
+ deemed unenforceable, it shall be automatically reformed to the
361
+ minimum extent necessary to make it enforceable. If the provision
362
+ cannot be reformed, it shall be severed from this Public License
363
+ without affecting the enforceability of the remaining terms and
364
+ conditions.
365
+
366
+ c. No term or condition of this Public License will be waived and no
367
+ failure to comply consented to unless expressly agreed to by the
368
+ Licensor.
369
+
370
+ d. Nothing in this Public License constitutes or may be interpreted
371
+ as a limitation upon, or waiver of, any privileges and immunities
372
+ that apply to the Licensor or You, including from the legal
373
+ processes of any jurisdiction or authority.
374
+
375
+
376
+ =======================================================================
377
+
378
+ Creative Commons is not a party to its public
379
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
380
+ its public licenses to material it publishes and in those instances
381
+ will be considered the “Licensor.” The text of the Creative Commons
382
+ public licenses is dedicated to the public domain under the CC0 Public
383
+ Domain Dedication. Except for the limited purpose of indicating that
384
+ material is shared under a Creative Commons public license or as
385
+ otherwise permitted by the Creative Commons policies published at
386
+ creativecommons.org/policies, Creative Commons does not authorize the
387
+ use of the trademark "Creative Commons" or any other trademark or logo
388
+ of Creative Commons without its prior written consent including,
389
+ without limitation, in connection with any unauthorized modifications
390
+ to any of its public licenses or any other arrangements,
391
+ understandings, or agreements concerning use of licensed material. For
392
+ the avoidance of doubt, this paragraph does not form part of the
393
+ public licenses.
394
+
395
+ Creative Commons may be contacted at creativecommons.org.
data/SOURCE.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "work_identity": "work:tiny-hash-intent:v1",
3
+ "snapshot_date": "2026-11-04",
4
+ "source_origin": {
5
+ "dataset": "BANKING77",
6
+ "owner": "PolyAI",
7
+ "origin": "https://github.com/PolyAI-LDN/task-specific-datasets",
8
+ "original_data_commit": "9d081458ff52e53cf7e848f414e6e9344e4e6696",
9
+ "license_commit": "3bf93de788b9362c34d06cba1d271bc23dd1bcb6",
10
+ "license": "CC-BY-4.0",
11
+ "citation": "Casanueva, Temcinas, Gerz, Henderson and Vulic (2020), Efficient Intent Detection with Dual Sentence Encoders. https://arxiv.org/abs/2003.04807",
12
+ "obtained": "2026-11-04 via author GitHub Download raw file using official CUA; files unmodified",
13
+ "files": {
14
+ "train.csv": {
15
+ "sha256": "b06e26ac675513959a63135f11b94ea7786ed02da65db93a5650d8838cbc664b",
16
+ "bytes": 839073,
17
+ "source_url": "https://github.com/PolyAI-LDN/task-specific-datasets/blob/9d081458ff52e53cf7e848f414e6e9344e4e6696/banking_data/train.csv"
18
+ },
19
+ "test.csv": {
20
+ "sha256": "d12d6e3bc4c3103966ae786dc435913c0c563dfa328f5a3646d0e62cfeeb474d",
21
+ "bytes": 239961,
22
+ "source_url": "https://github.com/PolyAI-LDN/task-specific-datasets/blob/9d081458ff52e53cf7e848f414e6e9344e4e6696/banking_data/test.csv"
23
+ },
24
+ "categories.json": {
25
+ "sha256": "53261da888122daf2d120d925458631d9619e15d82e56052e7a42e535ce32b63",
26
+ "bytes": 2036,
27
+ "source_url": "https://github.com/PolyAI-LDN/task-specific-datasets/blob/9d081458ff52e53cf7e848f414e6e9344e4e6696/banking_data/categories.json"
28
+ },
29
+ "LICENSE-CC-BY-4.0": {
30
+ "sha256": "7e7170e3cebf88a9f60c7b8421418323c09304da1af4d5e90f4da1dc1c8a2661",
31
+ "bytes": 18650,
32
+ "source_url": "https://github.com/PolyAI-LDN/task-specific-datasets/blob/3bf93de788b9362c34d06cba1d271bc23dd1bcb6/LICENSE"
33
+ }
34
+ }
35
+ },
36
+ "reused_from_work_identity": "work:label-budget-lab:v1",
37
+ "scope": "Exact same public author data bytes, not a new dataset; earlier study already viewed benchmark test results. New model-specific choices fixed before implementing or fitting this model."
38
+ }
data/categories.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "card_arrival",
3
+ "card_linking",
4
+ "exchange_rate",
5
+ "card_payment_wrong_exchange_rate",
6
+ "extra_charge_on_statement",
7
+ "pending_cash_withdrawal",
8
+ "fiat_currency_support",
9
+ "card_delivery_estimate",
10
+ "automatic_top_up",
11
+ "card_not_working",
12
+ "exchange_via_app",
13
+ "lost_or_stolen_card",
14
+ "age_limit",
15
+ "pin_blocked",
16
+ "contactless_not_working",
17
+ "top_up_by_bank_transfer_charge",
18
+ "pending_top_up",
19
+ "cancel_transfer",
20
+ "top_up_limits",
21
+ "wrong_amount_of_cash_received",
22
+ "card_payment_fee_charged",
23
+ "transfer_not_received_by_recipient",
24
+ "supported_cards_and_currencies",
25
+ "getting_virtual_card",
26
+ "card_acceptance",
27
+ "top_up_reverted",
28
+ "balance_not_updated_after_cheque_or_cash_deposit",
29
+ "card_payment_not_recognised",
30
+ "edit_personal_details",
31
+ "why_verify_identity",
32
+ "unable_to_verify_identity",
33
+ "get_physical_card",
34
+ "visa_or_mastercard",
35
+ "topping_up_by_card",
36
+ "disposable_card_limits",
37
+ "compromised_card",
38
+ "atm_support",
39
+ "direct_debit_payment_not_recognised",
40
+ "passcode_forgotten",
41
+ "declined_cash_withdrawal",
42
+ "pending_card_payment",
43
+ "lost_or_stolen_phone",
44
+ "request_refund",
45
+ "declined_transfer",
46
+ "Refund_not_showing_up",
47
+ "declined_card_payment",
48
+ "pending_transfer",
49
+ "terminate_account",
50
+ "card_swallowed",
51
+ "transaction_charged_twice",
52
+ "verify_source_of_funds",
53
+ "transfer_timing",
54
+ "reverted_card_payment?",
55
+ "change_pin",
56
+ "beneficiary_not_allowed",
57
+ "transfer_fee_charged",
58
+ "receiving_money",
59
+ "failed_transfer",
60
+ "transfer_into_account",
61
+ "verify_top_up",
62
+ "getting_spare_card",
63
+ "top_up_by_cash_or_cheque",
64
+ "order_physical_card",
65
+ "virtual_card_not_working",
66
+ "wrong_exchange_rate_for_cash_withdrawal",
67
+ "get_disposable_virtual_card",
68
+ "top_up_failed",
69
+ "balance_not_updated_after_bank_transfer",
70
+ "cash_withdrawal_not_recognised",
71
+ "exchange_charge",
72
+ "top_up_by_card_charge",
73
+ "activate_my_card",
74
+ "cash_withdrawal_charge",
75
+ "card_about_to_expire",
76
+ "apple_pay_or_google_pay",
77
+ "verify_my_identity",
78
+ "country_support"
79
+ ]
data/test.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/train.csv ADDED
The diff for this file is too large to render. See raw diff
 
evaluate.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score all official rows only after the selected model/export test freeze."""
2
+
3
+ import argparse, csv, json
4
+ from pathlib import Path
5
+ import unicodedata
6
+ import numpy as np
7
+ from model import (
8
+ CONFIG,
9
+ PARAMETERS,
10
+ file_sha,
11
+ load_csv,
12
+ features,
13
+ logits_for,
14
+ nll,
15
+ probabilities,
16
+ decode_portable,
17
+ normalized,
18
+ )
19
+
20
+
21
+ def statistics(logits, gold, temperature, labels):
22
+ n = len(gold)
23
+ c = len(labels)
24
+ prob = probabilities(logits, temperature)
25
+ pred = np.argmax(logits, axis=1)
26
+ confidence = prob[np.arange(n), pred]
27
+ loss = nll(logits, gold, temperature)
28
+ difference = prob.copy()
29
+ difference[np.arange(n), gold] -= 1
30
+ brier = np.sum(difference * difference, axis=1)
31
+ cm = np.zeros((c, c), dtype=np.int64)
32
+ np.add.at(cm, (gold, pred), 1)
33
+ classes = []
34
+ for k, label in enumerate(labels):
35
+ actual = int(cm[k].sum())
36
+ called = int(cm[:, k].sum())
37
+ tp = int(cm[k, k])
38
+ classes.append(
39
+ {
40
+ "label_id": k,
41
+ "label": label,
42
+ "support": actual,
43
+ "predicted": called,
44
+ "correct": tp,
45
+ "precision": tp / called if called else 0.0,
46
+ "recall": tp / actual if actual else 0.0,
47
+ "f1": 2 * tp / (actual + called) if actual + called else 0.0,
48
+ }
49
+ )
50
+ bins = []
51
+ binids = np.minimum(9, np.floor(confidence * 10).astype(int))
52
+ ece = 0.0
53
+ for b in range(10):
54
+ mask = binids == b
55
+ size = int(mask.sum())
56
+ acc = float((pred[mask] == gold[mask]).mean()) if size else None
57
+ conf = float(confidence[mask].mean()) if size else None
58
+ bins.append(
59
+ {
60
+ "bin": b,
61
+ "lower_inclusive": b / 10,
62
+ "upper": (b + 1) / 10,
63
+ "upper_inclusive": b == 9,
64
+ "n": size,
65
+ "accuracy": acc,
66
+ "mean_confidence": conf,
67
+ }
68
+ )
69
+ if size:
70
+ ece += size / n * abs(acc - conf)
71
+ summary = {
72
+ "n": n,
73
+ "correct": int((pred == gold).sum()),
74
+ "accuracy": float((pred == gold).mean()) if n else None,
75
+ "macro_f1": float(np.mean([x["f1"] for x in classes])) if n else None,
76
+ "nll": float(loss.mean()) if n else None,
77
+ "brier": float(brier.mean()) if n else None,
78
+ "ece10": ece if n else None,
79
+ "ece_bins": bins,
80
+ "per_class": classes,
81
+ "confusion": cm.tolist(),
82
+ }
83
+ return summary, {
84
+ "pred": pred,
85
+ "confidence": confidence,
86
+ "p_gold": prob[np.arange(n), gold],
87
+ "nll": loss,
88
+ "brier": brier,
89
+ }
90
+
91
+
92
+ def evaluate(data, run, out):
93
+ if out.exists():
94
+ raise ValueError("New evaluation directory required.")
95
+ root = Path(__file__).resolve().parent
96
+ pre = json.loads((run / "PRETEST.json").read_text())
97
+ if pre["configuration"] != CONFIG:
98
+ raise ValueError("Configuration differs from PRETEST.")
99
+ for name, digest in pre["artifact_sha256"].items():
100
+ if file_sha(run / name) != digest:
101
+ raise ValueError("Frozen model/run artifact changed: " + name)
102
+ for name, digest in pre["implementation_sha256"].items():
103
+ if file_sha(root / name) != digest:
104
+ raise ValueError("Frozen implementation changed: " + name)
105
+ for name, digest in pre["source_sha256"].items():
106
+ if file_sha(data / name) != digest:
107
+ raise ValueError("Original data changed: " + name)
108
+ frozen_protocol = json.loads((root / "PROTOCOL-FREEZE.json").read_text())
109
+ for name, digest in frozen_protocol["sha256"].items():
110
+ if file_sha(root / name) != digest:
111
+ raise ValueError("Protocol/source snapshot differs.")
112
+ labels = json.loads((data / "categories.json").read_text())
113
+ lookup = {l: i for i, l in enumerate(labels)}
114
+ prefit = json.loads((run / "PREFIT.json").read_text())
115
+ test = load_csv(data / "test.csv", labels)
116
+ train = load_csv(data / "train.csv", labels)
117
+ assert len(test) == 3080
118
+ # First semantic test load for this model occurs after all freeze gates above.
119
+ tx = [features(r["text"]) for r in test]
120
+ gold = np.array([lookup[r["category"]] for r in test])
121
+ lower = {normalized(r["text"]) for r in train}
122
+ casepreserved = lambda s: " ".join(unicodedata.normalize("NFC", s).split())
123
+ case_set = {casepreserved(r["text"]) for r in train}
124
+ exact = {r["text"] for r in train}
125
+ fitset = {normalized(train[i]["text"]) for i in prefit["train_row_ids"]}
126
+ valset = {normalized(train[i]["text"]) for i in prefit["validation_row_ids"]}
127
+ overlap = [i for i, r in enumerate(test) if normalized(r["text"]) in lower]
128
+ overset = set(overlap)
129
+ nonoverlap = np.array(
130
+ [i for i in range(len(test)) if i not in overset], dtype=np.int64
131
+ )
132
+ audit = {
133
+ "official_train_rows": len(train),
134
+ "official_test_rows": len(test),
135
+ "fit_rows": prefit["training_rows"],
136
+ "validation_rows": prefit["validation_rows"],
137
+ "exact_overlap_test_row_ids": [
138
+ i for i, r in enumerate(test) if r["text"] in exact
139
+ ],
140
+ "case_preserving_NFC_whitespace_overlap_test_row_ids": [
141
+ i for i, r in enumerate(test) if casepreserved(r["text"]) in case_set
142
+ ],
143
+ "feature_normalized_overlap_test_row_ids": overlap,
144
+ "feature_overlap_with_fit_test_row_ids": [
145
+ i for i, r in enumerate(test) if normalized(r["text"]) in fitset
146
+ ],
147
+ "feature_overlap_with_validation_test_row_ids": [
148
+ i for i, r in enumerate(test) if normalized(r["text"]) in valset
149
+ ],
150
+ "nonoverlap_test_rows": len(nonoverlap),
151
+ "scope": "literal/normalized duplicate diagnostics only, not semantic contamination or IID certification; all original rows retained",
152
+ }
153
+ with np.load(run / "model-float64.npz", allow_pickle=False) as z:
154
+ p = {k: z[k] for k in PARAMETERS}
155
+ qmodel = json.loads((run / "model-int8.json").read_text())
156
+ q = decode_portable(qmodel)
157
+ fl = logits_for(tx, p)
158
+ ql = logits_for(tx, q)
159
+ out.mkdir()
160
+ np.savez_compressed(
161
+ out / "test-logits.npz",
162
+ float_logits=fl,
163
+ int8_logits=ql,
164
+ gold=gold,
165
+ nonoverlap_row_ids=nonoverlap,
166
+ )
167
+ modes = []
168
+ temperature = pre["selected_temperature"]
169
+ for representation, logits in [("float64", fl), ("int8", ql)]:
170
+ for name, temp in [("raw", 1.0), ("validation_temperature", temperature)]:
171
+ mode = f"{representation}-{name}"
172
+ all_stats, rows = statistics(logits, gold, temp, labels)
173
+ subset_stats, _ = statistics(
174
+ logits[nonoverlap], gold[nonoverlap], temp, labels
175
+ )
176
+ path = out / (mode + ".csv")
177
+ with path.open("w", newline="", encoding="utf-8") as f:
178
+ w = csv.writer(f)
179
+ w.writerow(
180
+ [
181
+ "test_row_id",
182
+ "gold_label_id",
183
+ "predicted_label_id",
184
+ "correct",
185
+ "confidence",
186
+ "p_gold",
187
+ "nll",
188
+ "brier",
189
+ ]
190
+ )
191
+ for i in range(len(test)):
192
+ w.writerow(
193
+ [
194
+ i,
195
+ int(gold[i]),
196
+ int(rows["pred"][i]),
197
+ int(rows["pred"][i] == gold[i]),
198
+ float(rows["confidence"][i]),
199
+ float(rows["p_gold"][i]),
200
+ float(rows["nll"][i]),
201
+ float(rows["brier"][i]),
202
+ ]
203
+ )
204
+ modes.append(
205
+ {
206
+ "mode": mode,
207
+ "representation": representation,
208
+ "temperature": temp,
209
+ "official": all_stats,
210
+ "nonoverlap": subset_stats,
211
+ "row_file": path.name,
212
+ "row_sha256": file_sha(path),
213
+ }
214
+ )
215
+ print(
216
+ mode,
217
+ all_stats["correct"],
218
+ "/",
219
+ len(test),
220
+ "NLL",
221
+ all_stats["nll"],
222
+ "ECE10",
223
+ all_stats["ece10"],
224
+ flush=True,
225
+ )
226
+ disagree = np.flatnonzero(np.argmax(fl, axis=1) != np.argmax(ql, axis=1)).tolist()
227
+ report = {
228
+ "work_identity": CONFIG["model_identity"],
229
+ "version": CONFIG["version"],
230
+ "pretest_sha256": file_sha(run / "PRETEST.json"),
231
+ "evaluator_sha256": file_sha(Path(__file__)),
232
+ "selected_epoch": pre["selected_epoch"],
233
+ "selected_temperature": temperature,
234
+ "one_fit_multiple_representations": True,
235
+ "labels": labels,
236
+ "data_audit": audit,
237
+ "quantization_disagreement_test_row_ids": disagree,
238
+ "quantization_disagreement_count": len(disagree),
239
+ "max_abs_test_logit_difference": float(np.max(np.abs(fl - ql))),
240
+ "modes": modes,
241
+ "scope": "Known public benchmark previously studied; this model first scored it after frozen selection. Closed-set English classifier, no OOD rejection or production/financial-decision claim.",
242
+ }
243
+ (out / "results.json").write_text(
244
+ json.dumps(report, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
245
+ + "\n"
246
+ )
247
+ (out / "data-audit.json").write_text(json.dumps(audit, indent=2) + "\n")
248
+ print("RESULTS", file_sha(out / "results.json"), flush=True)
249
+
250
+
251
+ if __name__ == "__main__":
252
+ a = argparse.ArgumentParser()
253
+ a.add_argument("--data", type=Path, default=Path("data"))
254
+ a.add_argument("--run", type=Path, required=True)
255
+ a.add_argument("--output", type=Path, required=True)
256
+ x = a.parse_args()
257
+ evaluate(x.data, x.run, x.output)
evaluation-001/data-audit.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "official_train_rows": 10003,
3
+ "official_test_rows": 3080,
4
+ "fit_rows": 8998,
5
+ "validation_rows": 1005,
6
+ "exact_overlap_test_row_ids": [],
7
+ "case_preserving_NFC_whitespace_overlap_test_row_ids": [
8
+ 554,
9
+ 976,
10
+ 977,
11
+ 1432,
12
+ 1474,
13
+ 2149,
14
+ 3070
15
+ ],
16
+ "feature_normalized_overlap_test_row_ids": [
17
+ 554,
18
+ 976,
19
+ 977,
20
+ 1432,
21
+ 1474,
22
+ 2149,
23
+ 3070
24
+ ],
25
+ "feature_overlap_with_fit_test_row_ids": [
26
+ 554,
27
+ 976,
28
+ 1474,
29
+ 2149,
30
+ 3070
31
+ ],
32
+ "feature_overlap_with_validation_test_row_ids": [
33
+ 977,
34
+ 1432
35
+ ],
36
+ "nonoverlap_test_rows": 3073,
37
+ "scope": "literal/normalized duplicate diagnostics only, not semantic contamination or IID certification; all original rows retained"
38
+ }
evaluation-001/float64-raw.csv ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-001/float64-validation_temperature.csv ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-001/int8-raw.csv ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-001/int8-validation_temperature.csv ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-001/results.json ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-001/test-logits.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc5832dd29a6bc3254898a7ee572a21d4b371d49374fafcc639586d1441946db
3
+ size 3685679
index.html CHANGED
@@ -1,19 +1,130 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <meta
7
+ http-equiv="Content-Security-Policy"
8
+ content="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'"
9
+ />
10
+ <title>Tiny Hash Intent</title>
11
+ <link rel="stylesheet" href="style.css" />
12
+ <script type="module" src="app.mjs"></script>
13
+ </head>
14
+ <body>
15
+ <main>
16
+ <header>
17
+ <p class="eyebrow">WIDECHAOS / FROM-SCRATCH CPU CLASSIFIER</p>
18
+ <h1>A small model, running in your browser.</h1>
19
+ <p class="lede">
20
+ 267,213 learned parameters. Character hashing, a tanh hidden layer,
21
+ and 77 English banking intents.
22
+ </p>
23
+ <p class="notice">
24
+ Closed set: every valid text receives one of the 77 labels. This model
25
+ cannot detect unrelated requests. Scores are conditional class scores,
26
+ not a guarantee that a label is appropriate.
27
+ </p>
28
+ </header>
29
+ <div class="workspace">
30
+ <section>
31
+ <h2>Try local inference</h2>
32
+ <label for="query">Text to classify</label
33
+ ><textarea
34
+ id="query"
35
+ rows="6"
36
+ spellcheck="false"
37
+ aria-describedby="limit"
38
+ >
39
+ Where is my card? It has not arrived.</textarea
40
+ >
41
+ <p id="limit" class="hint">
42
+ Up to 2,048 UTF-16 units. Long input is rejected, never silently
43
+ shortened. English training data; other languages are not validated.
44
+ </p>
45
+ <label class="check"
46
+ ><input type="checkbox" id="calibrated" checked />Use the
47
+ validation-selected temperature (0.75)</label
48
+ ><button id="run" disabled>Classify locally</button>
49
+ <p id="state" role="status" aria-live="polite">
50
+ Loading fixed model weights…
51
+ </p>
52
+ <p id="error" role="alert" tabindex="-1" hidden></p>
53
+ <p class="hint">
54
+ After loading the fixed asset, inference sends no text to a server
55
+ and uses no model API, storage or telemetry.
56
+ </p>
57
+ <details>
58
+ <summary>How this model was prepared</summary>
59
+ <p>
60
+ One NumPy CPU fit over 8,998 training rows, with 1,005 validation
61
+ rows from the original BANKING77 train split. Thirty epochs were
62
+ completed; epoch 28 was selected by validation NLL, then
63
+ temperature was chosen on validation only.
64
+ </p>
65
+ <p>
66
+ The int8 file stores quantized embedding/output weights with
67
+ floating scales and biases. This browser dequantizes them and
68
+ computes in Float64; it does not use integer-only kernels.
69
+ </p>
70
+ </details>
71
+ </section>
72
+ <section>
73
+ <h2>Inspect the prediction</h2>
74
+ <div id="placeholder" class="placeholder">
75
+ Run a query to inspect its three highest class scores.
76
+ </div>
77
+ <div id="results" hidden>
78
+ <p id="prediction" class="prediction"></p>
79
+ <p id="condition" class="hint"></p>
80
+ <ol id="top3"></ol>
81
+ <p class="notice">
82
+ An unrelated input still receives a label. No abstention
83
+ threshold, banking advice or account operation is provided.
84
+ </p>
85
+ <div id="downloads"></div>
86
+ <p class="hint">
87
+ The report includes your input text, model SHA-256 and all 77
88
+ scores. Review it before sharing.
89
+ </p>
90
+ <details>
91
+ <summary>Full current report</summary>
92
+ <pre id="report"></pre>
93
+ </details>
94
+ </div>
95
+ </section>
96
+ </div>
97
+ <section class="facts">
98
+ <h2>Measured on the known benchmark</h2>
99
+ <p>
100
+ Both representations got 2,779 of 3,080 official test rows correct
101
+ (90.23%). Two predicted labels changed after quantization; the
102
+ unchanged correct count does not mean identical predictions. All
103
+ errors and the 3,073-row nonoverlap subset are retained.
104
+ </p>
105
+ <p>
106
+ This benchmark was already studied in an earlier project. This model's
107
+ architecture, fitting choices and validation-only selection were fixed
108
+ before its own test evaluation. One fit has float/int8 and
109
+ raw/calibrated evaluation modes; these are not four independently
110
+ trained models.
111
+ </p>
112
+ <p>
113
+ <a href="README.md"
114
+ >Training, calibration, metrics, attribution and reproduction</a
115
+ >
116
+ </p>
117
+ </section>
118
+ <footer>
119
+ <p>
120
+ Data: PolyAI BANKING77 / Casanueva et al. (2020), CC BY 4.0. Code:
121
+ Renchao Wu, Apache 2.0. Weights and experimental data retain CC BY 4.0
122
+ attribution.
123
+ </p>
124
+ <p lang="zh">
125
+ 真实CPU从零训练,浏览器本地推理。同一模型的量化与校准版本不另算训练;英语闭集分类不识别域外请求,也不代表银行业务建议或生产服务能力。
126
+ </p>
127
+ </footer>
128
+ </main>
129
+ </body>
130
  </html>
infer.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the bundled CPU model locally without server or model API calls."""
2
+
3
+ import argparse, json
4
+ from pathlib import Path
5
+ import numpy as np
6
+ from model import (
7
+ PARAMETERS,
8
+ decode_portable,
9
+ features,
10
+ logits_for,
11
+ probabilities,
12
+ file_sha,
13
+ )
14
+
15
+ r = Path(__file__).resolve().parent
16
+ if __name__ == "__main__":
17
+ a = argparse.ArgumentParser()
18
+ a.add_argument("text")
19
+ a.add_argument("--run", type=Path, default=r / "run-001")
20
+ a.add_argument("--representation", choices=["float64", "int8"], default="int8")
21
+ a.add_argument("--raw", action="store_true")
22
+ x = a.parse_args()
23
+ m = json.loads((x.run / "model-int8.json").read_text())
24
+ T = 1 if x.raw else m["temperature"]
25
+ if x.representation == "int8":
26
+ p = decode_portable(m)
27
+ artifact = x.run / "model-int8.json"
28
+ else:
29
+ artifact = x.run / "model-float64.npz"
30
+ with np.load(artifact, allow_pickle=False) as z:
31
+ p = {k: z[k] for k in PARAMETERS}
32
+ z = logits_for([features(x.text)], p)[0]
33
+ prob = probabilities(z, T)
34
+ order = np.argsort(-z, kind="stable")[:3]
35
+ print(
36
+ json.dumps(
37
+ {
38
+ "input": x.text,
39
+ "representation": x.representation,
40
+ "temperature": T,
41
+ "model_file_sha256": file_sha(artifact),
42
+ "top3": [
43
+ {
44
+ "label_id": int(i),
45
+ "label": m["labels"][int(i)],
46
+ "score": float(prob[int(i)]),
47
+ }
48
+ for i in order
49
+ ],
50
+ "scope": "closed-set English intent labels, no OOD detector or banking advice",
51
+ },
52
+ ensure_ascii=False,
53
+ indent=2,
54
+ )
55
+ )
inference.mjs ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Portable int8 storage, dequantized Float64 arithmetic in a local browser. */
2
+ const PREPROCESS =
3
+ "NFC/lowercase/Python-whitespace; ^text$; codepoint3,4,5 FNV1a32; count-L2";
4
+ const WS =
5
+ /[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/gu;
6
+ const trim = (text) => text.replace(WS, " ").replace(/^ | $/g, "");
7
+ function scalar(text) {
8
+ for (const c of text) {
9
+ const p = c.codePointAt(0);
10
+ if (p >= 0xd800 && p <= 0xdfff) return false;
11
+ }
12
+ return true;
13
+ }
14
+ function keys(value, names) {
15
+ return (
16
+ value &&
17
+ typeof value === "object" &&
18
+ !Array.isArray(value) &&
19
+ Object.keys(value).length === names.length &&
20
+ names.every((k) => Object.hasOwn(value, k))
21
+ );
22
+ }
23
+ function numbers(a, n, positive = false) {
24
+ if (
25
+ !Array.isArray(a) ||
26
+ a.length !== n ||
27
+ a.some(
28
+ (x) =>
29
+ typeof x !== "number" || !Number.isFinite(x) || (positive && x <= 0),
30
+ )
31
+ )
32
+ throw Error("Invalid model numeric array.");
33
+ return a;
34
+ }
35
+ function bytes(value, n) {
36
+ if (
37
+ typeof value !== "string" ||
38
+ value.length !== 4 * Math.ceil(n / 3) ||
39
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(value)
40
+ )
41
+ throw Error("Invalid encoded weights.");
42
+ let raw;
43
+ try {
44
+ raw = atob(value);
45
+ } catch {
46
+ throw Error("Invalid base64 weights.");
47
+ }
48
+ if (raw.length !== n) throw Error("Wrong weight byte count.");
49
+ const q = new Int8Array(n);
50
+ for (let i = 0; i < n; i++) {
51
+ const v = raw.charCodeAt(i);
52
+ q[i] = v > 127 ? v - 256 : v;
53
+ if (q[i] === -128) throw Error("Unsupported -128 quantized value.");
54
+ }
55
+ return q;
56
+ }
57
+ export function parseModel(raw) {
58
+ if (typeof raw !== "string" || new TextEncoder().encode(raw).length > 2097152)
59
+ throw Error("Model asset exceeds 2 MiB.");
60
+ const m = JSON.parse(raw);
61
+ if (
62
+ !keys(m, [
63
+ "schema_version",
64
+ "tool_version",
65
+ "work_identity",
66
+ "dimensions",
67
+ "preprocessing",
68
+ "input_utf16_limit",
69
+ "labels",
70
+ "temperature",
71
+ "embedding_scales",
72
+ "embedding_q_base64",
73
+ "output_scales",
74
+ "output_q_base64",
75
+ "hidden_bias",
76
+ "output_bias",
77
+ ]) ||
78
+ m.schema_version !== 1 ||
79
+ m.tool_version !== "0.1.0" ||
80
+ m.work_identity !== "work:tiny-hash-intent:v1" ||
81
+ m.preprocessing !== PREPROCESS ||
82
+ m.input_utf16_limit !== 2048 ||
83
+ !keys(m.dimensions, ["features", "hidden", "classes"]) ||
84
+ m.dimensions.features !== 4096 ||
85
+ m.dimensions.hidden !== 64 ||
86
+ m.dimensions.classes !== 77
87
+ )
88
+ throw Error("Unsupported portable model schema.");
89
+ if (
90
+ !Array.isArray(m.labels) ||
91
+ m.labels.length !== 77 ||
92
+ new Set(m.labels).size !== 77 ||
93
+ m.labels.some(
94
+ (l) => typeof l !== "string" || !scalar(l) || !trim(l) || l.length > 128,
95
+ )
96
+ )
97
+ throw Error("Invalid model labels.");
98
+ if (
99
+ typeof m.temperature !== "number" ||
100
+ !Number.isFinite(m.temperature) ||
101
+ m.temperature <= 0
102
+ )
103
+ throw Error("Invalid model temperature.");
104
+ const se = numbers(m.embedding_scales, 4096, true),
105
+ sw = numbers(m.output_scales, 77, true),
106
+ qe = bytes(m.embedding_q_base64, 4096 * 64),
107
+ qw = bytes(m.output_q_base64, 64 * 77);
108
+ const E = new Float64Array(qe.length),
109
+ W = new Float64Array(qw.length);
110
+ for (let i = 0; i < E.length; i++) E[i] = qe[i] * se[Math.floor(i / 64)];
111
+ for (let i = 0; i < W.length; i++) W[i] = qw[i] * sw[i % 77];
112
+ if (!E.every(Number.isFinite) || !W.every(Number.isFinite))
113
+ throw Error("Nonfinite dequantized weights.");
114
+ return {
115
+ E,
116
+ W,
117
+ bh: Float64Array.from(numbers(m.hidden_bias, 64)),
118
+ bo: Float64Array.from(numbers(m.output_bias, 77)),
119
+ labels: m.labels.slice(),
120
+ temperature: m.temperature,
121
+ version: m.tool_version,
122
+ };
123
+ }
124
+ export function normalized(text) {
125
+ return trim(text.normalize("NFC").toLowerCase());
126
+ }
127
+ export function fnv(text) {
128
+ let h = 2166136261;
129
+ for (const b of new TextEncoder().encode(text))
130
+ h = Math.imul(h ^ b, 16777619) >>> 0;
131
+ return h;
132
+ }
133
+ export function features(text) {
134
+ if (typeof text !== "string" || !scalar(text) || !trim(text))
135
+ throw Error("Use nonblank Unicode scalar text.");
136
+ if (text.length > 2048)
137
+ throw Error(
138
+ "Input exceeds 2,048 UTF-16 units; no truncation is performed.",
139
+ );
140
+ const chars = Array.from("^" + normalized(text) + "$"),
141
+ counts = new Map();
142
+ for (const n of [3, 4, 5])
143
+ for (let i = 0; i + n <= chars.length; i++) {
144
+ const id = fnv(chars.slice(i, i + n).join("")) % 4096;
145
+ counts.set(id, (counts.get(id) || 0) + 1);
146
+ }
147
+ const ids = [...counts.keys()].sort((a, b) => a - b),
148
+ den = Math.sqrt(ids.reduce((s, id) => s + counts.get(id) ** 2, 0));
149
+ return { ids, values: ids.map((id) => (den ? counts.get(id) / den : 0)) };
150
+ }
151
+ export function predict(model, text, calibrated = true) {
152
+ const f = features(text),
153
+ h = new Float64Array(64),
154
+ logits = new Float64Array(77);
155
+ for (let k = 0; k < 64; k++) {
156
+ let v = model.bh[k];
157
+ for (let j = 0; j < f.ids.length; j++)
158
+ v += f.values[j] * model.E[f.ids[j] * 64 + k];
159
+ if (!Number.isFinite(v)) throw Error("Nonfinite hidden activation.");
160
+ h[k] = Math.tanh(v);
161
+ }
162
+ for (let c = 0; c < 77; c++) {
163
+ let v = model.bo[c];
164
+ for (let k = 0; k < 64; k++) v += h[k] * model.W[k * 77 + c];
165
+ if (!Number.isFinite(v)) throw Error("Nonfinite class score.");
166
+ logits[c] = v;
167
+ }
168
+ const T = calibrated ? model.temperature : 1;
169
+ if (!Number.isFinite(T) || T <= 0) throw Error("Invalid temperature.");
170
+ const scaled = Array.from(logits, (z) => z / T);
171
+ if (!scaled.every(Number.isFinite))
172
+ throw Error("Nonfinite scaled class score.");
173
+ const max = Math.max(...scaled),
174
+ exp = scaled.map((z) => Math.exp(z - max)),
175
+ sum = exp.reduce((a, b) => a + b, 0),
176
+ prob = exp.map((v) => v / sum);
177
+ const order = Array.from({ length: 77 }, (_, i) => i).sort(
178
+ (a, b) => logits[b] - logits[a] || a - b,
179
+ );
180
+ return {
181
+ predicted_label_id: order[0],
182
+ predicted_label: model.labels[order[0]],
183
+ temperature: T,
184
+ feature_bins_used: f.ids.length,
185
+ top3: order
186
+ .slice(0, 3)
187
+ .map((i) => ({ label_id: i, label: model.labels[i], score: prob[i] })),
188
+ logits: Array.from(logits),
189
+ probabilities: prob,
190
+ };
191
+ }
model.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small from-scratch character-hash neural classifier, CPU/NumPy only."""
2
+
3
+ import base64
4
+ from collections import Counter
5
+ import csv
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+ import unicodedata
10
+ import numpy as np
11
+
12
+ CONFIG = json.loads(Path(__file__).with_name("CONFIG.json").read_text())
13
+ PARAMETERS = ("E", "W", "bh", "bo")
14
+
15
+
16
+ def file_sha(path):
17
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
18
+
19
+
20
+ def normalized(text):
21
+ return " ".join(unicodedata.normalize("NFC", text).lower().split())
22
+
23
+
24
+ def validate_text(text):
25
+ if not isinstance(text, str) or not text.strip():
26
+ raise ValueError("Use nonblank text.")
27
+ try:
28
+ text.encode("utf-8")
29
+ units = len(text.encode("utf-16-le")) // 2
30
+ except UnicodeError:
31
+ raise ValueError("Use valid Unicode scalar text.") from None
32
+ if units > CONFIG["input_utf16_limit"]:
33
+ raise ValueError("Input exceeds 2048 UTF-16 units; no truncation is performed.")
34
+ return text
35
+
36
+
37
+ def fnv(text):
38
+ h = 2166136261
39
+ for b in text.encode("utf-8"):
40
+ h = ((h ^ b) * 16777619) & 0xFFFFFFFF
41
+ return h
42
+
43
+
44
+ def features(text, dimensions=None):
45
+ validate_text(text)
46
+ dimensions = dimensions or CONFIG["feature_bins"]
47
+ value = "^" + normalized(text) + "$"
48
+ counts = Counter()
49
+ for n in CONFIG["ngram_lengths"]:
50
+ for i in range(len(value) - n + 1):
51
+ counts[fnv(value[i : i + n]) % dimensions] += 1
52
+ ids = np.array(sorted(counts), dtype=np.int64)
53
+ values = np.array([counts[int(i)] for i in ids], dtype=np.float64)
54
+ length = float(np.sqrt(values @ values))
55
+ if length:
56
+ values /= length
57
+ return ids, values
58
+
59
+
60
+ def load_csv(path, labels):
61
+ with Path(path).open(encoding="utf-8", newline="") as f:
62
+ r = csv.DictReader(f)
63
+ if r.fieldnames != ["text", "category"]:
64
+ raise ValueError("Expected original text/category CSV.")
65
+ rows = list(r)
66
+ for row in rows:
67
+ if set(row) != {"text", "category"} or row["category"] not in labels:
68
+ raise ValueError("Invalid source row or label.")
69
+ validate_text(row["text"])
70
+ return rows
71
+
72
+
73
+ def initialize(d=4096, h=64, c=77, seed=123, std=0.05):
74
+ rng = np.random.default_rng(seed)
75
+ return {
76
+ "E": rng.normal(0, std, (d, h)),
77
+ "W": rng.normal(0, std, (h, c)),
78
+ "bh": np.zeros(h),
79
+ "bo": np.zeros(c),
80
+ }
81
+
82
+
83
+ def one_forward(x, p):
84
+ ids, values = x
85
+ hidden = np.tanh(values @ p["E"][ids] + p["bh"])
86
+ return hidden, hidden @ p["W"] + p["bo"]
87
+
88
+
89
+ def logsumexp(x):
90
+ m = np.max(x, axis=-1, keepdims=True)
91
+ return np.squeeze(m + np.log(np.exp(x - m).sum(axis=-1, keepdims=True)), axis=-1)
92
+
93
+
94
+ def probabilities(logits, temperature=1.0):
95
+ if not np.isfinite(temperature) or temperature <= 0:
96
+ raise ValueError("Temperature must be finite and positive.")
97
+ z = np.asarray(logits, dtype=np.float64) / temperature
98
+ z -= np.max(z, axis=-1, keepdims=True)
99
+ p = np.exp(z)
100
+ return p / p.sum(axis=-1, keepdims=True)
101
+
102
+
103
+ def logits_for(xs, p):
104
+ return np.array([one_forward(x, p)[1] for x in xs], dtype=np.float64).reshape(
105
+ len(xs), p["W"].shape[1]
106
+ )
107
+
108
+
109
+ def nll(logits, ys, temperature=1.0):
110
+ z = logits / temperature
111
+ return logsumexp(z) - z[np.arange(len(ys)), ys]
112
+
113
+
114
+ def batch_loss_grad(xs, ys, p, l2=1e-4):
115
+ if not len(xs) or len(xs) != len(ys):
116
+ raise ValueError("Nonempty matching batch required.")
117
+ grad = {k: np.zeros_like(p[k]) for k in PARAMETERS}
118
+ ce = 0.0
119
+ for x, y in zip(xs, ys):
120
+ hidden, z = one_forward(x, p)
121
+ ce += float(logsumexp(z) - z[int(y)])
122
+ dz = probabilities(z)
123
+ dz[int(y)] -= 1
124
+ grad["W"] += np.outer(hidden, dz)
125
+ grad["bo"] += dz
126
+ dh = (p["W"] @ dz) * (1 - hidden * hidden)
127
+ grad["bh"] += dh
128
+ ids, values = x
129
+ grad["E"][ids] += values[:, None] * dh[None, :]
130
+ ce /= len(xs)
131
+ for k in PARAMETERS:
132
+ grad[k] /= len(xs)
133
+ penalty = 0.5 * l2 * (float(np.sum(p["E"] ** 2)) + float(np.sum(p["W"] ** 2)))
134
+ grad["E"] += l2 * p["E"]
135
+ grad["W"] += l2 * p["W"]
136
+ if not np.isfinite(ce + penalty) or any(
137
+ not np.all(np.isfinite(g)) for g in grad.values()
138
+ ):
139
+ raise ValueError("Nonfinite loss or gradient.")
140
+ return ce + penalty, ce, grad
141
+
142
+
143
+ class Adam:
144
+ def __init__(self, p, lr=0.003, b1=0.9, b2=0.999, eps=1e-8):
145
+ self.m = {k: np.zeros_like(p[k]) for k in p}
146
+ self.v = {k: np.zeros_like(p[k]) for k in p}
147
+ self.step = 0
148
+ self.lr = lr
149
+ self.b1 = b1
150
+ self.b2 = b2
151
+ self.eps = eps
152
+
153
+ def update(self, p, grad):
154
+ self.step += 1
155
+ for k in p:
156
+ self.m[k] = self.b1 * self.m[k] + (1 - self.b1) * grad[k]
157
+ self.v[k] = self.b2 * self.v[k] + (1 - self.b2) * grad[k] ** 2
158
+ mh = self.m[k] / (1 - self.b1**self.step)
159
+ vh = self.v[k] / (1 - self.b2**self.step)
160
+ p[k] -= self.lr * mh / (np.sqrt(vh) + self.eps)
161
+ if any(not np.all(np.isfinite(v)) for v in p.values()):
162
+ raise ValueError("Nonfinite fitted parameter.")
163
+
164
+
165
+ def portable(p, labels, temperature):
166
+ scaleE = np.max(np.abs(p["E"]), axis=1) / 127
167
+ scaleE = np.where(scaleE == 0, 1, scaleE)
168
+ scaleW = np.max(np.abs(p["W"]), axis=0) / 127
169
+ scaleW = np.where(scaleW == 0, 1, scaleW)
170
+ qe = np.clip(np.rint(p["E"] / scaleE[:, None]), -127, 127).astype(np.int8)
171
+ qw = np.clip(np.rint(p["W"] / scaleW[None, :]), -127, 127).astype(np.int8)
172
+ return {
173
+ "schema_version": 1,
174
+ "tool_version": CONFIG["version"],
175
+ "work_identity": CONFIG["model_identity"],
176
+ "dimensions": {
177
+ "features": len(p["E"]),
178
+ "hidden": len(p["bh"]),
179
+ "classes": len(labels),
180
+ },
181
+ "preprocessing": "NFC/lowercase/Python-whitespace; ^text$; codepoint3,4,5 FNV1a32; count-L2",
182
+ "input_utf16_limit": CONFIG["input_utf16_limit"],
183
+ "labels": labels,
184
+ "temperature": temperature,
185
+ "embedding_scales": scaleE.tolist(),
186
+ "embedding_q_base64": base64.b64encode(qe.tobytes()).decode(),
187
+ "output_scales": scaleW.tolist(),
188
+ "output_q_base64": base64.b64encode(qw.tobytes()).decode(),
189
+ "hidden_bias": p["bh"].tolist(),
190
+ "output_bias": p["bo"].tolist(),
191
+ }
192
+
193
+
194
+ def decode_portable(model):
195
+ if model["schema_version"] != 1 or model["tool_version"] != CONFIG["version"]:
196
+ raise ValueError("Unsupported portable model.")
197
+ d, h, c = [model["dimensions"][k] for k in ["features", "hidden", "classes"]]
198
+ qe = np.frombuffer(
199
+ base64.b64decode(model["embedding_q_base64"], validate=True), dtype=np.int8
200
+ ).reshape(d, h)
201
+ qw = np.frombuffer(
202
+ base64.b64decode(model["output_q_base64"], validate=True), dtype=np.int8
203
+ ).reshape(h, c)
204
+ se = np.asarray(model["embedding_scales"], dtype=np.float64)
205
+ sw = np.asarray(model["output_scales"], dtype=np.float64)
206
+ if (
207
+ se.shape != (d,)
208
+ or sw.shape != (c,)
209
+ or np.any(se <= 0)
210
+ or np.any(sw <= 0)
211
+ or np.any(qe == -128)
212
+ or np.any(qw == -128)
213
+ ):
214
+ raise ValueError("Invalid quantization scales or bytes.")
215
+ p = {
216
+ "E": qe.astype(np.float64) * se[:, None],
217
+ "W": qw.astype(np.float64) * sw[None, :],
218
+ "bh": np.asarray(model["hidden_bias"], dtype=np.float64),
219
+ "bo": np.asarray(model["output_bias"], dtype=np.float64),
220
+ }
221
+ if (
222
+ p["bh"].shape != (h,)
223
+ or p["bo"].shape != (c,)
224
+ or len(model["labels"]) != c
225
+ or any(not np.all(np.isfinite(v)) for v in p.values())
226
+ ):
227
+ raise ValueError("Invalid portable parameter shape/values.")
228
+ return p
plot_training.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plot every saved epoch and temperature candidate without opening a GUI."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import matplotlib
6
+
7
+ matplotlib.use("Agg")
8
+ import matplotlib.pyplot as plt
9
+
10
+ r = Path(__file__).resolve().parent
11
+ trace = json.loads((r / "run-001/trace.json").read_text())
12
+ cal = json.loads((r / "run-001/calibration.json").read_text())
13
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4.4), layout="constrained")
14
+ axes[0].plot(
15
+ [x["epoch"] for x in trace],
16
+ [x["train_epoch_end_nll"] for x in trace],
17
+ label="Train, epoch end",
18
+ color="#335f9c",
19
+ )
20
+ axes[0].plot(
21
+ [x["epoch"] for x in trace],
22
+ [x["validation_nll"] for x in trace],
23
+ label="Validation",
24
+ color="#ad5b26",
25
+ )
26
+ axes[0].axvline(
27
+ cal["selected_epoch"],
28
+ color="#566358",
29
+ ls="--",
30
+ label=f"Selected epoch {cal['selected_epoch']}",
31
+ )
32
+ axes[0].set(
33
+ xlabel="Epoch (all 30 retained)",
34
+ ylabel="Uncalibrated cross-entropy / NLL",
35
+ ylim=(0, None),
36
+ title="One CPU fit, fixed configuration",
37
+ )
38
+ axes[0].legend(fontsize=9)
39
+ grid = cal["temperature_grid"]
40
+ axes[1].plot(
41
+ [x["temperature"] for x in grid],
42
+ [x["validation_nll"] for x in grid],
43
+ marker="o",
44
+ color="#335f9c",
45
+ )
46
+ selected = next(x for x in grid if x["temperature"] == cal["selected_temperature"])
47
+ axes[1].scatter(
48
+ [selected["temperature"]],
49
+ [selected["validation_nll"]],
50
+ s=80,
51
+ color="#ad5b26",
52
+ label=f"Selected T={selected['temperature']}",
53
+ zorder=4,
54
+ )
55
+ axes[1].set(
56
+ xlabel="Temperature (fixed finite grid)",
57
+ ylabel="Validation NLL",
58
+ ylim=(0, None),
59
+ title="Selected float model, validation only",
60
+ )
61
+ axes[1].legend(fontsize=9)
62
+ for ax in axes:
63
+ ax.grid(alpha=0.2)
64
+ fig.suptitle(
65
+ "Tiny Hash Intent · BANKING77 · 8,998 fit / 1,005 validation rows", fontsize=12
66
+ )
67
+ fig.savefig(r / "training-curves.png", dpi=170)
68
+ plt.close(fig)
portable-reference-results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "PASS",
3
+ "total_vectors": 15,
4
+ "valid_vectors": 12,
5
+ "rejected_vectors": 3,
6
+ "max_probability_delta": 1.1102230246251565e-15,
7
+ "scope": "conformance vectors, not language/OOD performance evidence"
8
+ }
predict_driver.mjs ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from "node:fs";
2
+ import { parseModel, predict, features } from "./inference.mjs";
3
+ const model = parseModel(
4
+ fs.readFileSync(
5
+ new URL("./run-001/model-int8.json", import.meta.url),
6
+ "utf8",
7
+ ),
8
+ );
9
+ const cases = JSON.parse(fs.readFileSync(0, "utf8"));
10
+ console.log(
11
+ JSON.stringify(
12
+ cases.map((input) => {
13
+ try {
14
+ return {
15
+ input,
16
+ features: features(input),
17
+ raw: predict(model, input, false),
18
+ calibrated: predict(model, input, true),
19
+ };
20
+ } catch (e) {
21
+ return { input, error: e.message };
22
+ }
23
+ }),
24
+ ),
25
+ );
requirements-plot.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ matplotlib==3.11.2
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ numpy==2.5.4
run-001/PREFIT.json ADDED
The diff for this file is too large to render. See raw diff
 
run-001/PRETEST.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "phase": "training complete, before this model first scores official test",
3
+ "configuration": {
4
+ "version": "0.1.0",
5
+ "feature_bins": 4096,
6
+ "ngram_lengths": [
7
+ 3,
8
+ 4,
9
+ 5
10
+ ],
11
+ "hidden_size": 64,
12
+ "classes": 77,
13
+ "init_seed": 123,
14
+ "shuffle_seed_base": 2026,
15
+ "init_std": 0.05,
16
+ "epochs": 30,
17
+ "batch_size": 128,
18
+ "learning_rate": 0.003,
19
+ "beta1": 0.9,
20
+ "beta2": 0.999,
21
+ "epsilon": 1e-08,
22
+ "l2": 0.0001,
23
+ "temperature_grid": [
24
+ 0.5,
25
+ 0.75,
26
+ 1,
27
+ 1.25,
28
+ 1.5,
29
+ 2,
30
+ 3
31
+ ],
32
+ "input_utf16_limit": 2048,
33
+ "arithmetic": "float64",
34
+ "split": "sha256(feature-normalized-text) integer modulo10 ==0 validation; else train",
35
+ "model_identity": "work:tiny-hash-intent:v1"
36
+ },
37
+ "selected_epoch": 28,
38
+ "selected_temperature": 0.75,
39
+ "initial_parameter_sha256": "1e32ba55e2006034a90a88f1fbc2af65eb5696a1338623e9684739d8ad577e8f",
40
+ "selected_parameter_sha256": "ba69e24521a56d71c024abfde6c08ea57b4f9bf50983967b5e471d332d8724ab",
41
+ "fit_steps": 2130,
42
+ "total_examples_fit": 269940,
43
+ "artifact_sha256": {
44
+ "PREFIT.json": "bad33e33120df6d7ad03452547dc7aa30b1e1e7fcf6ad1f3de0a599d2e498d68",
45
+ "initial-statistics.json": "b688717eba3f9b5f90e7e470b5fc29dde8c17b68c1b5ee25a619461c7f363e66",
46
+ "trace.json": "65046cc2f7f1ed82339d65e707ccfc6ca5299967718e8312bc037afae6e5175f",
47
+ "model-float64.npz": "fcfb60826d8d251b9b2e9f42765e3157e06e7292f0107151e99a4fcf3737d8d1",
48
+ "model-int8.json": "b9b8081ed0026d315574b7e2f1ff1b6de472a9d4724b23e6e1980618724388c4",
49
+ "validation-logits.npz": "e203e9aedfdbf5083891a40f689411d85a57dd2bf1ec0fff585a6b5b6e0ed666",
50
+ "calibration.json": "09de1745929953e2138777af3270e7b618f99a9c388a60964186f26d7af28c90"
51
+ },
52
+ "implementation_sha256": {
53
+ "model.py": "a6b4e59b61e5e9276bd2c29b23580966e813af19d482d7f193ff1f3b58e63e77",
54
+ "train.py": "e390575bf31202abda205668c95c3cdc609c0317609e522137b318008956832f",
55
+ "CONFIG.json": "f456a31e948ae14ae393f9c9d55f8f11d7bf286e7cc05d16ce067fbfecb19813",
56
+ "PROTOCOL.md": "c13007155e43c71acc6b7858674f2a437ddd69782390b3a2023ceef087957cda",
57
+ "PROTOCOL-FREEZE.json": "763f25b39349a0c9182da7d2397d1fb1b2f4d895a9c99c53d77b0afd58d54df1",
58
+ "test_model.py": "74a87872a3b190243cb95949969e8296bbfb59f0be84ad5f5cbd3bbbcb6dac4f"
59
+ },
60
+ "source_sha256": {
61
+ "train.csv": "b06e26ac675513959a63135f11b94ea7786ed02da65db93a5650d8838cbc664b",
62
+ "test.csv": "d12d6e3bc4c3103966ae786dc435913c0c563dfa328f5a3646d0e62cfeeb474d",
63
+ "categories.json": "53261da888122daf2d120d925458631d9619e15d82e56052e7a42e535ce32b63",
64
+ "LICENSE-CC-BY-4.0": "7e7170e3cebf88a9f60c7b8421418323c09304da1af4d5e90f4da1dc1c8a2661"
65
+ },
66
+ "one_training_run": true,
67
+ "scope": "one fit with float/int8 and raw/calibrated representations; prior benchmark knowledge disclosed"
68
+ }
run-001/calibration.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "selected_epoch": 28,
3
+ "selected_temperature": 0.75,
4
+ "validation_n": 1005,
5
+ "temperature_grid": [
6
+ {
7
+ "temperature": 0.5,
8
+ "validation_nll": 0.49316803587787944
9
+ },
10
+ {
11
+ "temperature": 0.75,
12
+ "validation_nll": 0.4198558133840975
13
+ },
14
+ {
15
+ "temperature": 1,
16
+ "validation_nll": 0.4422937451785744
17
+ },
18
+ {
19
+ "temperature": 1.25,
20
+ "validation_nll": 0.5248604773636097
21
+ },
22
+ {
23
+ "temperature": 1.5,
24
+ "validation_nll": 0.6528486956011165
25
+ },
26
+ {
27
+ "temperature": 2,
28
+ "validation_nll": 0.9905426083912591
29
+ },
30
+ {
31
+ "temperature": 3,
32
+ "validation_nll": 1.6893520049704513
33
+ }
34
+ ],
35
+ "quantized_validation_nll_at_inherited_temperature": 0.4200873743488531,
36
+ "scope": "grid selected only on validation float model; int8 inherited same T, no new fit"
37
+ }
run-001/initial-statistics.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "parameter_sha256": "1e32ba55e2006034a90a88f1fbc2af65eb5696a1338623e9684739d8ad577e8f",
3
+ "parameters": 267213,
4
+ "validation_uncalibrated_nll": 4.342896175229632,
5
+ "scope": "initial untrained diagnostic, not eligible for epoch selection"
6
+ }
run-001/model-float64.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fcfb60826d8d251b9b2e9f42765e3157e06e7292f0107151e99a4fcf3737d8d1
3
+ size 2048184
run-001/model-int8.json ADDED
The diff for this file is too large to render. See raw diff
 
run-001/trace.json ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "epoch": 1,
4
+ "batch_steps_so_far": 71,
5
+ "examples_fit_this_epoch": 8998,
6
+ "train_online_cross_entropy": 3.514578702047467,
7
+ "train_epoch_end_nll": 2.1299134584627466,
8
+ "validation_nll": 2.2440583115080206,
9
+ "selected_at_this_point": true,
10
+ "elapsed_seconds": 0.5189902922138572
11
+ },
12
+ {
13
+ "epoch": 2,
14
+ "batch_steps_so_far": 142,
15
+ "examples_fit_this_epoch": 8998,
16
+ "train_online_cross_entropy": 1.4277316590355977,
17
+ "train_epoch_end_nll": 0.9097463137518327,
18
+ "validation_nll": 1.069864202856657,
19
+ "selected_at_this_point": true,
20
+ "elapsed_seconds": 1.0181404170580208
21
+ },
22
+ {
23
+ "epoch": 3,
24
+ "batch_steps_so_far": 213,
25
+ "examples_fit_this_epoch": 8998,
26
+ "train_online_cross_entropy": 0.7523437906297294,
27
+ "train_epoch_end_nll": 0.5683117098627366,
28
+ "validation_nll": 0.7706515538530406,
29
+ "selected_at_this_point": true,
30
+ "elapsed_seconds": 1.5219290424138308
31
+ },
32
+ {
33
+ "epoch": 4,
34
+ "batch_steps_so_far": 284,
35
+ "examples_fit_this_epoch": 8998,
36
+ "train_online_cross_entropy": 0.5177040677160752,
37
+ "train_epoch_end_nll": 0.41507508117333736,
38
+ "validation_nll": 0.6495711167279027,
39
+ "selected_at_this_point": true,
40
+ "elapsed_seconds": 2.0206663333810866
41
+ },
42
+ {
43
+ "epoch": 5,
44
+ "batch_steps_so_far": 355,
45
+ "examples_fit_this_epoch": 8998,
46
+ "train_online_cross_entropy": 0.4004391850440758,
47
+ "train_epoch_end_nll": 0.3282932028946423,
48
+ "validation_nll": 0.58800679678542,
49
+ "selected_at_this_point": true,
50
+ "elapsed_seconds": 2.5190036674030125
51
+ },
52
+ {
53
+ "epoch": 6,
54
+ "batch_steps_so_far": 426,
55
+ "examples_fit_this_epoch": 8998,
56
+ "train_online_cross_entropy": 0.32696640264274923,
57
+ "train_epoch_end_nll": 0.27045556355416656,
58
+ "validation_nll": 0.5554340641461023,
59
+ "selected_at_this_point": true,
60
+ "elapsed_seconds": 3.015609542373568
61
+ },
62
+ {
63
+ "epoch": 7,
64
+ "batch_steps_so_far": 497,
65
+ "examples_fit_this_epoch": 8998,
66
+ "train_online_cross_entropy": 0.276495516423408,
67
+ "train_epoch_end_nll": 0.2309822271858711,
68
+ "validation_nll": 0.5283765537824954,
69
+ "selected_at_this_point": true,
70
+ "elapsed_seconds": 3.519180958159268
71
+ },
72
+ {
73
+ "epoch": 8,
74
+ "batch_steps_so_far": 568,
75
+ "examples_fit_this_epoch": 8998,
76
+ "train_online_cross_entropy": 0.24018665369320263,
77
+ "train_epoch_end_nll": 0.19969276547969483,
78
+ "validation_nll": 0.5124252531527369,
79
+ "selected_at_this_point": true,
80
+ "elapsed_seconds": 4.021570375189185
81
+ },
82
+ {
83
+ "epoch": 9,
84
+ "batch_steps_so_far": 639,
85
+ "examples_fit_this_epoch": 8998,
86
+ "train_online_cross_entropy": 0.21298740223017185,
87
+ "train_epoch_end_nll": 0.17835482174072778,
88
+ "validation_nll": 0.5016814230681566,
89
+ "selected_at_this_point": true,
90
+ "elapsed_seconds": 4.519548500422388
91
+ },
92
+ {
93
+ "epoch": 10,
94
+ "batch_steps_so_far": 710,
95
+ "examples_fit_this_epoch": 8998,
96
+ "train_online_cross_entropy": 0.191606085350254,
97
+ "train_epoch_end_nll": 0.1596622233970647,
98
+ "validation_nll": 0.49138292737540423,
99
+ "selected_at_this_point": true,
100
+ "elapsed_seconds": 5.020353125408292
101
+ },
102
+ {
103
+ "epoch": 11,
104
+ "batch_steps_so_far": 781,
105
+ "examples_fit_this_epoch": 8998,
106
+ "train_online_cross_entropy": 0.17407690382114632,
107
+ "train_epoch_end_nll": 0.14500047836409277,
108
+ "validation_nll": 0.4830880492905459,
109
+ "selected_at_this_point": true,
110
+ "elapsed_seconds": 5.533821083139628
111
+ },
112
+ {
113
+ "epoch": 12,
114
+ "batch_steps_so_far": 852,
115
+ "examples_fit_this_epoch": 8998,
116
+ "train_online_cross_entropy": 0.16022787854548376,
117
+ "train_epoch_end_nll": 0.1326235711814754,
118
+ "validation_nll": 0.4724188344793758,
119
+ "selected_at_this_point": true,
120
+ "elapsed_seconds": 6.092387792188674
121
+ },
122
+ {
123
+ "epoch": 13,
124
+ "batch_steps_so_far": 923,
125
+ "examples_fit_this_epoch": 8998,
126
+ "train_online_cross_entropy": 0.14876581335221165,
127
+ "train_epoch_end_nll": 0.1235782017898409,
128
+ "validation_nll": 0.4738900329656242,
129
+ "selected_at_this_point": false,
130
+ "elapsed_seconds": 6.599629125092179
131
+ },
132
+ {
133
+ "epoch": 14,
134
+ "batch_steps_so_far": 994,
135
+ "examples_fit_this_epoch": 8998,
136
+ "train_online_cross_entropy": 0.13980059781014115,
137
+ "train_epoch_end_nll": 0.11608045967055053,
138
+ "validation_nll": 0.4711191160097532,
139
+ "selected_at_this_point": true,
140
+ "elapsed_seconds": 7.1194493332877755
141
+ },
142
+ {
143
+ "epoch": 15,
144
+ "batch_steps_so_far": 1065,
145
+ "examples_fit_this_epoch": 8998,
146
+ "train_online_cross_entropy": 0.13268671633285803,
147
+ "train_epoch_end_nll": 0.10884973355844771,
148
+ "validation_nll": 0.4652048479424703,
149
+ "selected_at_this_point": true,
150
+ "elapsed_seconds": 7.638825333211571
151
+ },
152
+ {
153
+ "epoch": 16,
154
+ "batch_steps_so_far": 1136,
155
+ "examples_fit_this_epoch": 8998,
156
+ "train_online_cross_entropy": 0.1243915909692746,
157
+ "train_epoch_end_nll": 0.10411327935813444,
158
+ "validation_nll": 0.4644342861167773,
159
+ "selected_at_this_point": true,
160
+ "elapsed_seconds": 8.139266083016992
161
+ },
162
+ {
163
+ "epoch": 17,
164
+ "batch_steps_so_far": 1207,
165
+ "examples_fit_this_epoch": 8998,
166
+ "train_online_cross_entropy": 0.11943055414896693,
167
+ "train_epoch_end_nll": 0.09811011808563887,
168
+ "validation_nll": 0.4663727094944208,
169
+ "selected_at_this_point": false,
170
+ "elapsed_seconds": 8.599611875135452
171
+ },
172
+ {
173
+ "epoch": 18,
174
+ "batch_steps_so_far": 1278,
175
+ "examples_fit_this_epoch": 8998,
176
+ "train_online_cross_entropy": 0.11490649725510978,
177
+ "train_epoch_end_nll": 0.09429081558776996,
178
+ "validation_nll": 0.4619632416282607,
179
+ "selected_at_this_point": true,
180
+ "elapsed_seconds": 9.102239958010614
181
+ },
182
+ {
183
+ "epoch": 19,
184
+ "batch_steps_so_far": 1349,
185
+ "examples_fit_this_epoch": 8998,
186
+ "train_online_cross_entropy": 0.10996233090466821,
187
+ "train_epoch_end_nll": 0.09031945675132147,
188
+ "validation_nll": 0.4588480076079372,
189
+ "selected_at_this_point": true,
190
+ "elapsed_seconds": 9.603592917323112
191
+ },
192
+ {
193
+ "epoch": 20,
194
+ "batch_steps_so_far": 1420,
195
+ "examples_fit_this_epoch": 8998,
196
+ "train_online_cross_entropy": 0.1074862461336937,
197
+ "train_epoch_end_nll": 0.08605126452538867,
198
+ "validation_nll": 0.45339053146496167,
199
+ "selected_at_this_point": true,
200
+ "elapsed_seconds": 10.102855625096709
201
+ },
202
+ {
203
+ "epoch": 21,
204
+ "batch_steps_so_far": 1491,
205
+ "examples_fit_this_epoch": 8998,
206
+ "train_online_cross_entropy": 0.10230910778220413,
207
+ "train_epoch_end_nll": 0.0850068386573114,
208
+ "validation_nll": 0.45590172159788017,
209
+ "selected_at_this_point": false,
210
+ "elapsed_seconds": 10.564609458204359
211
+ },
212
+ {
213
+ "epoch": 22,
214
+ "batch_steps_so_far": 1562,
215
+ "examples_fit_this_epoch": 8998,
216
+ "train_online_cross_entropy": 0.100133367011985,
217
+ "train_epoch_end_nll": 0.0813685233234657,
218
+ "validation_nll": 0.4496875622813153,
219
+ "selected_at_this_point": true,
220
+ "elapsed_seconds": 11.064011916983873
221
+ },
222
+ {
223
+ "epoch": 23,
224
+ "batch_steps_so_far": 1633,
225
+ "examples_fit_this_epoch": 8998,
226
+ "train_online_cross_entropy": 0.09819578462686654,
227
+ "train_epoch_end_nll": 0.07889121157814989,
228
+ "validation_nll": 0.447471391268139,
229
+ "selected_at_this_point": true,
230
+ "elapsed_seconds": 11.563824250362813
231
+ },
232
+ {
233
+ "epoch": 24,
234
+ "batch_steps_so_far": 1704,
235
+ "examples_fit_this_epoch": 8998,
236
+ "train_online_cross_entropy": 0.09532394412202995,
237
+ "train_epoch_end_nll": 0.07749321187560944,
238
+ "validation_nll": 0.44785504027535594,
239
+ "selected_at_this_point": false,
240
+ "elapsed_seconds": 12.024684083182365
241
+ },
242
+ {
243
+ "epoch": 25,
244
+ "batch_steps_so_far": 1775,
245
+ "examples_fit_this_epoch": 8998,
246
+ "train_online_cross_entropy": 0.09330674329026896,
247
+ "train_epoch_end_nll": 0.07673316239348185,
248
+ "validation_nll": 0.4489560227794945,
249
+ "selected_at_this_point": false,
250
+ "elapsed_seconds": 12.488518500234932
251
+ },
252
+ {
253
+ "epoch": 26,
254
+ "batch_steps_so_far": 1846,
255
+ "examples_fit_this_epoch": 8998,
256
+ "train_online_cross_entropy": 0.0909377071371088,
257
+ "train_epoch_end_nll": 0.07339606031812031,
258
+ "validation_nll": 0.4523353770114581,
259
+ "selected_at_this_point": false,
260
+ "elapsed_seconds": 12.954314000438899
261
+ },
262
+ {
263
+ "epoch": 27,
264
+ "batch_steps_so_far": 1917,
265
+ "examples_fit_this_epoch": 8998,
266
+ "train_online_cross_entropy": 0.08898957638773888,
267
+ "train_epoch_end_nll": 0.0720078274568215,
268
+ "validation_nll": 0.4436812954583973,
269
+ "selected_at_this_point": true,
270
+ "elapsed_seconds": 13.454848458059132
271
+ },
272
+ {
273
+ "epoch": 28,
274
+ "batch_steps_so_far": 1988,
275
+ "examples_fit_this_epoch": 8998,
276
+ "train_online_cross_entropy": 0.08746392252096467,
277
+ "train_epoch_end_nll": 0.06960192799180602,
278
+ "validation_nll": 0.4422937451785744,
279
+ "selected_at_this_point": true,
280
+ "elapsed_seconds": 13.953503375407308
281
+ },
282
+ {
283
+ "epoch": 29,
284
+ "batch_steps_so_far": 2059,
285
+ "examples_fit_this_epoch": 8998,
286
+ "train_online_cross_entropy": 0.08655399200854046,
287
+ "train_epoch_end_nll": 0.0693505536343723,
288
+ "validation_nll": 0.44703005289002706,
289
+ "selected_at_this_point": false,
290
+ "elapsed_seconds": 14.41528108343482
291
+ },
292
+ {
293
+ "epoch": 30,
294
+ "batch_steps_so_far": 2130,
295
+ "examples_fit_this_epoch": 8998,
296
+ "train_online_cross_entropy": 0.08628019818883026,
297
+ "train_epoch_end_nll": 0.06746457678992626,
298
+ "validation_nll": 0.4488387768688932,
299
+ "selected_at_this_point": false,
300
+ "elapsed_seconds": 14.873163875192404
301
+ }
302
+ ]
run-001/validation-logits.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e203e9aedfdbf5083891a40f689411d85a57dd2bf1ec0fff585a6b5b6e0ed666
3
+ size 1204048
style.css CHANGED
@@ -1,28 +1,205 @@
 
 
 
 
 
 
 
 
 
 
1
  body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
5
-
6
  h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
 
1
+ :root {
2
+ color-scheme: light;
3
+ --ink: #26354b;
4
+ --muted: #5a6880;
5
+ --accent: #355f9d;
6
+ --line: #d5dfec;
7
+ }
8
+ * {
9
+ box-sizing: border-box;
10
+ }
11
  body {
12
+ margin: 0;
13
+ color: var(--ink);
14
+ background: #f4f6fb;
15
+ font:
16
+ 16px/1.6 system-ui,
17
+ -apple-system,
18
+ sans-serif;
19
+ }
20
+ main {
21
+ max-width: 1300px;
22
+ margin: auto;
23
+ padding: 48px 32px;
24
+ }
25
+ header {
26
+ max-width: 1000px;
27
+ margin-bottom: 32px;
28
+ }
29
+ .eyebrow {
30
+ font-size: 12px;
31
+ letter-spacing: 0.15em;
32
+ color: var(--accent);
33
+ font-weight: 750;
34
  }
 
35
  h1 {
36
+ font-size: clamp(36px, 4.4vw, 58px);
37
+ line-height: 1.1;
38
+ letter-spacing: -0.04em;
39
+ margin: 14px 0;
40
+ }
41
+ .lede {
42
+ font-size: 22px;
43
+ color: var(--muted);
44
+ }
45
+ .workspace {
46
+ display: grid;
47
+ grid-template-columns: 1fr 1fr;
48
+ gap: 26px;
49
+ }
50
+ section {
51
+ min-width: 0;
52
+ background: white;
53
+ border: 1px solid var(--line);
54
+ border-radius: 10px;
55
+ padding: 26px;
56
+ }
57
+ h2 {
58
+ font-size: 22px;
59
+ margin: 0 0 18px;
60
+ }
61
+ label {
62
+ display: block;
63
+ font-weight: 650;
64
+ margin: 14px 0 8px;
65
+ }
66
+ textarea,
67
+ button,
68
+ input {
69
+ font: inherit;
70
+ }
71
+ textarea {
72
+ width: 100%;
73
+ padding: 14px;
74
+ border: 1px solid #8295af;
75
+ border-radius: 6px;
76
+ color: var(--ink);
77
+ background: white;
78
+ resize: vertical;
79
+ }
80
+ .check {
81
+ font-size: 14px;
82
+ font-weight: 500;
83
+ display: flex;
84
+ gap: 10px;
85
+ align-items: flex-start;
86
+ }
87
+ .check input {
88
+ width: 20px;
89
+ height: 20px;
90
+ flex: 0 0 20px;
91
+ accent-color: var(--accent);
92
+ margin-top: 2px;
93
+ }
94
+ button {
95
+ min-height: 48px;
96
+ background: var(--accent);
97
+ color: white;
98
+ border: 0;
99
+ border-radius: 6px;
100
+ padding: 12px 20px;
101
+ font-weight: 650;
102
+ cursor: pointer;
103
+ margin-top: 12px;
104
+ }
105
+ button:disabled {
106
+ opacity: 0.5;
107
+ cursor: not-allowed;
108
+ }
109
+ .hint,
110
+ footer {
111
+ font-size: 14px;
112
+ color: var(--muted);
113
+ overflow-wrap: anywhere;
114
+ }
115
+ .notice {
116
+ font-size: 14px;
117
+ background: #edf2fa;
118
+ border-left: 4px solid var(--accent);
119
+ padding: 14px;
120
+ }
121
+ .placeholder {
122
+ border: 1px dashed var(--line);
123
+ padding: 28px;
124
+ border-radius: 6px;
125
+ color: var(--muted);
126
+ }
127
+ .prediction {
128
+ font-size: 26px;
129
+ font-weight: 700;
130
+ overflow-wrap: anywhere;
131
+ }
132
+ ol {
133
+ padding-left: 26px;
134
+ }
135
+ li {
136
+ padding: 12px 4px;
137
+ border-bottom: 1px solid var(--line);
138
+ }
139
+ li span {
140
+ overflow-wrap: anywhere;
141
+ }
142
+ li strong {
143
+ display: block;
144
+ color: var(--accent);
145
+ }
146
+ summary {
147
+ padding: 12px 0;
148
+ font-weight: 600;
149
+ cursor: pointer;
150
+ }
151
+ details p {
152
+ font-size: 14px;
153
+ }
154
+ pre {
155
+ white-space: pre-wrap;
156
+ overflow-wrap: anywhere;
157
+ overflow: auto;
158
+ max-height: 320px;
159
+ font:
160
+ 12px/1.6 ui-monospace,
161
+ monospace;
162
+ background: #f4f6fb;
163
+ padding: 12px;
164
+ }
165
+ #downloads a {
166
+ display: inline-block;
167
+ min-height: 48px;
168
+ padding: 10px 14px;
169
+ border: 1px solid var(--line);
170
+ border-radius: 6px;
171
+ color: var(--accent);
172
+ }
173
+ #error {
174
+ background: #fff0e9;
175
+ color: #8b3821;
176
+ padding: 14px;
177
+ border-left: 4px solid #a94c2f;
178
+ }
179
+ .facts {
180
+ margin-top: 26px;
181
+ }
182
+ footer {
183
+ margin-top: 28px;
184
+ }
185
+ a {
186
+ color: var(--accent);
187
+ }
188
+ :focus-visible {
189
+ outline: 3px solid #b77a18;
190
+ outline-offset: 3px;
191
+ }
192
+ [hidden] {
193
+ display: none !important;
194
+ }
195
+ @media (max-width: 900px) {
196
+ main {
197
+ padding: 28px 18px;
198
+ }
199
+ .workspace {
200
+ grid-template-columns: minmax(0, 1fr);
201
+ }
202
+ section {
203
+ padding: 20px;
204
+ }
205
  }
test_inference.mjs ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import {
4
+ parseModel,
5
+ predict,
6
+ features,
7
+ fnv,
8
+ normalized,
9
+ } from "./inference.mjs";
10
+ const raw = fs.readFileSync(
11
+ new URL("./run-001/model-int8.json", import.meta.url),
12
+ "utf8",
13
+ ),
14
+ model = parseModel(raw);
15
+ assert.equal(fnv("hello"), 0x4f9f2cab);
16
+ assert.equal(normalized(" Cafe\u0301\u0085 NOTE "), "café note");
17
+ assert.ok(features("😀").ids.length > 0);
18
+ for (const text of [
19
+ "Where is my card?",
20
+ "中文😀",
21
+ "<script>alert(1)</script>",
22
+ "x".repeat(2048),
23
+ ]) {
24
+ const a = predict(model, text, true),
25
+ b = predict(model, text, false);
26
+ assert.equal(a.probabilities.length, 77);
27
+ assert.ok(Math.abs(a.probabilities.reduce((a, b) => a + b, 0) - 1) < 1e-12);
28
+ assert.equal(a.predicted_label_id, b.predicted_label_id);
29
+ }
30
+ for (const input of ["", " ", "x".repeat(2049), "\ud800"])
31
+ assert.throws(() => predict(model, input));
32
+ for (const edit of [
33
+ (m) => (m.dimensions.classes = 76),
34
+ (m) => (m.labels[1] = m.labels[0]),
35
+ (m) => (m.embedding_scales[0] = -1),
36
+ (m) => (m.output_bias[0] = "bad"),
37
+ (m) => (m.embedding_q_base64 = "a"),
38
+ (m) => (m.extra = true),
39
+ ]) {
40
+ const m = JSON.parse(raw);
41
+ edit(m);
42
+ assert.throws(() => parseModel(JSON.stringify(m)));
43
+ }
44
+ console.log(
45
+ JSON.stringify({
46
+ status: "PASS",
47
+ known_classes: 77,
48
+ input_limit_utf16: 2048,
49
+ calibration_preserves_argmax: true,
50
+ malformed_models_rejected: 6,
51
+ }),
52
+ );
test_model.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math, unittest
2
+ from copy import deepcopy
3
+ import numpy as np
4
+ from model import (
5
+ initialize,
6
+ features,
7
+ fnv,
8
+ normalized,
9
+ batch_loss_grad,
10
+ one_forward,
11
+ probabilities,
12
+ nll,
13
+ Adam,
14
+ portable,
15
+ decode_portable,
16
+ )
17
+
18
+
19
+ class ModelTests(unittest.TestCase):
20
+ def test_all_parameter_finite_difference(self):
21
+ p = initialize(8, 3, 2, seed=9, std=0.2)
22
+ xs = [
23
+ (np.array([1, 3, 5]), np.array([0.2, 0.5, 0.7])),
24
+ (np.array([0, 3]), np.array([0.8, 0.6])),
25
+ ]
26
+ ys = [0, 1]
27
+ l2 = 0.04
28
+ loss, ce, g = batch_loss_grad(xs, ys, p, l2)
29
+ maxerror = 0
30
+ for key in p:
31
+ for index in np.ndindex(p[key].shape):
32
+ old = p[key][index]
33
+ eps = 1e-6
34
+ p[key][index] = old + eps
35
+ plus = batch_loss_grad(xs, ys, p, l2)[0]
36
+ p[key][index] = old - eps
37
+ minus = batch_loss_grad(xs, ys, p, l2)[0]
38
+ p[key][index] = old
39
+ expected = (plus - minus) / (2 * eps)
40
+ maxerror = max(maxerror, abs(expected - g[key][index]))
41
+ self.assertAlmostEqual(expected, g[key][index], delta=2e-8)
42
+ self.assertLess(maxerror, 2e-8)
43
+
44
+ def test_hand_forward_and_uniform(self):
45
+ p = {
46
+ "E": np.array([[0.2, -0.1], [0.6, 0.4]]),
47
+ "W": np.array([[0.2, -0.3], [-0.5, 0.1]]),
48
+ "bh": np.array([0.1, 0.2]),
49
+ "bo": np.array([0.3, -0.2]),
50
+ }
51
+ h, z = one_forward((np.array([0, 1]), np.array([0.6, 0.8])), p)
52
+ a = math.tanh(0.6 * 0.2 + 0.8 * 0.6 + 0.1)
53
+ b = math.tanh(0.6 * -0.1 + 0.8 * 0.4 + 0.2)
54
+ np.testing.assert_allclose(
55
+ z, [a * 0.2 - b * 0.5 + 0.3, a * -0.3 + b * 0.1 - 0.2], atol=1e-15
56
+ )
57
+ self.assertAlmostEqual(
58
+ float(nll(np.zeros((1, 77)), np.array([0]))[0]), math.log(77)
59
+ )
60
+ np.testing.assert_allclose(probabilities(np.array([10000.0, 9999.0])).sum(), 1)
61
+
62
+ def test_adam_scalar(self):
63
+ p = {"x": np.array([2.0, -3.0])}
64
+ g = {"x": np.array([0.4, -0.2])}
65
+ a = Adam(p, lr=0.003)
66
+ a.update(p, g)
67
+ np.testing.assert_allclose(
68
+ p["x"],
69
+ np.array([2.0, -3.0])
70
+ - 0.003 * np.array([0.4, -0.2]) / (np.abs([0.4, -0.2]) + 1e-8),
71
+ atol=1e-15,
72
+ )
73
+ self.assertEqual(a.step, 1)
74
+
75
+ def test_features_unicode_and_limits(self):
76
+ self.assertEqual(fnv("hello"), 0x4F9F2CAB)
77
+ self.assertEqual(normalized(" Cafe\u0301\u0085 NOTE "), "café note")
78
+ ids, v = features("😀a")
79
+ self.assertAlmostEqual(float(v @ v), 1)
80
+ self.assertEqual(len(ids), len(set(ids)))
81
+ for s in ["", " ", chr(0xD800), "x" * 2049]:
82
+ with self.assertRaises(ValueError):
83
+ features(s)
84
+
85
+ def test_zero_feature_vector(self):
86
+ p = initialize(8, 3, 2)
87
+ h, z = one_forward((np.array([], dtype=np.int64), np.array([])), p)
88
+ np.testing.assert_array_equal(z, np.zeros(2))
89
+
90
+ def test_quantization_shape_error_bounds(self):
91
+ p = initialize(8, 3, 2, seed=19)
92
+ m = portable(p, ["a", "b"], 1.25)
93
+ q = decode_portable(m)
94
+ for i, scale in enumerate(m["embedding_scales"]):
95
+ self.assertLessEqual(
96
+ float(np.max(np.abs(q["E"][i] - p["E"][i]))), scale * 0.50000001
97
+ )
98
+ for j, scale in enumerate(m["output_scales"]):
99
+ self.assertLessEqual(
100
+ float(np.max(np.abs(q["W"][:, j] - p["W"][:, j]))), scale * 0.50000001
101
+ )
102
+ m["embedding_scales"][0] = -1
103
+ with self.assertRaises(ValueError):
104
+ decode_portable(m)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ unittest.main(verbosity=2)
train.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Freeze original-train membership, fit once, select on validation, freeze test inputs."""
2
+
3
+ import argparse
4
+ from collections import Counter
5
+ import hashlib, json, math, platform, time
6
+ from pathlib import Path
7
+ import numpy as np
8
+ from model import (
9
+ CONFIG,
10
+ PARAMETERS,
11
+ Adam,
12
+ features,
13
+ file_sha,
14
+ initialize,
15
+ load_csv,
16
+ logits_for,
17
+ nll,
18
+ normalized,
19
+ batch_loss_grad,
20
+ portable,
21
+ decode_portable,
22
+ )
23
+
24
+
25
+ def write(path, value):
26
+ path.write_text(
27
+ json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + "\n"
28
+ )
29
+
30
+
31
+ def param_digest(p):
32
+ h = hashlib.sha256()
33
+ for k in PARAMETERS:
34
+ h.update(k.encode())
35
+ h.update(p[k].astype("<f8").tobytes())
36
+ return h.hexdigest()
37
+
38
+
39
+ def train(data, out):
40
+ root = Path(__file__).resolve().parent
41
+ if out.exists():
42
+ raise ValueError("A new output directory is required.")
43
+ old = json.loads((root / "PROTOCOL-FREEZE.json").read_text())
44
+ for name, digest in old["sha256"].items():
45
+ if file_sha(root / name) != digest:
46
+ raise ValueError("Frozen protocol/source changed: " + name)
47
+ source = json.loads((data / "SOURCE.json").read_text())
48
+ files = source["source_origin"]["files"]
49
+ for name, info in files.items():
50
+ if file_sha(data / name) != info["sha256"]:
51
+ raise ValueError("Original source bytes changed: " + name)
52
+ labels = json.loads((data / "categories.json").read_text())
53
+ assert len(labels) == 77 and len(set(labels)) == 77
54
+ rows = load_csv(data / "train.csv", labels)
55
+ assert len(rows) == 10003
56
+ lookup = {l: i for i, l in enumerate(labels)}
57
+ ys = np.array([lookup[r["category"]] for r in rows])
58
+ allx = [features(r["text"]) for r in rows]
59
+ keys = [hashlib.sha256(normalized(r["text"]).encode()).hexdigest() for r in rows]
60
+ valids = [i for i, k in enumerate(keys) if int(k, 16) % 10 == 0]
61
+ validset = set(valids)
62
+ trainids = [i for i in range(len(rows)) if i not in validset]
63
+ traincounts = Counter(int(ys[i]) for i in trainids)
64
+ valcounts = Counter(int(ys[i]) for i in valids)
65
+ if len(traincounts) != 77 or not valids:
66
+ raise ValueError(
67
+ "Fixed hash split lacks training class support or validation rows; not resampled."
68
+ )
69
+ assert not {keys[i] for i in trainids} & {keys[i] for i in valids}
70
+ out.mkdir()
71
+ names = [
72
+ "model.py",
73
+ "train.py",
74
+ "CONFIG.json",
75
+ "PROTOCOL.md",
76
+ "PROTOCOL-FREEZE.json",
77
+ "test_model.py",
78
+ ]
79
+ prefit = {
80
+ "phase": "before any gradient update",
81
+ "configuration": CONFIG,
82
+ "source": source,
83
+ "source_sha256": {n: file_sha(data / n) for n in files},
84
+ "implementation_sha256": {n: file_sha(root / n) for n in names},
85
+ "environment": {"python": platform.python_version(), "numpy": np.__version__},
86
+ "labels": labels,
87
+ "train_row_ids": trainids,
88
+ "validation_row_ids": valids,
89
+ "training_class_counts": [traincounts[c] for c in range(77)],
90
+ "validation_class_counts": [valcounts[c] for c in range(77)],
91
+ "normalized_groups": len(set(keys)),
92
+ "training_rows": len(trainids),
93
+ "validation_rows": len(valids),
94
+ "scope": "hash split of observed normalized text, not source-family or IID guarantee; benchmark already known from earlier separate study",
95
+ }
96
+ write(out / "PREFIT.json", prefit)
97
+ print(
98
+ "PREFIT",
99
+ file_sha(out / "PREFIT.json"),
100
+ len(trainids),
101
+ "train",
102
+ len(valids),
103
+ "validation",
104
+ flush=True,
105
+ )
106
+ xs = [allx[i] for i in trainids]
107
+ ty = ys[trainids]
108
+ vx = [allx[i] for i in valids]
109
+ vy = ys[valids]
110
+ p = initialize(
111
+ CONFIG["feature_bins"],
112
+ CONFIG["hidden_size"],
113
+ CONFIG["classes"],
114
+ CONFIG["init_seed"],
115
+ CONFIG["init_std"],
116
+ )
117
+ initial = param_digest(p)
118
+ adam = Adam(
119
+ p, CONFIG["learning_rate"], CONFIG["beta1"], CONFIG["beta2"], CONFIG["epsilon"]
120
+ )
121
+ trace = []
122
+ best = math.inf
123
+ bestepoch = None
124
+ start = time.perf_counter()
125
+ write(
126
+ out / "initial-statistics.json",
127
+ {
128
+ "parameter_sha256": initial,
129
+ "parameters": sum(x.size for x in p.values()),
130
+ "validation_uncalibrated_nll": float(nll(logits_for(vx, p), vy).mean()),
131
+ "scope": "initial untrained diagnostic, not eligible for epoch selection",
132
+ },
133
+ )
134
+ for epoch in range(1, CONFIG["epochs"] + 1):
135
+ order = np.random.default_rng(CONFIG["shuffle_seed_base"] + epoch).permutation(
136
+ len(xs)
137
+ )
138
+ online = 0.0
139
+ seen = 0
140
+ for begin in range(0, len(order), CONFIG["batch_size"]):
141
+ batch = order[begin : begin + CONFIG["batch_size"]]
142
+ loss, ce, g = batch_loss_grad(
143
+ [xs[int(i)] for i in batch], ty[batch], p, CONFIG["l2"]
144
+ )
145
+ adam.update(p, g)
146
+ online += ce * len(batch)
147
+ seen += len(batch)
148
+ tl = logits_for(xs, p)
149
+ vl = logits_for(vx, p)
150
+ train_nll = float(nll(tl, ty).mean())
151
+ val_nll = float(nll(vl, vy).mean())
152
+ if not np.isfinite(train_nll) or not np.isfinite(val_nll):
153
+ raise ValueError("Nonfinite epoch evaluation.")
154
+ selected = val_nll < best - 1e-12
155
+ if selected:
156
+ best = val_nll
157
+ bestepoch = epoch
158
+ np.savez_compressed(out / "model-float64.npz", **p)
159
+ trace.append(
160
+ {
161
+ "epoch": epoch,
162
+ "batch_steps_so_far": adam.step,
163
+ "examples_fit_this_epoch": seen,
164
+ "train_online_cross_entropy": online / seen,
165
+ "train_epoch_end_nll": train_nll,
166
+ "validation_nll": val_nll,
167
+ "selected_at_this_point": selected,
168
+ "elapsed_seconds": time.perf_counter() - start,
169
+ }
170
+ )
171
+ write(out / "trace.json", trace)
172
+ print(
173
+ f"epoch{epoch:02d} train_nll={train_nll:.6f} val_nll={val_nll:.6f} best={bestepoch}",
174
+ flush=True,
175
+ )
176
+ with np.load(out / "model-float64.npz", allow_pickle=False) as z:
177
+ selected = {k: z[k].copy() for k in PARAMETERS}
178
+ if param_digest(selected) == initial:
179
+ raise ValueError("No parameter change; not a completed fit.")
180
+ vl = logits_for(vx, selected)
181
+ grid = [
182
+ {"temperature": t, "validation_nll": float(nll(vl, vy, t).mean())}
183
+ for t in CONFIG["temperature_grid"]
184
+ ]
185
+ minimum = min(r["validation_nll"] for r in grid)
186
+ eligible = [r for r in grid if r["validation_nll"] <= minimum + 1e-12]
187
+ temperature = min(
188
+ eligible, key=lambda r: (abs(r["temperature"] - 1), r["temperature"])
189
+ )["temperature"]
190
+ exported = portable(selected, labels, temperature)
191
+ write(out / "model-int8.json", exported)
192
+ q = decode_portable(exported)
193
+ qvl = logits_for(vx, q)
194
+ np.savez_compressed(
195
+ out / "validation-logits.npz",
196
+ float_logits=vl,
197
+ int8_logits=qvl,
198
+ gold=vy,
199
+ original_train_row_ids=np.array(valids, dtype=np.int64),
200
+ )
201
+ calibration = {
202
+ "selected_epoch": bestepoch,
203
+ "selected_temperature": temperature,
204
+ "validation_n": len(valids),
205
+ "temperature_grid": grid,
206
+ "quantized_validation_nll_at_inherited_temperature": float(
207
+ nll(qvl, vy, temperature).mean()
208
+ ),
209
+ "scope": "grid selected only on validation float model; int8 inherited same T, no new fit",
210
+ }
211
+ write(out / "calibration.json", calibration)
212
+ required = [
213
+ "PREFIT.json",
214
+ "initial-statistics.json",
215
+ "trace.json",
216
+ "model-float64.npz",
217
+ "model-int8.json",
218
+ "validation-logits.npz",
219
+ "calibration.json",
220
+ ]
221
+ pretest = {
222
+ "phase": "training complete, before this model first scores official test",
223
+ "configuration": CONFIG,
224
+ "selected_epoch": bestepoch,
225
+ "selected_temperature": temperature,
226
+ "initial_parameter_sha256": initial,
227
+ "selected_parameter_sha256": param_digest(selected),
228
+ "fit_steps": adam.step,
229
+ "total_examples_fit": len(trainids) * CONFIG["epochs"],
230
+ "artifact_sha256": {n: file_sha(out / n) for n in required},
231
+ "implementation_sha256": prefit["implementation_sha256"],
232
+ "source_sha256": prefit["source_sha256"],
233
+ "one_training_run": True,
234
+ "scope": "one fit with float/int8 and raw/calibrated representations; prior benchmark knowledge disclosed",
235
+ }
236
+ write(out / "PRETEST.json", pretest)
237
+ print(
238
+ "PRETEST",
239
+ file_sha(out / "PRETEST.json"),
240
+ "selected epoch",
241
+ bestepoch,
242
+ "T",
243
+ temperature,
244
+ flush=True,
245
+ )
246
+
247
+
248
+ if __name__ == "__main__":
249
+ a = argparse.ArgumentParser()
250
+ a.add_argument("--data", type=Path, default=Path("data"))
251
+ a.add_argument("--output", type=Path, required=True)
252
+ x = a.parse_args()
253
+ train(x.data, x.output)
training-curves.png ADDED

Git LFS Details

  • SHA256: f894f54c008148927bc3e86e90fdaafb6033267680fe4b98c7d8c342a0e6ae23
  • Pointer size: 131 Bytes
  • Size of remote file: 120 kB
verify_portable.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare independently executed Node portable inference with CPU representation."""
2
+
3
+ import json, subprocess
4
+ from pathlib import Path
5
+ import numpy as np
6
+ from model import decode_portable, features, logits_for, probabilities
7
+
8
+ r = Path(__file__).parent
9
+ m = json.loads((r / "run-001/model-int8.json").read_text())
10
+ p = decode_portable(m)
11
+ cases = [
12
+ "Where is my card? It has not arrived.",
13
+ "How do I change my PIN?",
14
+ "My cash withdrawal is pending.",
15
+ "I want a refund for a card payment.",
16
+ "Write a poem about the moon.",
17
+ "CAFÉ Cafe\u0301",
18
+ " hello\u0085world\u001c",
19
+ "\ufeffBOM kept",
20
+ "中文😀",
21
+ "A\u2028B",
22
+ "<script>alert(1)</script>",
23
+ "x" * 2048,
24
+ "",
25
+ " ",
26
+ "x" * 2049,
27
+ ]
28
+ rows = json.loads(
29
+ subprocess.run(
30
+ ["node", "predict_driver.mjs"],
31
+ input=json.dumps(cases),
32
+ text=True,
33
+ capture_output=True,
34
+ check=True,
35
+ cwd=r,
36
+ ).stdout
37
+ )
38
+ maximum = 0.0
39
+ valid = 0
40
+ for text, result in zip(cases, rows):
41
+ try:
42
+ ids, values = features(text)
43
+ except ValueError:
44
+ assert "error" in result
45
+ continue
46
+ assert result["features"]["ids"] == ids.tolist()
47
+ np.testing.assert_allclose(
48
+ result["features"]["values"], values, rtol=1e-14, atol=1e-14
49
+ )
50
+ logits = logits_for([(ids, values)], p)[0]
51
+ for key, T in [("raw", 1), ("calibrated", m["temperature"])]:
52
+ actual = result[key]
53
+ np.testing.assert_allclose(actual["logits"], logits, rtol=1e-9, atol=1e-9)
54
+ prob = probabilities(logits, T)
55
+ np.testing.assert_allclose(actual["probabilities"], prob, rtol=1e-9, atol=1e-9)
56
+ maximum = max(
57
+ maximum, float(np.max(np.abs(np.array(actual["probabilities"]) - prob)))
58
+ )
59
+ assert actual["predicted_label_id"] == int(np.argmax(logits))
60
+ valid += 1
61
+ (r / "portable-reference-results.json").write_text(
62
+ json.dumps(
63
+ {
64
+ "status": "PASS",
65
+ "total_vectors": len(cases),
66
+ "valid_vectors": valid,
67
+ "rejected_vectors": len(cases) - valid,
68
+ "max_probability_delta": maximum,
69
+ "scope": "conformance vectors, not language/OOD performance evidence",
70
+ },
71
+ indent=2,
72
+ )
73
+ + "\n"
74
+ )
75
+ print(
76
+ "PortablePASS", valid, "valid,", len(cases) - valid, "rejected,maxPdelta", maximum
77
+ )
verify_results.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent feature/forward, raw-logit metric and Adam-moment verification."""
2
+
3
+ import base64, collections, csv, hashlib, json, math, unicodedata
4
+ from pathlib import Path
5
+ import numpy as np
6
+ from model import Adam
7
+
8
+ r = Path(__file__).resolve().parent
9
+ report = json.loads((r / "evaluation-001/results.json").read_text())
10
+ pre = json.loads((r / "run-001/PRETEST.json").read_text())
11
+ prefit = json.loads((r / "run-001/PREFIT.json").read_text())
12
+ labels = report["labels"]
13
+ with (r / "data/train.csv").open(newline="") as f:
14
+ train = list(csv.DictReader(f))
15
+ with (r / "data/test.csv").open(newline="") as f:
16
+ test = list(csv.DictReader(f))
17
+ norm = lambda text: " ".join(unicodedata.normalize("NFC", text).lower().split())
18
+ expected_val = [
19
+ i
20
+ for i, row in enumerate(train)
21
+ if int(hashlib.sha256(norm(row["text"]).encode()).hexdigest(), 16) % 10 == 0
22
+ ]
23
+ assert expected_val == prefit["validation_row_ids"]
24
+ assert sorted(prefit["train_row_ids"] + expected_val) == list(range(10003))
25
+ assert not set(prefit["train_row_ids"]) & set(expected_val)
26
+ trace = json.loads((r / "run-001/trace.json").read_text())
27
+ assert (
28
+ len(trace) == 30
29
+ and pre["selected_epoch"] == min(trace, key=lambda x: x["validation_nll"])["epoch"]
30
+ )
31
+ assert pre["total_examples_fit"] == 30 * 8998 and pre["fit_steps"] == 30 * math.ceil(
32
+ 8998 / 128
33
+ )
34
+ with np.load(r / "run-001/model-float64.npz", allow_pickle=False) as z:
35
+ fp = {k: z[k] for k in z.files}
36
+ portable = json.loads((r / "run-001/model-int8.json").read_text())
37
+ D, H, C = 4096, 64, 77
38
+ qe = np.frombuffer(
39
+ base64.b64decode(portable["embedding_q_base64"]), dtype=np.int8
40
+ ).reshape(D, H)
41
+ qw = np.frombuffer(
42
+ base64.b64decode(portable["output_q_base64"]), dtype=np.int8
43
+ ).reshape(H, C)
44
+ se = np.array(portable["embedding_scales"])
45
+ sw = np.array(portable["output_scales"])
46
+ qp = {
47
+ "E": qe * se[:, None],
48
+ "W": qw * sw[None, :],
49
+ "bh": np.array(portable["hidden_bias"]),
50
+ "bo": np.array(portable["output_bias"]),
51
+ }
52
+ assert np.all(np.abs(qp["E"] - fp["E"]) <= se[:, None] * 0.500000001)
53
+ assert np.all(np.abs(qp["W"] - fp["W"]) <= sw[None, :] * 0.500000001)
54
+ with np.load(r / "evaluation-001/test-logits.npz", allow_pickle=False) as z:
55
+ fl = z["float_logits"]
56
+ ql = z["int8_logits"]
57
+ gold = z["gold"]
58
+ subset = z["nonoverlap_row_ids"]
59
+ lookup = {l: i for i, l in enumerate(labels)}
60
+ assert gold.tolist() == [lookup[row["category"]] for row in test]
61
+
62
+
63
+ def feature_counts(text):
64
+ value = "^" + norm(text) + "$"
65
+ counter = collections.Counter()
66
+ for n in [3, 4, 5]:
67
+ for pos in range(len(value) - n + 1):
68
+ h = 2166136261
69
+ for byte in value[pos : pos + n].encode():
70
+ h = ((h ^ byte) * 16777619) & 0xFFFFFFFF
71
+ counter[h % 4096] += 1
72
+ divisor = math.sqrt(sum(x * x for x in counter.values()))
73
+ return {k: v / divisor for k, v in sorted(counter.items())} if divisor else {}
74
+
75
+
76
+ for i in [0, 1, 39, 40, 123, 554, 976, 1474, 2000, 3000, 3079]:
77
+ x = feature_counts(test[i]["text"])
78
+ for p, saved in [(fp, fl), (qp, ql)]:
79
+ hidden = [
80
+ math.tanh(
81
+ math.fsum(v * float(p["E"][j, k]) for j, v in x.items())
82
+ + float(p["bh"][k])
83
+ )
84
+ for k in range(H)
85
+ ]
86
+ out = [
87
+ math.fsum(hidden[k] * float(p["W"][k, c]) for k in range(H))
88
+ + float(p["bo"][c])
89
+ for c in range(C)
90
+ ]
91
+ np.testing.assert_allclose(out, saved[i], rtol=1e-10, atol=1e-10)
92
+ # Closed-form moment sums, independent of the implementation's recurrence.
93
+ p = {"v": np.array([1.5])}
94
+ adam = Adam(p)
95
+ gradients = []
96
+ expected = 1.5
97
+ for t in range(1, 21):
98
+ g = math.sin(t) * 0.3
99
+ gradients.append(g)
100
+ m = 0.1 * math.fsum(0.9 ** (t - j) * x for j, x in enumerate(gradients, 1))
101
+ v = 0.001 * math.fsum(0.999 ** (t - j) * x * x for j, x in enumerate(gradients, 1))
102
+ expected -= 0.003 * (m / (1 - 0.9**t)) / (math.sqrt(v / (1 - 0.999**t)) + 1e-8)
103
+ adam.update(p, {"v": np.array([g])})
104
+ assert math.isclose(float(p["v"][0]), expected, abs_tol=1e-12)
105
+ checked = 0
106
+ for mode in report["modes"]:
107
+ logits = fl if mode["representation"] == "float64" else ql
108
+ T = mode["temperature"]
109
+ calculated = []
110
+ with (r / "evaluation-001" / mode["row_file"]).open() as f:
111
+ rows = list(csv.DictReader(f))
112
+ for i, (z, row, y) in enumerate(zip(logits, rows, gold)):
113
+ pred = max(range(C), key=lambda c: (float(z[c]), -c))
114
+ a = [float(v) / T for v in z]
115
+ m = max(a)
116
+ ex = [math.exp(v - m) for v in a]
117
+ total = math.fsum(ex)
118
+ prob = [v / total for v in ex]
119
+ loss = m + math.log(total) - a[int(y)]
120
+ brier = math.fsum((v - int(c == y)) ** 2 for c, v in enumerate(prob))
121
+ assert int(row["test_row_id"]) == i and int(row["predicted_label_id"]) == pred
122
+ assert math.isclose(float(row["nll"]), loss, abs_tol=1e-11)
123
+ assert math.isclose(float(row["brier"]), brier, abs_tol=1e-11)
124
+ assert math.isclose(float(row["confidence"]), prob[pred], abs_tol=1e-12)
125
+ assert math.isclose(float(row["p_gold"]), prob[int(y)], abs_tol=1e-12)
126
+ calculated.append((int(y), pred, prob[pred], loss, brier))
127
+ checked += 1
128
+ for name, indices in [("official", range(3080)), ("nonoverlap", subset)]:
129
+ chosen = [calculated[int(i)] for i in indices]
130
+ stats = mode[name]
131
+ n = len(chosen)
132
+ cm = collections.Counter((y, p) for y, p, conf, loss, brier in chosen)
133
+ assert stats["n"] == n
134
+ assert stats["correct"] == sum(y == p for y, p, conf, loss, brier in chosen)
135
+ f1 = []
136
+ for c in range(C):
137
+ actual = sum(n for (y, p), n in cm.items() if y == c)
138
+ predicted = sum(n for (y, p), n in cm.items() if p == c)
139
+ value = 2 * cm[c, c] / (actual + predicted) if actual + predicted else 0
140
+ f1.append(value)
141
+ assert stats["per_class"][c]["support"] == actual
142
+ assert math.isclose(value, stats["per_class"][c]["f1"], abs_tol=1e-12)
143
+ assert math.isclose(sum(f1) / C, stats["macro_f1"], abs_tol=1e-12)
144
+ assert math.isclose(sum(x[3] for x in chosen) / n, stats["nll"], abs_tol=1e-12)
145
+ assert math.isclose(
146
+ sum(x[4] for x in chosen) / n, stats["brier"], abs_tol=1e-12
147
+ )
148
+ ece = 0
149
+ for b in range(10):
150
+ bucket = [x for x in chosen if min(9, int(x[2] * 10)) == b]
151
+ assert len(bucket) == stats["ece_bins"][b]["n"]
152
+ if bucket:
153
+ ece += (
154
+ len(bucket)
155
+ / n
156
+ * abs(
157
+ sum(x[2] for x in bucket) / len(bucket)
158
+ - sum(x[0] == x[1] for x in bucket) / len(bucket)
159
+ )
160
+ )
161
+ else:
162
+ assert (
163
+ stats["ece_bins"][b]["accuracy"] is None
164
+ and stats["ece_bins"][b]["mean_confidence"] is None
165
+ )
166
+ assert math.isclose(ece, stats["ece10"], abs_tol=1e-12)
167
+ assert (
168
+ report["quantization_disagreement_test_row_ids"]
169
+ == np.flatnonzero(np.argmax(fl, axis=1) != np.argmax(ql, axis=1)).tolist()
170
+ )
171
+ print(
172
+ json.dumps(
173
+ {
174
+ "status": "PASS",
175
+ "independent_test_prediction_metric_rows": checked,
176
+ "float_and_int8_forward_rows": 22,
177
+ "Adam_closed_form_steps": 20,
178
+ "both_subset_metrics": True,
179
+ "quant_disagreements_retained": report["quantization_disagreement_count"],
180
+ }
181
+ )
182
+ )