@ai-ecoverse/kev.js 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +171 -0
- package/dist/api.d.ts +97 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +166 -0
- package/dist/api.js.map +1 -0
- package/dist/encode.d.ts +42 -0
- package/dist/encode.d.ts.map +1 -0
- package/dist/encode.js +39 -0
- package/dist/encode.js.map +1 -0
- package/dist/head.d.ts +20 -0
- package/dist/head.d.ts.map +1 -0
- package/dist/head.js +66 -0
- package/dist/head.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/load.d.ts +33 -0
- package/dist/load.d.ts.map +1 -0
- package/dist/load.js +118 -0
- package/dist/load.js.map +1 -0
- package/dist/model.d.ts +99 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +179 -0
- package/dist/model.js.map +1 -0
- package/package.json +41 -0
package/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 2026 Jared Palmer
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# @ai-ecoverse/kev.js
|
|
2
|
+
|
|
3
|
+
[Kev](https://github.com/jaredpalmer/kev) decision models running in the browser on WebGPU (or WASM), with the same
|
|
4
|
+
TypeSafe System One request and response shapes as `kev.serve`. No server: the model, tokenizer and pointer head
|
|
5
|
+
run in a Web Worker.
|
|
6
|
+
|
|
7
|
+
**[Homepage and live demo](https://ai-ecoverse.github.io/kev.js/)** · **[Weights](https://huggingface.co/ai-ecoverse/kev.js)** · `npm install @ai-ecoverse/kev.js onnxruntime-web`
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import * as ort from "onnxruntime-web/webgpu";
|
|
13
|
+
import { loadKev } from "@ai-ecoverse/kev.js";
|
|
14
|
+
|
|
15
|
+
const kev = await loadKev("https://huggingface.co/ai-ecoverse/kev.js/resolve/main/kev-0.8b", { ort, variant: "q8f32" });
|
|
16
|
+
const res = await kev.systemOne({
|
|
17
|
+
state: "I was charged twice. Please fix this ASAP.",
|
|
18
|
+
questions: {
|
|
19
|
+
billing: { type: "noul", instructions: "Is this ticket about billing?" },
|
|
20
|
+
urgency: { type: "score", instructions: "How urgent is this ticket?", criteria: ["can wait", "this week", "today"] },
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
// Kev-0.8B (kev-0.8b@2256796):
|
|
24
|
+
res.answers.billing.noul; // 1.0 probability of yes, rounded to 2 places like kev.serve
|
|
25
|
+
res.answers.urgency.score; // 1.77 expected level: mostly "today"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Results
|
|
29
|
+
|
|
30
|
+
Measured in Chrome on an Apple M4 Max (WebGPU on Metal), against the fp32 PyTorch model (`kev.evaluate.load`) at the
|
|
31
|
+
same commit. Each fp32 ONNX export matches PyTorch to 1e-4 or better, so the 300-record comparisons use it as the
|
|
32
|
+
reference. The 300 records are held-out transfer-v4 development data (sources Kev was not trained on).
|
|
33
|
+
|
|
34
|
+
| Model (pinned checkpoint) | Download | Accuracy, browser / reference | Brier, browser / reference | Mean / max \|Δp\| (300 records) | Answers changed | 3-question request |
|
|
35
|
+
|---|---|---|---|---|---|---|
|
|
36
|
+
| Kev-0.8B `q8f32` (`kev-0.8b@2256796`) | 822 MB | 0.660 / 0.657 | 0.475 / 0.472 | 0.0063 / 0.085 | 3 / 300 | 108 ms |
|
|
37
|
+
| Kev-0.8B `q8` (int8, fp16 activations) | 788 MB | 0.663 / 0.657 | 0.476 / 0.472 | 0.0073 / 0.087 | 4 / 300 | 115 ms |
|
|
38
|
+
| Kev-4B `q8f32` (`kev-4b@4bc64c6`) | 4.7 GB | 0.773 / 0.773 | 0.324 / 0.324 | 0.0028 / 0.075 | 0 / 300 | 360 ms |
|
|
39
|
+
| Kev-9B `q8f32` (`kev-9b@442e597`) | 8.8 GB | 0.800 / 0.800 | 0.318 / 0.318 | 0.0033 / 0.160 | 0 / 300 | 570 ms |
|
|
40
|
+
|
|
41
|
+
Kev's own PyTorch server takes 329 ms (Kev-0.8B), 779 ms (Kev-4B) and about 2 s (Kev-9B) for a comparable request
|
|
42
|
+
on an M5 with MPS, which has no fast DeltaNet kernels. Kev-9B needs a GPU with roughly 9 GB free for its weights,
|
|
43
|
+
and some browsers cap one origin's Cache Storage below that; the loader then runs uncached and downloads again next
|
|
44
|
+
time. The WASM (CPU) fallback is roughly 5× slower than WebGPU. The largest
|
|
45
|
+
deviations come from near-ties, where the reference itself is split close to 50/50.
|
|
46
|
+
|
|
47
|
+
`q8f32` (int8 weights, fp32 activations) is the default everywhere. int4 is not usable: at 0.8B, round-to-nearest,
|
|
48
|
+
k-quant, block size 16, and int8 for the linear-attention layers all moved probabilities by 0.24–0.78 and flipped
|
|
49
|
+
1–8 of 49 answers, and at 4B int4 moved them by 0.31–0.37 with 3 of 29 flipped. For a model whose output is a
|
|
50
|
+
calibrated probability that is disqualifying. `export/build.sh` lists the variants that were tried.
|
|
51
|
+
|
|
52
|
+
### Checkpoint revisions
|
|
53
|
+
|
|
54
|
+
Kev's checkpoints are republished under the same Hub ids (all three were updated on 2026-09-21), so everything
|
|
55
|
+
here is pinned to a commit. `kev_web_export.pin` resolves `jaredpalmer/kev-4b` to `jaredpalmer/kev-4b@<sha>`. The
|
|
56
|
+
merge, the fixtures and the reference sets record it, and `package.py` refuses to combine fixtures and weights
|
|
57
|
+
from different commits. Each bundle's `manifest.json` names its revision (`run`), and its files live under
|
|
58
|
+
`r-<sha>/`. Publishing a new checkpoint therefore never overwrites a file an older manifest points at: the switch is
|
|
59
|
+
the single commit that replaces `manifest.json`, and browsers key their cache by that revision.
|
|
60
|
+
|
|
61
|
+
## How It Works
|
|
62
|
+
|
|
63
|
+
Kev is a Qwen3.5 base, a rank-16 LoRA and a small pointer head. The head scores each option's `</opt>` hidden state
|
|
64
|
+
against the question's `<decide>` hidden state. Nothing is generated, so one forward pass is the whole job.
|
|
65
|
+
|
|
66
|
+
Qwen3.5 mixes Gated DeltaNet (recurrent) layers with full attention, so Kev serves hybrid models in rows. The state
|
|
67
|
+
runs once, and each question runs as a continuation of the state's cache
|
|
68
|
+
(`kev.model._branch_rows_from_prefix`). That maps directly onto an ordinary exported decoder with a KV cache,
|
|
69
|
+
with no custom attention mask:
|
|
70
|
+
|
|
71
|
+
1. **Merge** (`kev_web_export.merge`): fold the LoRA into the base in fp32 (exact), write a
|
|
72
|
+
`Qwen3_5ForConditionalGeneration` checkpoint, the head (`head.safetensors`) and `kev.json`.
|
|
73
|
+
2. **Build** (`export/build.sh`): the onnxruntime-genai model builder with `exclude_lm_head=true` outputs
|
|
74
|
+
`hidden_states` after the final norm. It emits `LinearAttention`, `CausalConvWithState`,
|
|
75
|
+
`LinearAttentionGate`, `GatedRMSNorm`, `MRotaryEmbedding` and `GroupQueryAttention`, all of which have WebGPU
|
|
76
|
+
kernels in onnxruntime-web 1.30 (`onnxruntime-web/webgpu`, the native WebGPU EP). 667 of 675 nodes run on
|
|
77
|
+
WebGPU; the other 8 are shape ops.
|
|
78
|
+
3. **Post-process** (`kev_web_export.postprocess`): the builder can only quantize embeddings to int4. The
|
|
79
|
+
embedding table (0.5 GB fp16 for 0.8B, 2.5 GB fp32 for 4B) becomes int8 with one scale per row, using plain
|
|
80
|
+
`Gather`/`Cast`/`Mul`. The rotary caches are trimmed from 262k positions to 8,192, which is `kev.serve`'s limit.
|
|
81
|
+
External weights are split into files of at most 32 MB (`--shard-mb`): proxies and CDNs cap response bodies (bb
|
|
82
|
+
connect cuts one at 34.5 MiB), a failed file is cheap to retry, and browsers cap a single buffer near 2 GB. A
|
|
83
|
+
single tensor larger than that keeps its own file — Kev-9B's MLP matrices are 50 MB each — which Hugging Face
|
|
84
|
+
serves fine but a capped proxy would not. An
|
|
85
|
+
embedding table is one tensor of hundreds of MB and an ONNX initializer cannot span files, so it is stored as
|
|
86
|
+
column slices that are gathered separately and concatenated — bit-identical, and every file stays small.
|
|
87
|
+
4. **Package** (`kev_web_export.package`): `manifest.json` (I/O names, empty-cache shapes, parity), tokenizer,
|
|
88
|
+
head and one directory per variant.
|
|
89
|
+
|
|
90
|
+
The runtime (`src/`) is a port of `kev/api.py` and `kev/model.py`. `render`, `to_record`, `to_answers`,
|
|
91
|
+
`encode` and the delimiter escaping are reproduced exactly, including Python's `str()` formatting (`True`,
|
|
92
|
+
`1e-07`). On WebGPU the state's recurrent, conv and KV caches stay on the GPU (`gpu-buffer`) and are reused by
|
|
93
|
+
every question, and by later requests with the same state (LRU of 4, as in `kev.serve`).
|
|
94
|
+
|
|
95
|
+
## Quick Start
|
|
96
|
+
|
|
97
|
+
Using the library needs nothing but `npm install @ai-ecoverse/kev.js onnxruntime-web` and the published weights.
|
|
98
|
+
Building the weights yourself needs Python 3.12 with [uv](https://docs.astral.sh/uv/) and a lot of disk (Kev-0.8B
|
|
99
|
+
about 20 GB, Kev-4B about 45 GB, Kev-9B about 85 GB at peak):
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
git clone --recursive https://github.com/ai-ecoverse/kev.js && cd kev.js
|
|
103
|
+
cd export && uv sync
|
|
104
|
+
./build_model.sh kev-0.8b # or kev-4b, kev-9b; optionally a pinned run: jaredpalmer/kev-4b@<sha>
|
|
105
|
+
cd .. && npm install && npm run dev # http://127.0.0.1:5173, serving public/models
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`build_model.sh` pins the checkpoint, merges the LoRA in fp32, builds the int8 WebGPU graph, shards it, builds the
|
|
109
|
+
fp32 reference, writes the PyTorch fixtures and the 300-record reference set, measures parity and packages the bundle
|
|
110
|
+
into `public/models/<name>`. On macOS the onnxruntime-genai builder can abort with `recursive_mutex lock failed`
|
|
111
|
+
after it has written everything, so `build.sh` checks for `genai_config.json` instead of the exit code.
|
|
112
|
+
|
|
113
|
+
### Publishing
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
HF_TOKEN=... uv run python -m kev_web_export.upload_hf --repo ai-ecoverse/kev.js # weights + model card
|
|
117
|
+
npm run build:lib # dist/ for npm (tsc)
|
|
118
|
+
npm run build:demo # homepage (PAGES_BASE=/kev.js/ in CI)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`.github/workflows` builds the homepage to GitHub Pages on every push to `main`, runs the tests that need no
|
|
122
|
+
weights, and publishes the npm package from a `v*` tag with trusted publishing (OIDC, no token). The demo loads
|
|
123
|
+
weights from Hugging Face unless `VITE_MODEL_BASE` or `?models=<url>` says otherwise; `npm run dev` serves
|
|
124
|
+
`public/models` instead. GitHub Pages cannot set COOP/COEP headers, so `crossOriginIsolated` is false there and the
|
|
125
|
+
WASM fallback runs single-threaded; WebGPU is unaffected.
|
|
126
|
+
|
|
127
|
+
`kev.systemOne(req, { onAnswer })` reports each question as it finishes, so a UI can fill answers in as they land.
|
|
128
|
+
`kev.systemOneSeparate()` answers each question in its own pass. `kev.probs(record)` returns raw probabilities.
|
|
129
|
+
Weight files are cached in Cache Storage (`kev-web-v1`). In the demo page, `window.kev.systemOne(...)` works from
|
|
130
|
+
the console, and `?verbose` logs where onnxruntime placed each node.
|
|
131
|
+
|
|
132
|
+
## Testing
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
npm test # rendering, tokenization and encoding parity; full runtime on onnxruntime-node
|
|
136
|
+
KEV_VARIANTS=fp32 npm test # just the exact variant
|
|
137
|
+
KEV_MODEL=kev-4b npm test # fixtures/kev-4b.json against public/models/kev-4b
|
|
138
|
+
cd export && uv run python -m kev_web_export.parity --model build/kev-0.8b/web-q8f32/model.onnx \
|
|
139
|
+
--head build/kev-0.8b/head.safetensors --fixtures ../fixtures/kev-0.8b.json
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`scripts/cdp.mjs` drives a page in a Chrome started with `--remote-debugging-port=9222`, for checking the demo in a
|
|
143
|
+
real browser: `node scripts/cdp.mjs '<expression>'` evaluates in the tab (`MATCH=` picks it by URL), and
|
|
144
|
+
`node scripts/cdp.mjs --shot out.png` screenshots it.
|
|
145
|
+
|
|
146
|
+
- `fixtures/kev-0.8b.json`: 43 records (3 hand-written, including structured state and delimiter injection, plus
|
|
147
|
+
40 from transfer-v4 dev) with the rendered record, Kev's token encoding and the PyTorch probabilities.
|
|
148
|
+
Regenerate with `kev_web_export.fixtures`.
|
|
149
|
+
- `fixtures/kev-4b.json`: the same 3 hand-written records plus 20 dev records, for Kev-4B.
|
|
150
|
+
- `fixtures/kev-*-transfer-v4-dev300.json`: 300 labelled records with fp32 reference probabilities
|
|
151
|
+
(`kev_web_export.evalset`), used for the browser accuracy and Brier comparisons above.
|
|
152
|
+
|
|
153
|
+
## Limitations
|
|
154
|
+
|
|
155
|
+
- JSON parsing loses two things Kev's Python server keeps. `1.0` arrives as `1` and is rendered `1`, where Python
|
|
156
|
+
renders `1.0`. Object keys that look like integers (`"10"`, `"2"`) are iterated in numeric order, which can
|
|
157
|
+
reorder Choice options with numeric names.
|
|
158
|
+
- The first load downloads 822 MB for Kev-0.8B, or 4.7 GB for Kev-4B, and the files stay in Cache Storage. Serve
|
|
159
|
+
them from a fast origin: over a tunnel at ~1.2 MB/s, Kev-0.8B takes 11 minutes. More parallel requests do not
|
|
160
|
+
help on a bandwidth-limited link (measured: 1.2 MB/s with one stream, 0.75 MB/s across six), so the loader
|
|
161
|
+
fetches 2 files at a time.
|
|
162
|
+
Kev-4B needs a GPU with enough memory for about 4.5 GB of weights. Only Chrome was tested; Safari and Firefox
|
|
163
|
+
WebGPU are untested.
|
|
164
|
+
- Kev-9B is not packaged. At int8 it would be about 10 GB.
|
|
165
|
+
- onnxruntime-node 1.30 on Node 24+ reads 0 bytes from `Float16Array` float16 tensors, so the tests hide
|
|
166
|
+
`Float16Array` (`test/no-float16.ts`). Browsers are not affected.
|
|
167
|
+
- Requests run one at a time per model instance.
|
|
168
|
+
|
|
169
|
+
## License
|
|
170
|
+
|
|
171
|
+
Apache-2.0, like Kev and the Qwen3.5 weights. Kev itself is vendored as a pinned submodule (`vendor/kev`).
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
export type JSONContent = string | number | boolean | null | JSONContent[] | {
|
|
2
|
+
[key: string]: JSONContent;
|
|
3
|
+
};
|
|
4
|
+
export interface NoulQuestion {
|
|
5
|
+
type: "noul";
|
|
6
|
+
instructions: JSONContent;
|
|
7
|
+
criteria?: {
|
|
8
|
+
true?: JSONContent;
|
|
9
|
+
false?: JSONContent;
|
|
10
|
+
} | null;
|
|
11
|
+
}
|
|
12
|
+
export interface ChoiceQuestion {
|
|
13
|
+
type: "choice";
|
|
14
|
+
instructions: JSONContent;
|
|
15
|
+
criteria: Record<string, JSONContent>;
|
|
16
|
+
}
|
|
17
|
+
export interface ScoreQuestion {
|
|
18
|
+
type: "score";
|
|
19
|
+
instructions: JSONContent;
|
|
20
|
+
criteria: JSONContent[];
|
|
21
|
+
}
|
|
22
|
+
export type Question = NoulQuestion | ChoiceQuestion | ScoreQuestion;
|
|
23
|
+
export interface SystemOneRequest {
|
|
24
|
+
state: JSONContent;
|
|
25
|
+
model?: string;
|
|
26
|
+
questions: Record<string, Question>;
|
|
27
|
+
}
|
|
28
|
+
export interface NoulAnswer {
|
|
29
|
+
type: "noul";
|
|
30
|
+
noul: number;
|
|
31
|
+
}
|
|
32
|
+
export interface ChoiceAnswer {
|
|
33
|
+
type: "choice";
|
|
34
|
+
choice: string;
|
|
35
|
+
confidence: number;
|
|
36
|
+
probabilities: Record<string, number>;
|
|
37
|
+
}
|
|
38
|
+
export interface ScoreAnswer {
|
|
39
|
+
type: "score";
|
|
40
|
+
score: number;
|
|
41
|
+
legend: Record<string, string>;
|
|
42
|
+
probabilities: Record<string, number>;
|
|
43
|
+
confidence: number;
|
|
44
|
+
}
|
|
45
|
+
export type Answer = NoulAnswer | ChoiceAnswer | ScoreAnswer;
|
|
46
|
+
export interface SystemOneResponse {
|
|
47
|
+
model: string;
|
|
48
|
+
answers: Record<string, Answer>;
|
|
49
|
+
usage: {
|
|
50
|
+
input_tokens: number;
|
|
51
|
+
output_tokens: number;
|
|
52
|
+
};
|
|
53
|
+
latency_ms: number;
|
|
54
|
+
}
|
|
55
|
+
/** Internal record consumed by encode(): rendered state and, per question, instruction + option texts. */
|
|
56
|
+
export interface DecisionRecord {
|
|
57
|
+
state: string;
|
|
58
|
+
questions: {
|
|
59
|
+
instr: string;
|
|
60
|
+
options: string[];
|
|
61
|
+
}[];
|
|
62
|
+
}
|
|
63
|
+
export type QuestionMeta = {
|
|
64
|
+
id: string;
|
|
65
|
+
type: "noul";
|
|
66
|
+
} | {
|
|
67
|
+
id: string;
|
|
68
|
+
type: "choice";
|
|
69
|
+
keys: string[];
|
|
70
|
+
} | {
|
|
71
|
+
id: string;
|
|
72
|
+
type: "score";
|
|
73
|
+
legend: Record<string, string>;
|
|
74
|
+
};
|
|
75
|
+
export declare const MAX_OPTIONS = 255;
|
|
76
|
+
export declare class ValidationError extends Error {
|
|
77
|
+
status: number;
|
|
78
|
+
}
|
|
79
|
+
export declare function validate(req: unknown): SystemOneRequest;
|
|
80
|
+
/** Python's repr(float): shortest round-trip digits, exponent form below 1e-4 and from 1e16. */
|
|
81
|
+
export declare function pyFloat(x: number): string;
|
|
82
|
+
/** Flatten str | object | array into the text the model sees. Field names are kept as labels. */
|
|
83
|
+
export declare function render(v: JSONContent | undefined, indent?: number): string;
|
|
84
|
+
export declare function optionText(name: string, desc: JSONContent | undefined): string;
|
|
85
|
+
export declare function toRecord(req: SystemOneRequest): {
|
|
86
|
+
record: DecisionRecord;
|
|
87
|
+
meta: QuestionMeta[];
|
|
88
|
+
};
|
|
89
|
+
export declare function choiceConfidence(p: number[]): number;
|
|
90
|
+
/** Approximation of TypeSafe's 'distance from the modal level' statistic: 1 - E|level - mode| / (L - 1). */
|
|
91
|
+
export declare function scoreConfidence(p: number[]): number;
|
|
92
|
+
/** Python round(x, 2): nearest, exact ties to even. */
|
|
93
|
+
export declare function r2(x: number): number;
|
|
94
|
+
export declare function toAnswers(probs: number[][], meta: QuestionMeta[]): Record<string, Answer>;
|
|
95
|
+
/** Python json.dumps (default separators, ensure_ascii). Every number in an answer is a Python float. */
|
|
96
|
+
export declare function pyJsonDumps(v: unknown): string;
|
|
97
|
+
//# sourceMappingURL=api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"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"}
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// TypeSafe System One request/response shapes mapped onto Kev's pointer primitive (port of kev/api.py).
|
|
2
|
+
//
|
|
3
|
+
// Noul -> 2 options [no, yes]; answer = p(yes)
|
|
4
|
+
// Choice -> options 'name' or 'name: desc'; answer = argmax, probabilities by name, confidence
|
|
5
|
+
// Score -> options = ordered level descriptions; answer = expected level, legend, probabilities by index
|
|
6
|
+
//
|
|
7
|
+
// Kev renders JSON content with Python's str(), so the text the model sees depends on Python formatting rules
|
|
8
|
+
// (True/False, float repr). Those are reproduced here so browser and server feed the model identical text.
|
|
9
|
+
export const MAX_OPTIONS = 255;
|
|
10
|
+
export class ValidationError extends Error {
|
|
11
|
+
status = 422;
|
|
12
|
+
}
|
|
13
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
14
|
+
export function validate(req) {
|
|
15
|
+
if (!isObject(req))
|
|
16
|
+
throw new ValidationError("request must be an object");
|
|
17
|
+
if (!("state" in req))
|
|
18
|
+
throw new ValidationError("state is required");
|
|
19
|
+
if (!isObject(req.questions) || Object.keys(req.questions).length < 1)
|
|
20
|
+
throw new ValidationError("questions must have at least 1 entry");
|
|
21
|
+
for (const [id, q] of Object.entries(req.questions)) {
|
|
22
|
+
if (!isObject(q))
|
|
23
|
+
throw new ValidationError(`questions.${id} must be an object`);
|
|
24
|
+
if (!("instructions" in q))
|
|
25
|
+
throw new ValidationError(`questions.${id}.instructions is required`);
|
|
26
|
+
if (q.type === "noul") {
|
|
27
|
+
if (q.criteria != null && !isObject(q.criteria))
|
|
28
|
+
throw new ValidationError(`questions.${id}.criteria must be an object`);
|
|
29
|
+
}
|
|
30
|
+
else if (q.type === "choice") {
|
|
31
|
+
if (!isObject(q.criteria))
|
|
32
|
+
throw new ValidationError(`questions.${id}.criteria must be an object`);
|
|
33
|
+
const n = Object.keys(q.criteria).length;
|
|
34
|
+
if (n < 1 || n > MAX_OPTIONS)
|
|
35
|
+
throw new ValidationError(`criteria must have 1..${MAX_OPTIONS} options`);
|
|
36
|
+
}
|
|
37
|
+
else if (q.type === "score") {
|
|
38
|
+
if (!Array.isArray(q.criteria) || q.criteria.length < 2 || q.criteria.length > MAX_OPTIONS)
|
|
39
|
+
throw new ValidationError(`questions.${id}.criteria must be a list of 2..${MAX_OPTIONS} levels`);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
throw new ValidationError(`questions.${id}.type must be noul, choice or score`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return req;
|
|
46
|
+
}
|
|
47
|
+
/** Python's repr(float): shortest round-trip digits, exponent form below 1e-4 and from 1e16. */
|
|
48
|
+
export function pyFloat(x) {
|
|
49
|
+
if (Number.isNaN(x))
|
|
50
|
+
return "nan";
|
|
51
|
+
if (!Number.isFinite(x))
|
|
52
|
+
return x > 0 ? "inf" : "-inf";
|
|
53
|
+
if (x === 0)
|
|
54
|
+
return Object.is(x, -0) ? "-0.0" : "0.0";
|
|
55
|
+
const sign = x < 0 ? "-" : "";
|
|
56
|
+
const [mant, expS] = Math.abs(x).toExponential().split("e");
|
|
57
|
+
const exp = parseInt(expS, 10);
|
|
58
|
+
const digits = mant.replace(".", "");
|
|
59
|
+
if (exp < -4 || exp >= 16) {
|
|
60
|
+
const m = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
|
|
61
|
+
return `${sign}${m}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`;
|
|
62
|
+
}
|
|
63
|
+
if (exp >= 0)
|
|
64
|
+
return `${sign}${digits.slice(0, exp + 1).padEnd(exp + 1, "0")}.${digits.slice(exp + 1) || "0"}`;
|
|
65
|
+
return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
|
|
66
|
+
}
|
|
67
|
+
/** Python's str() for JSON scalars. JSON cannot tell 1 from 1.0 once parsed, so integral numbers print as ints. */
|
|
68
|
+
function pyStr(v) {
|
|
69
|
+
if (typeof v === "boolean")
|
|
70
|
+
return v ? "True" : "False";
|
|
71
|
+
if (typeof v === "number")
|
|
72
|
+
return Number.isInteger(v) && Math.abs(v) < 1e21 ? String(v) : pyFloat(v);
|
|
73
|
+
return v;
|
|
74
|
+
}
|
|
75
|
+
/** Flatten str | object | array into the text the model sees. Field names are kept as labels. */
|
|
76
|
+
export function render(v, indent = 0) {
|
|
77
|
+
const pad = " ".repeat(indent);
|
|
78
|
+
if (v === null || v === undefined)
|
|
79
|
+
return "";
|
|
80
|
+
if (typeof v !== "object")
|
|
81
|
+
return pyStr(v);
|
|
82
|
+
if (Array.isArray(v))
|
|
83
|
+
return v.map((x) => `${pad}- ${render(x, indent + 1).trimStart()}`).join("\n");
|
|
84
|
+
return Object.entries(v)
|
|
85
|
+
.map(([k, x]) => (typeof x === "object" && x !== null ? `${pad}${k}:\n${render(x, indent + 1)}` : `${pad}${k}: ${render(x)}`))
|
|
86
|
+
.join("\n");
|
|
87
|
+
}
|
|
88
|
+
export function optionText(name, desc) {
|
|
89
|
+
return desc === null || desc === undefined || desc === "" ? name : `${name}: ${render(desc)}`;
|
|
90
|
+
}
|
|
91
|
+
export function toRecord(req) {
|
|
92
|
+
const questions = [];
|
|
93
|
+
const meta = [];
|
|
94
|
+
for (const [id, q] of Object.entries(req.questions)) {
|
|
95
|
+
const instr = render(q.instructions);
|
|
96
|
+
let options;
|
|
97
|
+
if (q.type === "noul") {
|
|
98
|
+
const c = q.criteria ?? {};
|
|
99
|
+
options = [optionText("no", c.false), optionText("yes", c.true)];
|
|
100
|
+
meta.push({ id, type: "noul" });
|
|
101
|
+
}
|
|
102
|
+
else if (q.type === "choice") {
|
|
103
|
+
options = Object.entries(q.criteria).map(([k, v]) => optionText(k, v));
|
|
104
|
+
meta.push({ id, type: "choice", keys: Object.keys(q.criteria) });
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
options = q.criteria.map((x) => render(x));
|
|
108
|
+
meta.push({ id, type: "score", legend: Object.fromEntries(q.criteria.map((x, i) => [String(i), render(x)])) });
|
|
109
|
+
}
|
|
110
|
+
questions.push({ instr, options });
|
|
111
|
+
}
|
|
112
|
+
return { record: { state: render(req.state), questions }, meta };
|
|
113
|
+
}
|
|
114
|
+
const argmax = (p) => p.reduce((best, v, i) => (v > p[best] ? i : best), 0);
|
|
115
|
+
export function choiceConfidence(p) {
|
|
116
|
+
const K = p.length;
|
|
117
|
+
return K === 1 ? 1 : (Math.max(...p) - 1 / K) / (1 - 1 / K);
|
|
118
|
+
}
|
|
119
|
+
/** Approximation of TypeSafe's 'distance from the modal level' statistic: 1 - E|level - mode| / (L - 1). */
|
|
120
|
+
export function scoreConfidence(p) {
|
|
121
|
+
const mode = argmax(p);
|
|
122
|
+
return 1 - p.reduce((s, pi, i) => s + pi * Math.abs(i - mode), 0) / (p.length - 1);
|
|
123
|
+
}
|
|
124
|
+
/** Python round(x, 2): nearest, exact ties to even. */
|
|
125
|
+
export function r2(x) {
|
|
126
|
+
const t = x * 100;
|
|
127
|
+
if (Number.isInteger(t * 2) && !Number.isInteger(t)) {
|
|
128
|
+
const f = Math.floor(t);
|
|
129
|
+
return (f % 2 === 0 ? f : f + 1) / 100;
|
|
130
|
+
}
|
|
131
|
+
return Number(x.toFixed(2));
|
|
132
|
+
}
|
|
133
|
+
export function toAnswers(probs, meta) {
|
|
134
|
+
const out = {};
|
|
135
|
+
probs.forEach((p, i) => {
|
|
136
|
+
const m = meta[i];
|
|
137
|
+
if (m.type === "noul")
|
|
138
|
+
out[m.id] = { type: "noul", noul: r2(p[1]) };
|
|
139
|
+
else if (m.type === "choice")
|
|
140
|
+
out[m.id] = {
|
|
141
|
+
type: "choice", choice: m.keys[argmax(p)], confidence: r2(choiceConfidence(p)),
|
|
142
|
+
probabilities: Object.fromEntries(m.keys.map((k, j) => [k, r2(p[j])])),
|
|
143
|
+
};
|
|
144
|
+
else
|
|
145
|
+
out[m.id] = {
|
|
146
|
+
type: "score", score: r2(p.reduce((s, pi, j) => s + j * pi, 0)), legend: m.legend,
|
|
147
|
+
probabilities: Object.fromEntries(p.map((v, j) => [String(j), r2(v)])), confidence: r2(scoreConfidence(p)),
|
|
148
|
+
};
|
|
149
|
+
});
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
/** Python json.dumps (default separators, ensure_ascii). Every number in an answer is a Python float. */
|
|
153
|
+
export function pyJsonDumps(v) {
|
|
154
|
+
if (v === null || v === undefined)
|
|
155
|
+
return "null";
|
|
156
|
+
if (typeof v === "number")
|
|
157
|
+
return pyFloat(v);
|
|
158
|
+
if (typeof v === "boolean")
|
|
159
|
+
return v ? "true" : "false";
|
|
160
|
+
if (typeof v === "string")
|
|
161
|
+
return JSON.stringify(v).replace(/[\u0080-]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
162
|
+
if (Array.isArray(v))
|
|
163
|
+
return `[${v.map(pyJsonDumps).join(", ")}]`;
|
|
164
|
+
return `{${Object.entries(v).map(([k, x]) => `${pyJsonDumps(k)}: ${pyJsonDumps(x)}`).join(", ")}}`;
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=api.js.map
|