victorbennett commited on
Commit
4d3d9bc
·
verified ·
1 Parent(s): c852294

add verdin

Browse files
verdin/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 The Verdin Authors
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.
verdin/NOTICE ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Verdin
2
+ Copyright 2026 The Verdin Authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE). The license covers the Verdin source
5
+ code only. It does not cover model weights: converted checkpoints (e.g. Verdin-4B) carry their own license, stated in
6
+ their model card and NOTICE file.
7
+
8
+ -------------------------------------------------------------------------------------------------------------------------
9
+ Portions of this software are derived from the following works, each licensed under the Apache License, Version 2.0:
10
+
11
+ kev (https://github.com/jaredpalmer/kev)
12
+ Copyright 2026 Jared Palmer
13
+ Verdin reproduces kev's request format and rendering (verdin/render.py: JSON-to-text rendering, option texts, date
14
+ facts, question keys, the delimiter/branch token layout and its caps), its answer formatting and confidence formulas
15
+ (verdin/answers.py) and its pointer-head readout, including the mini-jev-lab modifications to kev (schema-first
16
+ rendering, configurable token caps, the trained "unknown" output). The checkpoints Verdin converts are kev runs.
17
+
18
+ Hugging Face Transformers (https://github.com/huggingface/transformers)
19
+ Copyright The HuggingFace Inc. team and the Qwen team, Alibaba Group
20
+ verdin/torch_backend.py ports the reference PyTorch implementation of the chunked gated delta rule
21
+ (torch_chunk_gated_delta_rule) and follows the Qwen3.5 text model's forward semantics (models/qwen3_5).
22
+
23
+ Qwen3.5 (https://huggingface.co/Qwen/Qwen3.5-4B-Base)
24
+ Copyright the Qwen team, Alibaba Group
25
+ The model architecture implemented here; base weights released under the Apache License, Version 2.0.
26
+
27
+ -------------------------------------------------------------------------------------------------------------------------
28
+ Portions of this software are derived from the following work, licensed under the MIT License:
29
+
30
+ mlx-lm (https://github.com/ml-explore/mlx-lm)
31
+ Copyright (c) 2023 Apple Inc.
32
+ verdin/mlx_backend.py adapts the gated delta rule Metal kernels of mlx_lm/models/gated_delta.py (made varlen, with
33
+ the initial state taken by index and the final state optional).
34
+
35
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
36
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
37
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
38
+ persons to whom the Software is furnished to do so, subject to the following conditions:
39
+
40
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
41
+ Software.
42
+
43
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
44
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
45
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
46
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
47
+
48
+ -------------------------------------------------------------------------------------------------------------------------
49
+ Optional runtime dependencies (not distributed with Verdin): PyTorch (BSD-3-Clause), tokenizers (Apache-2.0),
50
+ safetensors (Apache-2.0), flash-linear-attention / fla (MIT), causal-conv1d (BSD-3-Clause), MLX (MIT; the Apple-silicon
51
+ backend), NumPy (BSD-3-Clause).
verdin/README-mac.md ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Verdin on Apple silicon (MLX backend)
2
+
3
+ `verdin/mlx_backend.py` runs Verdin checkpoints on the Mac's GPU through [MLX](https://github.com/ml-explore/mlx). It
4
+ executes the same plans as the torch backend (`engine.py`: prefix states, sweeps, prefix cache, batching, OOM policy),
5
+ reads the same converted checkpoint directory, and serves the same `/v1/systemone` wire format. Only the forward pass is
6
+ MLX.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ uv venv --python 3.12 ~/.venvs/verdin-mlx
12
+ uv pip install --python ~/.venvs/verdin-mlx/bin/python "mlx>=0.32.3" numpy tokenizers
13
+ ```
14
+
15
+ That is the whole runtime: no torch, transformers, mlx-lm or kev. Tested with mlx 0.32.3 on an M5 Max (128 GB,
16
+ macOS 26.5). Conversion (`verdin.convert`) still needs torch; run it on a Linux host (CPU is enough) or in a torch venv on
17
+ the Mac and copy the output directory (8.4 GB for the 4B).
18
+
19
+ ## Serve
20
+
21
+ ```bash
22
+ cd mini-jev-lab
23
+ ~/.venvs/verdin-mlx/bin/python -m verdin.mlx_backend --model ~/models/verdin-4b --host 0.0.0.0 --port 8903
24
+ ```
25
+
26
+ `verdin.mlx_backend`'s entry point is `verdin.server` with the MLX engine plugged in; every `verdin.server` flag works
27
+ (`--max-batch`, `--prefix-cache`, `--prefill-chunk`, `--max-sweep-tokens`, `--dtype`, ...; torch-only kernel flags are
28
+ ignored). Once `verdin/mlx_hook.patch` is merged into `core.py`, plain `python -m verdin.server --model DIR` picks the MLX
29
+ backend by itself on Apple silicon (`--backend auto`; `--backend mlx` forces it).
30
+
31
+ Extra flags of the MLX entry point:
32
+
33
+ | flag | default | meaning |
34
+ |---|---|---|
35
+ | `--attn-dtype` | `auto` | precision of q / K / V inside attention (a state's K/V are cached in it): `auto` = fp32 for states of at most `--attn-fp32-max-state` tokens and bf16 above; `fp32`; `bf16` |
36
+ | `--attn-fp32-max-state` | 4096 | the `auto` threshold. fp32 attention halves the drift from the fp32 model (see Parity); MLX's fused fp32 attention is ~3x slower than bf16, which costs ~35 % of a 7k-token request and nothing measurable below 4k |
37
+ | `--memory-limit-gb` | 0 | `mx.set_memory_limit` (0 = MLX's default, ~1.5 x the recommended working set) |
38
+ | `--cache-limit-gb` | 1 | buffers MLX keeps for reuse after they are freed |
39
+ | `--wired-limit-gb` | 0 | `mx.set_wired_limit` (0 = unchanged) |
40
+
41
+ State-bidirectional checkpoints (`architecture.state_bidir` = B, 10-17): the prefill chunk must be a multiple of B; the
42
+ default below is rounded down to a multiple of B, at least B (8,192 for the DI3C-BIDIR Verdin).
43
+
44
+ Defaults of the shared flags on MLX: `--prefill-chunk 0` = 4,096 state tokens per prefill segment, `--max-sweep-tokens 0` =
45
+ 8,192 tokens per layer pass.
46
+
47
+ Python:
48
+
49
+ ```python
50
+ from verdin.mlx_backend import load_verdin # before the hook is merged
51
+ v = load_verdin("/Users/me/models/verdin-4b") # or Verdin.from_pretrained(path, backend="mlx") after it
52
+ v.decide("The mug arrived broken.", {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}})
53
+ ```
54
+
55
+ ## How it runs on Metal
56
+
57
+ - **Weights**: bf16 as stored, projections fused once at load (`in_proj_qkv|z|b|a`, `q|k|v`, `gate|up`) and
58
+ pre-transposed, so every projection of a sweep is one GEMM over all its tokens. 7.8 GB resident for the 4B.
59
+ - **Precision**: residual stream, norms, gates, RoPE, SiLU and the conv accumulation in fp32; GEMM inputs and outputs in
60
+ bf16 (as on CUDA). The Gated DeltaNet recurrence runs in fp32 on fp32 q/k/v. The pointer head runs in fp32 on the CPU
61
+ stream. MLX computes fp32 GEMMs and fp32 attention as TF32 on GPUs with neural accelerators (M5: 7e-4 relative
62
+ error in a GEMM, 8e-3 in an attention output) unless `MLX_ENABLE_TF32=0`; the backend sets that default so that fp32
63
+ attention and `--dtype fp32` really are fp32 (bf16 GEMMs are unaffected).
64
+ - **Gated DeltaNet**: a varlen Metal kernel (mlx-lm's packed gated-delta kernel, MIT, made varlen): one launch for every
65
+ prefill segment of the sweep (each carries its state's recurrent state in and out) and one for every branch row (each
66
+ starts from its request's state by index; nothing is copied per question).
67
+ - **Causal conv**: one Metal kernel, SiLU fused, reading `[carried tails ; tokens]` by index.
68
+ - **Attention**: `mx.fast.scaled_dot_product_attention` (fused for head_dim 256: no score matrix). Prefill segments use
69
+ MLX's bottom-right-aligned `"causal"` mask over the state's K/V so far (also for the later chunks of a long state;
70
+ state-bidirectional checkpoints: no mask for a one-block segment, (k <= q) | same block for a multi-block one);
71
+ all rows of a request attend `[prefix K/V ; own row]` under one block-diagonal mask (single-row requests use the plain
72
+ causal mask). q / K / V are fp32 for states of up to 4,096 tokens and bf16 above (`--attn-dtype`).
73
+ - **Elementwise chains** are fused with `mx.compile(shapeless=True)`.
74
+ - **Threads**: MLX cannot evaluate a lazy array from another thread, so the engine owns one thread and runs every MLX
75
+ call on it; the server's batcher thread hands batches to it.
76
+
77
+ ## Parity
78
+
79
+ **Verdin-4B as released (state-bidirectional).** Probabilities at T = 1. Verdin MLX runs with its defaults (bf16
80
+ weights; fp32 attention for states up to 4,096 tokens; prefill chunk 8,192 = one attention block). References: Verdin's
81
+ CUDA backend on an RTX 5090 (the engine of the submitted Decision Index run; bf16 as served, fp32 for the long states),
82
+ kev's stored GPU eval rows of this checkpoint (RTX 3090), and MLX in all-fp32 mode (`--dtype fp32`) as an fp32 proxy.
83
+
84
+ | comparison | records / questions | same argmax % (flips) | max abs dp | median |
85
+ |---|---|---|---|---|
86
+ | **Verdin MLX vs Verdin CUDA bf16**, the six suites of table 1 below | 5,777 / 8,129 | **99.74** (21) | 0.129 | 6.6e-05 |
87
+ | Verdin MLX vs kev's GPU rows, same records | 5,777 / 8,129 | 99.63 (30) | 0.245 | 9.2e-05 |
88
+ | (Verdin CUDA bf16 vs kev's GPU rows, same records) | 5,777 / 8,129 | 99.64 (29) | 0.246 | 9.9e-05 |
89
+ | Verdin MLX vs the fp32 proxy, typed-decisions / hard-v1 / score-v1 | 1,469 / 3,821 | 99.63 (14) | 0.065 | 4.0e-04 |
90
+ | (Verdin CUDA bf16 / kev's GPU rows vs the fp32 proxy, same) | 1,469 / 3,821 | 99.76 (9) / 99.48 (20) | 0.165 / 0.195 | 5.4e-04 / 8.2e-04 |
91
+ | **Verdin MLX vs Verdin CUDA fp32**, 48 long states (5k-25k tokens, up to four 8,192-token blocks) | 48 / 79 | **100** (0) | 0.065 | 6.5e-04 |
92
+ | (Verdin CUDA bf16 vs Verdin CUDA fp32, same) | 48 / 79 | 100 (0) | 0.026 | 4.3e-04 |
93
+ | (Verdin MLX `--dtype fp32` vs Verdin CUDA fp32, same: two independent implementations of the block mask) | 48 / 79 | 100 (0) | 0.0028 | 6.2e-05 |
94
+
95
+ Per suite against kev's rows, Verdin MLX agrees 99.93 % (robust-v1), 99.55 % (jevbench-public), 99.35 %
96
+ (typed-decisions), 98.82 % (hard-v1), 99.88 % (score-v1) and 99.93 % (multilingual-v1); accuracy 82.72 % (kev's rows) vs
97
+ 82.65 % (Verdin MLX) overall. typed-decisions and hard-v1 miss the 99.5 % per-suite bar, and so does Verdin's CUDA
98
+ engine on the same records (99.55 % / 98.82 %): the gap is bf16 drift on near-ties, most of it in kev's stored rows.
99
+ Against the fp32 proxy, Verdin MLX is within 0.1 pp of its accuracy on each of the three suites (typed / hard / score:
100
+ fp32 proxy 70.35 / 72.38 / 93.50; Verdin MLX 70.45 / 72.48 / 93.50; kev's rows 70.60 / 72.87 / 93.37). The long states
101
+ exercise multi-block prefill segments (a state's tokens attend within their own 8,192-token block and causally to
102
+ earlier blocks); the CUDA reference is independent code (Verdin's torch backend, checked against transformers with a
103
+ hand-built mask by `verdin/tests/test_bidir.py`). Raw rows and logs: `results/verdin/mlx-bidir/` (run_parity.sh,
104
+ run_parity2.sh; CUDA rows from .204 in `cuda204/`; not in git).
105
+
106
+ **Development checkpoint (causal).**
107
+ Checkpoint: `exp-combo-s-di-4b-s1` converted by `verdin.convert` (bf16, md5 `c7d83115...`). Probabilities at T = 1.
108
+ Verdin runs with its defaults (bf16 weights; fp32 attention for states up to 4,096 tokens, which covers every record of
109
+ table 1). Raw rows and reports: `results/verdin/mlx/` (not in git). Repeated runs are bitwise identical.
110
+
111
+ **1. Against kev's stored GPU eval rows** (`results/eval/minijev-combo-s-di-4b-s1/<suite>/rows.json` on .204): every
112
+ evaluated record of six suites, 5,777 records / 8,129 questions, states up to 4,048 tokens. "old MLX path" =
113
+ `minijev.mlx_kev` (what `minijev.mac_serve_mlx` serves) on the same requests.
114
+
115
+ | suite | records | questions | Verdin same argmax % | accuracy kev / Verdin (pp) | Verdin max abs dp | median | old MLX path same argmax % | max abs dp | median |
116
+ |---|---|---|---|---|---|---|---|---|---|
117
+ | robust-v1 | 2735 | 2735 | 100.00 | 91.33 / 91.33 (+0.00) | 0.084 | 4.8e-06 | 99.85 | 0.261 | 5.9e-06 |
118
+ | jevbench-public | 223 | 223 | 100.00 | 78.48 / 78.48 (+0.00) | 0.096 | 4.4e-05 | 100.00 | 0.105 | 7.2e-05 |
119
+ | typed-decisions | 400 | 2000 | 99.25 | 67.35 / 67.75 (+0.40) | 0.166 | 1.9e-03 | 99.30 | 0.198 | 2.8e-03 |
120
+ | hard-v1 | 669 | 1021 | 98.53 | 63.76 / 64.54 (+0.78) | 0.217 | 1.7e-03 | 98.43 | 0.277 | 2.4e-03 |
121
+ | score-v1.heldout | 400 | 800 | 99.62 | 89.75 / 90.12 (+0.38) | 0.147 | 1.9e-05 | 99.50 | 0.176 | 2.3e-05 |
122
+ | multilingual-v1 | 1350 | 1350 | 99.56 | 78.22 / 78.30 (+0.07) | 0.104 | 5.8e-05 | 99.11 | 0.169 | 7.7e-05 |
123
+ | **all** | 5777 | 8129 | **99.52** (39 flips) | 79.28 / 79.53 (+0.25) | 0.217 | 1.2e-04 | 99.38 (50 flips) | 0.277 | 1.6e-04 |
124
+
125
+ Overall agreement passes 99.5 %; per suite, typed-decisions, hard-v1 and score-v1 miss the 99.5 % / 0.2 pp bars. The
126
+ old MLX path misses them the same way (and multilingual too). Most flips are near-ties in kev's rows (median top-2 margin
127
+ 0.022; 72 % under 0.05), and Verdin's accuracy is higher on every suite where the two differ.
128
+
129
+ **2. Against the fp32 model.** kev's stored rows are not an fp32 computation: kev serves a checkpoint trained with a bf16
130
+ backbone in bf16 with the LoRA unmerged (see `numeric_parity.py`). Two fp32 references settle which side the drift is on:
131
+
132
+ - phase A's exact reference (kev's DecisionModel on the CPU in fp32, LoRA unmerged; 64 records / 124 questions from nine
133
+ suites, 6 states over 4,096 tokens, so two prefill chunks):
134
+
135
+ | vs exact kev fp32 | questions | flips | max abs dp | median |
136
+ |---|---|---|---|---|
137
+ | kev stored GPU rows | 77 | 1 | 0.088 | 4.1e-04 |
138
+ | old MLX path | 124 | 0 | 0.151 | 3.7e-04 |
139
+ | Verdin MLX, `--attn-dtype bf16` | 124 | 1 | 0.054 | 3.5e-04 |
140
+ | **Verdin MLX (default: fp32 attention up to 4,096 state tokens)** | 124 | 0 | 0.054 | 2.3e-04 |
141
+ | Verdin MLX, `--attn-dtype fp32` | 124 | 0 | 0.023 | 2.1e-04 |
142
+ | Verdin MLX, all fp32 (bf16-rounded weights, `--dtype fp32`) | 124 | 0 | 0.025 | 9.8e-05 |
143
+
144
+ The last row equals phase A's torch CPU number for the same bf16-rounded weights (0.0248): the rounding of the weights
145
+ to bf16 is the floor.
146
+ - the fp32 proxy (`--dtype fp32`, every GEMM in fp32) on all of typed-decisions, hard-v1 and score-v1 (1,469 records,
147
+ 3,821 questions), the three suites that miss the bars above:
148
+
149
+ | vs fp32 proxy | flips | same argmax % | max abs dp | median | accuracy typed / hard / score |
150
+ |---|---|---|---|---|---|
151
+ | (fp32 proxy itself) | | | | | 67.55 / 64.35 / 90.12 |
152
+ | kev stored GPU rows | 27 | 99.29 | 0.206 | 9.8e-04 | 67.35 / 63.76 / 89.75 |
153
+ | old MLX path | 21 | 99.45 | 0.262 | 1.2e-03 | 67.65 / 64.54 / 90.00 |
154
+ | Verdin MLX, `--attn-dtype bf16` | 17 | 99.56 | 0.175 | 6.4e-04 | 67.75 / 64.35 / 89.75 |
155
+ | **Verdin MLX (default)** | 12 | 99.69 | 0.121 | 4.9e-04 | 67.75 / 64.54 / 90.12 |
156
+
157
+ Verdin is within 0.2 pp of the fp32 model's accuracy on each suite; kev's GPU rows are 0.2-0.6 pp below it. The
158
+ per-suite misses in table 1 are the reference's own bf16 drift (it disagrees with the fp32 model twice as often as
159
+ Verdin does), not Verdin's.
160
+ - long states (48 records not in table 1: 11 diskills / jevbench states of 5-9k tokens, 3 documents-v1 concatenations
161
+ of ~25k tokens, the 31 hard-v1 records kev's eval caps rejected; 79 questions) against the fp32 proxy: Verdin
162
+ (default: bf16 attention on most of these) 0 flips, max abs dp 0.045, median 2.3e-03; with fp32 attention and prefill
163
+ chunks of 1,024 / 4,096 / 16,384 tokens: 0 flips each, max 0.033 / 0.039 / 0.018; the old MLX path: 1 flip, max
164
+ 0.141, mean abs dp 2.3x Verdin's.
165
+
166
+ **3. Unit level** (`mlx_parity tiny`): on tiny random Qwen3.5 models, MLX in fp32 (CPU and GPU, with the Metal kernels)
167
+ matches Verdin's torch CPU fp32 backend to 1e-4 in a logit across every engine path (batching, chunked prefill,
168
+ multi-sweep plans, query-chunked masks, the prefix cache, duplicate states, the unknown head); the varlen gated-delta
169
+ kernels match the ops recurrence to 2e-7.
170
+
171
+ ## Performance (M5 Max, 128 GB)
172
+
173
+ `python -m verdin.tests.mlx_bench` against `verdin.mlx_backend` (defaults) and against the old path
174
+ (`minijev.mac_serve_mlx`: kev.serve + `minijev.mlx_kev`, same checkpoint, KEV_SCHEMA_FIRST=1, date facts), one server at
175
+ a time, client on the Mac, run back to back with the same protocol (results/verdin/mlx/bench-*-final.json). Latency =
176
+ client wall clock, requests one after another, every state new to the server.
177
+
178
+ | class (state tokens, median) | old MLX path p50 / p95 ms | Verdin p50 / p95 ms |
179
+ |---|---|---|
180
+ | short: 1 question, state < 300 (100) | 70.9 / 83.4 | **42.8 / 52.9** |
181
+ | medium: 2-6 questions, state 400-4,000 (950) | 337.5 / 835 | 338.4 / 1,086 |
182
+ | long: 5,000-7,500 (6,354), within kev.serve's 8,192 caps | 1,319 / 1,576 | 1,349 / 1,636 |
183
+ | xlong: 8,200-24,000 (8,615) | refused (422, kev.serve caps) | 3,792 / 10,141 |
184
+
185
+ | concurrency (short + medium + long mix, 111 requests) | old MLX path req/s (tok/s) | Verdin req/s (tok/s) |
186
+ |---|---|---|
187
+ | 1 | 1.78 (2,655) | 1.93 (2,875) |
188
+ | 4 | 1.93 (2,876) | 1.98 (2,952) |
189
+ | 8 | 1.98 (2,948) | 1.99 (2,966) |
190
+
191
+ - **The Mac is compute bound and power limited.** MLX's bf16 GEMMs reach 51-60 TFLOPS on an M5 Max for a few seconds,
192
+ then ~26 TFLOPS sustained (40 s GEMM loop; macOS `powermode 0`, AC power). A 4B forward costs 7.1 GFLOP per token, so
193
+ sustained throughput tops out near 3.7k tokens/s whatever the engine; both servers sit at ~2.9k in the mix above.
194
+ Cross-request batching (Verdin's dynamic batcher) has little to amortise here: weight reads stop mattering above ~100
195
+ tokens per pass. Numbers move with thermal history: an earlier pair of runs gave the old path 3.06 req/s at
196
+ concurrency 1 and Verdin 1.77 (before the attention change below); every phase of the benchmark starts after 30 s
197
+ idle (`--cooldown`), and the single-request phases reproduced within 2 % across runs.
198
+ - **Where Verdin wins**: short requests (-40 % latency), the 8k+ states the old path refuses, and multi-question
199
+ requests in burst conditions (GPU rested before each request: typed-decisions 5-question requests 158-220 ms vs
200
+ 190-245 ms).
201
+ - **Long states** cost the same as the old path once attention runs in bf16 (the default above 4,096 state tokens).
202
+ With fp32 attention a 7k-token state took ~35 % longer (MLX's fused fp32 attention is ~3x slower than bf16); that
203
+ is why the fp32 default stops at 4,096 tokens.
204
+ - Settings checked under sustained load (interleaved A/B): prefill chunk 1,024 / 2,048 / 4,096 and sweep size
205
+ 2,048 / 4,096 / 8,192 tokens all within noise; the gated-delta kernel's packed layout beats one SIMD-group per value
206
+ row for one 7.7k-token segment (9.1 vs 16.8 ms) and for 64 short rows alike; bf16 instead of fp32 q/k/v into it
207
+ saves ~5 ms per layer at 7.7k tokens (not taken: within noise end to end).
208
+
209
+ ## Memory
210
+
211
+ | | old MLX path | Verdin |
212
+ |---|---|---|
213
+ | weights resident (MLX active memory after load) | | 7.84 GB |
214
+ | process footprint idle (macOS `footprint`, includes Metal buffers) | 8.28 GB | 8.98 GB |
215
+ | peak footprint in the benchmark | 12.0 GB (no request over 8k tokens) | 17.0 GB (incl. 24k-token states, batches up to 32k tokens) |
216
+ | MLX peak, the 5,777-record parity run (batches of 16 requests / 16k tokens) | 14.8 GB | 15.5 GB |
217
+ | MLX peak, 48 long states up to 25k tokens, prefill chunk 1,024 / 4,096 / 16,384 | | 12.2 / 14.2-18.6 / 35.6 GB |
218
+
219
+ Per state token the prefix cache holds 8 attention layers x K and V x 4 heads x 256: 64 KiB in fp32 (states up to
220
+ 4,096 tokens) or 32 KiB in bf16, plus 50 MB of DeltaNet state per state (24 layers x 32 heads x 128 x 128 fp32): a
221
+ 65k-token state is ~2 GiB. `--prefix-cache 4` keeps four states (LRU, states of at least 384 tokens).
222
+ `--memory-limit-gb` caps MLX; an allocation failure is retried request by request and then refused with "too many
223
+ tokens" (the engine's OOM policy, tested with a simulated failure).
224
+
225
+ ## Tests
226
+
227
+ | command | what |
228
+ |---|---|
229
+ | `python -m verdin.tests.mlx_parity tiny` | tiny random models: MLX on the CPU (exact fp32), the GPU in fp32 and bf16, against Verdin's torch CPU fp32 backend, across batching, chunked prefill, multi-sweep plans, query-chunked masks, the prefix cache, duplicate states, the unknown head, the OOM policy; the varlen gated-delta kernels against the ops recurrence. Needs torch (test only). |
230
+ | `python -m verdin.tests.mlx_parity select / verdin / kev / compare / vs` | the 4B parity: against kev's stored GPU eval rows and the old Mac path (`compare`), against any reference such as phase A's exact kev fp32 rows or the `--dtype fp32` proxy (`vs`); see its docstring |
231
+ | `python -m verdin.tests.mlx_bench build / run / table` | the serving benchmark above, for any `/v1/systemone` server |
232
+
233
+ ## Limits and open issues
234
+
235
+ - **Parity bar vs kev's GPU rows**: met overall (99.52 % same argmax, 39 of 8,129) but not per suite on typed-decisions
236
+ (99.25 %, +0.40 pp), hard-v1 (98.53 %, +0.78 pp) and score-v1 (99.62 %, +0.38 pp). The fp32 references show this is
237
+ the stored rows' own bf16 drift (they are 0.2-0.6 pp below the fp32 model; Verdin is within 0.2 pp of it and flips
238
+ half as often). The old MLX path misses the same bars. A fair bar for any bf16 engine is the fp32 model.
239
+ - **Speed**: about equal to the old path on throughput and long states, faster on short requests; the M5 Max's
240
+ sustained power limit, not the engine, sets the ceiling. Medium multi-question requests (1-4k-token states) had a
241
+ higher p95 than the old path in the final run (1,086 vs 835 ms; p50 equal); fp32 attention up to 4,096 tokens is the
242
+ likely cost (`--attn-fp32-max-state 1024` trades it back, untested on parity).
243
+ - **Conversion needs torch** (`verdin.convert`); the Mac checkpoint used here is phase A's conversion on .124 copied
244
+ over (md5 of `model.safetensors` and `head.safetensors` verified against `verdin_config.json`).
245
+ - `import verdin.mlx_backend` sets `MLX_ENABLE_TF32=0` for the process (unless already set). Verdin needs it for fp32
246
+ attention (the default up to 4,096 state tokens) and `--dtype fp32`; it also applies to any other MLX code in the
247
+ same process.
248
+ - `python -m verdin.server` selects MLX only after `verdin/mlx_hook.patch` is merged; until then use
249
+ `python -m verdin.mlx_backend` (same flags).
250
+ - Tested on one machine (M5 Max, 128 GB, mlx 0.32.3). Smaller Macs: 8.4 GB of weights + activations; use
251
+ `--max-sweep-tokens 2048 --prefill-chunk 1024` and `--attn-dtype bf16` to cut the peak (a state-bidirectional
252
+ checkpoint keeps its prefill chunk at a multiple of its block).
verdin/README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Verdin
2
+
3
+ Verdin is an inference engine for **System One decision models**. You send a state (text or JSON) and typed
4
+ questions (choice, noul yes/no, score); you get a probability for every option of every question from one prefill
5
+ pass. Nothing is generated and nothing needs parsing.
6
+
7
+ It runs **Verdin-4B**: Qwen3.5-4B-Base with a LoRA fine-tune merged into the weights and a pointer head that reads the
8
+ option-boundary tokens, trained with [kev](https://github.com/jaredpalmer/kev) in mini-jev-lab. Verdin replaces kev at
9
+ serving time: same request format, same tokens, same numbers, less work per request.
10
+
11
+ ```
12
+ state + questions ──► [<state> schema state] ─┬─ [<q> instr <opt> a </opt> <opt> b </opt> <decide>] ──► a 0.81 b 0.19
13
+ └─ [<q> instr <opt> no </opt> <opt> yes </opt> <decide>] ──► yes 0.07
14
+ ```
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install torch tokenizers safetensors # CPU is enough to run and to test
20
+ pip install flash-linear-attention # CUDA: Gated DeltaNet kernels (fla >= 0.5, Triton)
21
+ pip install causal-conv1d # CUDA, optional: fused causal conv (else a torch path)
22
+ ```
23
+
24
+ Runtime imports: `torch`, `tokenizers`, `safetensors` (and `fla` / `causal_conv1d` on GPU when present). No
25
+ transformers, peft or kev. `verdin.render` needs only `tokenizers`, so other backends can share it.
26
+
27
+ ## Convert a kev run
28
+
29
+ ```bash
30
+ python -m verdin.convert --run runs/exp-combo-s-di-4b-s1 --out runs/verdin-4b-s1 \
31
+ --schema-first 1 --date-facts 1 --max-state 65536 --max-branch 66560 --max-packed 131072
32
+ ```
33
+
34
+ This reads the run (`adapter_model.safetensors`, `adapter_config.json`, `head.pt`) and the base snapshot pinned in
35
+ `head.pt` (from the HF cache, or `--base DIR`). It writes:
36
+
37
+ | file | content |
38
+ |---|---|
39
+ | `model.safetensors` | the text backbone with the LoRA merged in fp32, cast once to bf16 (`--dtype fp32` keeps fp32). Only what the forward reads: no vision tower, MTP head or LM head. 8.4 GB for the 4B. |
40
+ | `head.safetensors` | the pointer head in fp32 (`q`, `k`, and `unk_key` / `unk_bias` if the run trained an unknown output) |
41
+ | `tokenizer.json` | the tokenizer exactly as kev runs it (transformers' backend tokenizer of the base, exported; the run's own copy if transformers is missing) |
42
+ | `verdin_config.json` | architecture, render settings, special tokens, calibrated temperature, unknown-head flag, source run, base revision and md5s, conversion checks |
43
+ | `NOTICE`, `LICENSE.base` | credits; the base model's license |
44
+
45
+ kev never stored the render settings in a run (they were environment variables), so `--schema-first` and
46
+ `--date-facts` are required. Use the values the run was trained and evaluated with (`KEV_SCHEMA_FIRST`,
47
+ `--date-facts`). The caps default to the Decision Index serving config above.
48
+
49
+ Checks run on the CPU: every adapter tensor must be consumed, and every merged weight is probed with random inputs
50
+ (`x W_merged^T` against `x W^T + s (x A^T) B^T`). With `--verify N` (default 3), N probe requests also run through
51
+ Verdin's forward three ways: base weights plus the unmerged LoRA, merged fp32 weights, and the bf16-rounded weights. The
52
+ differences go into `verdin_config.json`. For exp-combo-s-di-4b-s1, merged and unmerged differ by at most 5.7e-6 in a
53
+ logit (4e-7 in a probability). Rounding the merged weights to bf16 costs at most 1.6e-3 in a probability at T = 1.
54
+
55
+ ## Serve
56
+
57
+ ```bash
58
+ python -m verdin.server --model runs/verdin-4b-s1 --host 0.0.0.0 --port 8903
59
+ ```
60
+
61
+ `POST /v1/systemone` and `GET /v1/models` use the TypeSafe wire format that kev.serve and minijev.predictor_server
62
+ speak. The Decision Index http engine and JevBench's typesafe adapter work against Verdin unchanged; both are tested in
63
+ `verdin/tests/test_server.py`.
64
+
65
+ ```json
66
+ POST /v1/systemone (numbers illustrative)
67
+ {"state": {"ticket": "Charged twice for order 1182"},
68
+ "questions": {"team": {"type": "choice", "instructions": "Route it.", "criteria": {"billing": "charges, refunds", "tech": null}},
69
+ "urgent": {"type": "noul", "instructions": "Is it urgent?"},
70
+ "anger": {"type": "score", "instructions": "How angry is the customer?", "criteria": ["calm", "annoyed", "furious"]}}}
71
+
72
+ 200 {"model": "Verdin-4B",
73
+ "answers": {"team": {"type": "choice", "choice": "billing", "probabilities": {"billing": 0.97, "tech": 0.03}, "confidence": 0.94},
74
+ "urgent": {"type": "noul", "noul": 0.31},
75
+ "anger": {"type": "score", "score": 0.88, "probabilities": {"0": 0.27, "1": 0.58, "2": 0.15},
76
+ "legend": {"0": "calm", "1": "annoyed", "2": "furious"}, "confidence": 0.79}},
77
+ "usage": {"input_tokens": 92, "output_tokens": 0}, "latency_ms": 31.2, "compute_ms": 28.9}
78
+ ```
79
+
80
+ Probabilities are full-precision floats at the checkpoint's calibrated temperature (kev's playground server rounded
81
+ them to 2 decimals). A malformed or invalid request gets `422 {"error", "detail"}`. A request over a token cap, or over
82
+ the device's memory, gets 422 with `too many tokens: ...`. The Decision Index counts that marker as an explicit
83
+ "unsupported", not as an error. Requests are never truncated.
84
+
85
+ | flag | default | meaning |
86
+ |---|---|---|
87
+ | `--backend` | `auto` | `cuda`, `cpu`, `mlx` (`auto` picks MLX on Apple silicon; see [README-mac.md](README-mac.md)) |
88
+ | `--dtype` | `auto` | `bf16` / `fp32`; `auto` is the checkpoint's stored dtype |
89
+ | `--max-batch` / `--max-batch-tokens` | 32 / 32768 | dynamic batching: requests waiting while the GPU is busy run together. `--max-batch 1` turns cross-request batching off |
90
+ | `--batch-wait-ms` | 0 | optional collection window before a batch starts |
91
+ | `--prefix-cache` / `--prefix-cache-min-tokens` | 4 / 384 | keep the prefix states of recent states (LRU); a repeated state then pays only for its questions |
92
+ | `--prefill-chunk` / `--max-sweep-tokens` | 8192 / 16384 (CUDA) | long states are prefilled in chunks; tokens per layer pass |
93
+ | `--gdr`, `--branch-gdr`, `--conv`, `--sdpa` | auto, recurrent, auto, auto | kernel choices (fla chunk or fused-recurrent for the branch rows, causal-conv1d or torch, SDPA or its math kernel) |
94
+
95
+ ## Python API
96
+
97
+ ```python
98
+ from verdin import Verdin
99
+
100
+ v = Verdin.from_pretrained("runs/verdin-4b-s1") # CUDA if available, else CPU; dtype from the checkpoint
101
+ v.decide("The mug arrived broken.", {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}})
102
+ # {'damaged': {'type': 'noul', 'noul': 0.98}}
103
+
104
+ v.decide_batch([{"state": s, "questions": qs} for s, qs in work]) # batched; refused items come back as exceptions
105
+ enc = v.encode({"state": s, "questions": qs}) # tokens (verdin.render.Encoded)
106
+ res = v.run([enc])[0] # raw logits per question (temperature 1)
107
+ probs, p_unknown = v.probabilities(enc, res, temperature=1.0)
108
+ ```
109
+
110
+ ## How it runs
111
+
112
+ A request is a state prefix, shared by all its questions, plus one branch row per question. Each row is the same
113
+ causal sequence kev runs for that question: the state followed by the branch, with positions continuing.
114
+
115
+ - **One pass over the state.** Its tokens run once. Their per-layer results (attention K/V, the Gated DeltaNet
116
+ recurrent state, the last three pre-conv tokens) become the prefix state. Every question then starts from it. kev
117
+ recomputes the state once per question whenever the padded row batch fits its row budget.
118
+ - **All questions of all waiting requests in one pass.** Prefill segments and branch rows from many requests go
119
+ through the layers together as one flat, unpadded token list (a *sweep*). Each projection and MLP is one GEMM. The
120
+ DeltaNet layers make one varlen kernel call for the prefill segments and one for all branch rows. Each row's initial
121
+ state is its request's prefix state, replicated per row by `index_select`; nothing is copied per question beyond
122
+ that. The causal conv is a single gather over `[carried tails; tokens]`. Full attention runs per request, with all
123
+ of its rows' tokens attending `[prefix K/V; own row]` under a block-diagonal mask. The prefix K/V is read once per
124
+ request.
125
+ - **Long states** (up to the 65,536-token cap) are prefilled in chunks of `prefill_chunk` tokens, one chunk per sweep,
126
+ with every state carried between sweeps. Attention calls are split by query so that even a math-kernel fallback never
127
+ needs an L x L score matrix.
128
+ - **State-bidirectional checkpoints** (kev KEV_STATE_BIDIR; `architecture.state_bidir` = B, `format_version` 2): the
129
+ full-attention layers let a state token at i see the state token at j when j <= i or i // B = j // B; branch tokens
130
+ and the DeltaNet layers stay causal. `--prefill-chunk` must be a multiple of B (the default is rounded down to one, at
131
+ least B), so every block is attended whole inside one segment; a segment that would split a block is an error. The
132
+ torch (CUDA, CPU) and MLX backends implement it (tests: verdin/tests/test_bidir.py, `mlx_parity tiny|bidir`).
133
+ - **No LoRA at runtime.** The adapter is merged at conversion.
134
+ - **Precision.** The residual stream, every norm, gate and softmax, RoPE, the conv accumulation and the pointer head
135
+ run in fp32. Matmul weights and activations use the compute dtype (bf16 on GPU).
136
+ - **Only what is read.** The last layer's MLP, the final norm and the pointer head run on the readout tokens only
137
+ (`<decide>` and each `</opt>`).
138
+
139
+ Code map: `render.py` (validation, rendering, tokenization; pure Python + tokenizers), `answers.py` (wire format),
140
+ `config.py`, `engine.py` (backend-independent: sweep planning, flat layouts and conv indices, prefix states and cache,
141
+ batch de-duplication, out-of-memory policy), `torch_backend.py` (the model and kernels: executes one sweep), `core.py`
142
+ (Python API), `server.py` (HTTP + batcher), `convert.py`. A new backend (MLX) implements `BaseEngine.execute(layout)`
143
+ and reuses everything else.
144
+
145
+ ## Limits
146
+
147
+ - **Caps.** By default (from `verdin_config.json`): state ≤ 65,536 tokens (including the delimiter and schema
148
+ block), any one branch ≤ 66,560 tokens minus the state, and the packed record ≤ 131,072 tokens. Choice questions take
149
+ 1..255 options and scores 2..255 levels. Anything over a cap is refused, never truncated.
150
+ - **Memory on a 32 GB RTX 5090 (bf16).** Weights take 8.4 GB. Each prefix state needs 32 KiB per state token of
151
+ attention K/V (2 GiB at 65k) plus 48 MiB of DeltaNet state. A sweep needs at most about 3 GB of activations at
152
+ 16k tokens. During attention the GQA-expanded K/V of one layer adds about 1 GiB at 65k keys. Each branch row in a
153
+ sweep holds a 2 MiB replicated DeltaNet state per layer (`--max-sweep-rows`, default 256). Estimated peak for one
154
+ 65k-token request is about 14-16 GB. The GPU job measures the real peaks. A request that still runs out of memory is
155
+ retried alone, then refused with "too many tokens".
156
+ - **Determinism.** With dynamic batching, bf16 numbers can move in the last bits with batch composition (GEMM shapes
157
+ change). `--max-batch 1` gives one request per forward. On CPU in fp32, batched and single runs agree to
158
+ ~1e-7 in the tests.
159
+ - **Scope.** Qwen3.5 hybrid backbones (Gated DeltaNet + gated full attention) with kev's plain pointer head and an
160
+ optional unknown logit. Not supported: option isolation, `KEV_LAYER_MIX`, `KEV_OPT_INTERACT`, `KEV_TRUNCATE`, Gemma
161
+ bases, trained special-token embeddings. `convert` refuses these.
162
+ - **Mac.** The MLX backend (`verdin/mlx_backend.py`, Apple silicon) is described in [README-mac.md](README-mac.md).
163
+ - **Not yet.** CUDA Graphs for the branch phase are a reserved option (`--cuda-graphs`) that is not implemented yet.
164
+
165
+ ## Tests
166
+
167
+ | test | where | what |
168
+ |---|---|---|
169
+ | `python -m verdin.tests.test_tiny [--device cuda --dtype bf16]` | anywhere (needs transformers) | the forward pass on a tiny random Qwen3.5 against transformers run as kev runs it, across batching, chunked prefill, multi-sweep plans, the prefix cache, duplicate states, query chunking, the unknown head and unmerged-vs-merged LoRA |
170
+ | `python -m verdin.tests.test_server --tokenizer tokenizer.json` | anywhere | server on a random tiny checkpoint: every question type, 422s, the cap refusal, 96 concurrent requests against one-at-a-time, the Decision Index http engine and validator, the JevBench typesafe adapter |
171
+ | `python -m verdin.tests.render_parity` | host with kev | tokens identical to kev's encode on our suites plus edge cases |
172
+ | `python -m verdin.tests.numeric_parity kev / verdin / compare` | host with kev | logits against kev's DecisionModel (fp32 reference, LoRA unmerged) and the stored eval rows |
173
+ | `python -m verdin.tests.eval_rows` | GPU host | every suite against kev's stored rows (argmax agreement, accuracy difference) |
174
+ | `python -m verdin.tests.bench` | GPU host | latency and throughput at concurrency 1/8/32, peak memory, against kev's predictor_server |
175
+ | `bash verdin/tests/parity_gpu.sh s1` | GPU host | all of the above in one job, with `verdict.json` |
176
+
177
+ ## Validation (phase A, CPU; checkpoint exp-combo-s-di-4b-s1)
178
+
179
+ - **Tokens.** Verdin's request-to-token path matched kev's on 10,483 record encodings from 18 suites plus edge cases.
180
+ The edge cases cover forged delimiters, odd JSON values, schemas over 512 tokens, date pairs and invalid requests.
181
+ Four settings were run: serving caps with schema-first and date facts, eval caps, kev's default caps without schema
182
+ or date facts, and the remaining suites at serving caps. There were 0 mismatches. Every cap refusal came with kev's
183
+ own message, and every invalid request was rejected by both.
184
+ - **Numbers.** On 64 records (124 questions; multi-question records and 3-8k-token states), Verdin in fp32 was
185
+ compared with kev's DecisionModel in fp32 with the LoRA unmerged. Max |dlogit| was 3.0e-5 and max |dp| 8.6e-6, with
186
+ 124/124 matching argmax. Verdin's batched and single-request runs differed by 3.8e-6 at most. Running the bf16 merged
187
+ weights with fp32 compute gave max |dp| 0.025 at T = 1 (0.0088 at the served T = 2.76), still 124/124. kev's stored
188
+ GPU eval rows come from its default path for this checkpoint: a bf16 backbone with an unmerged fp32 LoRA. Those rows
189
+ sit up to 0.09 away from the fp32 model (median 2e-4). They disagree on 1 of 120 argmaxes, a near-tie where the fp32
190
+ model is right.
191
+ - **Wire format.** The real checkpoint, served on the CPU, passed the Decision Index http engine and validator, the
192
+ JevBench typesafe adapter, and 96 concurrent requests (batches up to 23, |dp| ≤ 2.2e-7 against one-at-a-time runs).
193
+ - GPU acceptance (kernels, bf16 against the stored rows on every suite, speed against kev) is `verdin/tests/parity_gpu.sh`.
194
+
195
+ ## License
196
+
197
+ The code is under Apache-2.0 (`LICENSE`); `NOTICE` credits kev (Apache-2.0), Hugging Face Transformers (Apache-2.0)
198
+ and Qwen3.5 (Apache-2.0). Model weights are not covered by this license. Verdin-4B is released under CC-BY-NC-4.0, as
199
+ stated in its model card.
verdin/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verdin: an inference engine for System One decision models (state + typed questions -> a probability for every
2
+ option, from one prefill pass, no generated tokens). Apache-2.0; see LICENSE and NOTICE.
3
+
4
+ from verdin import Verdin
5
+ v = Verdin.from_pretrained("runs/verdin-4b-s1")
6
+ v.decide(state, questions)
7
+ """
8
+ __version__ = "0.1.0"
9
+
10
+
11
+ def __getattr__(name): # lazy: `import verdin.render` must not pull in torch
12
+ if name == "Verdin":
13
+ from .core import Verdin
14
+ return Verdin
15
+ raise AttributeError(name)
16
+
17
+
18
+ __all__ = ["Verdin", "__version__"]
verdin/answers.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logits -> the /v1/systemone answer objects (TypeSafe wire format, as kev.serve and minijev.predictor_server send it).
2
+
3
+ noul {"type": "noul", "noul": P(true)}
4
+ choice {"type": "choice", "choice": argmax key, "probabilities": {key: p}, "confidence": c}
5
+ score {"type": "score", "score": expected level, "probabilities": {"0": p, ...}, "legend": {"0": text}, "confidence": c}
6
+
7
+ Probabilities are full-precision floats (what the Decision Index runs scored; kev.serve's playground rounds to 2
8
+ decimals, which no benchmark client needs). Confidence formulas are kev.api's.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ from .render import Question, render
15
+
16
+
17
+ def softmax(z: list[float], temperature: float = 1.0) -> list[float]:
18
+ """Softmax in float64 of z / temperature."""
19
+ z = [x / temperature for x in z]
20
+ m = max(z)
21
+ e = [math.exp(x - m) for x in z]
22
+ s = sum(e)
23
+ return [x / s for x in e]
24
+
25
+
26
+ def choice_confidence(p: list[float]) -> float:
27
+ K = len(p)
28
+ return 1.0 if K == 1 else (max(p) - 1 / K) / (1 - 1 / K)
29
+
30
+
31
+ def score_confidence(p: list[float]) -> float:
32
+ """1 - E|level - mode| / (L - 1) (kev's approximation of TypeSafe's statistic)."""
33
+ L = len(p); mode = max(range(L), key=lambda i: p[i])
34
+ return 1.0 - sum(pi * abs(i - mode) for i, pi in enumerate(p)) / (L - 1)
35
+
36
+
37
+ def answer(q: Question, p: list[float]) -> dict:
38
+ keys = q.keys
39
+ if q.type == "noul":
40
+ return {"type": "noul", "noul": float(p[1])}
41
+ best = max(range(len(p)), key=lambda i: p[i]) # first maximum, as kev / predictor_server
42
+ if q.type == "choice":
43
+ return {"type": "choice", "choice": keys[best], "probabilities": {k: float(v) for k, v in zip(keys, p)},
44
+ "confidence": float(choice_confidence(p))}
45
+ return {"type": "score", "score": float(sum(i * pi for i, pi in enumerate(p))),
46
+ "probabilities": {k: float(v) for k, v in zip(keys, p)},
47
+ "legend": {k: render(x) for k, x in zip(keys, q.criteria)}, "confidence": float(score_confidence(p))}
48
+
49
+
50
+ def answers(questions: list[Question], probs: list[list[float]], unknown: list[float] | None = None) -> dict:
51
+ """The "answers" object; with an unknown head, `unknown` adds each question's p(unknown) as "unknown_probability"
52
+ (an extra field: TypeSafe clients ignore it)."""
53
+ out = {}
54
+ for i, (q, p) in enumerate(zip(questions, probs)):
55
+ a = answer(q, p)
56
+ if unknown is not None:
57
+ a["unknown_probability"] = float(unknown[i])
58
+ out[q.id] = a
59
+ return out
verdin/config.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """verdin_config.json: everything a backend needs to run a converted checkpoint (no kev, no transformers).
2
+
3
+ {
4
+ "format": "verdin", "format_version": 1, "model_name": "Verdin-4B",
5
+ "architecture": {...Qwen3.5 text backbone...},
6
+ "weights": {"file": "model.safetensors", "dtype": "bfloat16"},
7
+ "head": {"file": "head.safetensors", "dim": 256, "unknown": false, "temperature": 2.76},
8
+ "tokenizer": {"file": "tokenizer.json", "specials": {"state": "<|fim_prefix|>", ...}},
9
+ "render": {"schema_first": true, "date_facts": true, "max_state": ..., "max_branch": ..., "max_packed": ..., "schema_max": 512},
10
+ "source": {...kev run, base revision, LoRA, md5s...}, "conversion": {...verification...}
11
+ }
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ FORMAT = "verdin"
20
+ FORMAT_VERSION = 2 # 2 (2026-10-14): architecture.state_bidir; a converter writes 2 only for such a checkpoint, else 1
21
+ CONFIG_NAME = "verdin_config.json"
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Arch:
26
+ """The Qwen3.5 hybrid text backbone (Gated DeltaNet linear attention + gated full attention, zero-centred RMSNorm,
27
+ partial RoPE). Only what the forward pass reads."""
28
+ hidden_size: int
29
+ num_hidden_layers: int
30
+ layer_types: tuple
31
+ intermediate_size: int
32
+ num_attention_heads: int
33
+ num_key_value_heads: int
34
+ head_dim: int
35
+ rms_norm_eps: float
36
+ rope_theta: float
37
+ partial_rotary_factor: float
38
+ linear_num_key_heads: int
39
+ linear_num_value_heads: int
40
+ linear_key_head_dim: int
41
+ linear_value_head_dim: int
42
+ linear_conv_kernel_dim: int
43
+ vocab_size: int
44
+ attn_output_gate: bool = True
45
+ hidden_act: str = "silu"
46
+ type: str = "qwen3_5_text"
47
+ # kev KEV_STATE_BIDIR (format_version 2): > 0 = the full-attention layers let state tokens attend bidirectionally
48
+ # within blocks of this many absolute positions (state token i -> j iff j <= i or i // B == j // B); 0 = causal
49
+ state_bidir: int = 0
50
+
51
+ KEYS = ("hidden_size", "num_hidden_layers", "layer_types", "intermediate_size", "num_attention_heads",
52
+ "num_key_value_heads", "head_dim", "rms_norm_eps", "rope_theta", "partial_rotary_factor",
53
+ "linear_num_key_heads", "linear_num_value_heads", "linear_key_head_dim", "linear_value_head_dim",
54
+ "linear_conv_kernel_dim", "vocab_size", "attn_output_gate", "hidden_act", "type", "state_bidir")
55
+
56
+ @classmethod
57
+ def from_dict(cls, d):
58
+ d = {k: d[k] for k in cls.KEYS if k in d}
59
+ d["layer_types"] = tuple(d["layer_types"])
60
+ return cls(**d)
61
+
62
+ @classmethod
63
+ def from_hf_text_config(cls, tc):
64
+ """From a Qwen3.5 config.json's text_config (or a text-only config)."""
65
+ rope = tc.get("rope_parameters") or {}
66
+ sec = rope.get("mrope_section")
67
+ if sec is not None and sum(sec) * 2 != int(tc["head_dim"] * rope.get("partial_rotary_factor", 1.0)):
68
+ raise ValueError(f"unexpected mrope_section {sec}")
69
+ if tc.get("hidden_act", "silu") != "silu" or not tc.get("attn_output_gate", True):
70
+ raise ValueError("only the silu / gated-attention Qwen3.5 text backbone is supported")
71
+ if tc.get("mlp_only_layers"):
72
+ raise ValueError("mlp_only_layers is not supported")
73
+ return cls(hidden_size=tc["hidden_size"], num_hidden_layers=tc["num_hidden_layers"], layer_types=tuple(tc["layer_types"]),
74
+ intermediate_size=tc["intermediate_size"], num_attention_heads=tc["num_attention_heads"],
75
+ num_key_value_heads=tc["num_key_value_heads"], head_dim=tc["head_dim"], rms_norm_eps=tc["rms_norm_eps"],
76
+ rope_theta=rope.get("rope_theta", tc.get("rope_theta")), partial_rotary_factor=rope.get("partial_rotary_factor", 1.0),
77
+ linear_num_key_heads=tc["linear_num_key_heads"], linear_num_value_heads=tc["linear_num_value_heads"],
78
+ linear_key_head_dim=tc["linear_key_head_dim"], linear_value_head_dim=tc["linear_value_head_dim"],
79
+ linear_conv_kernel_dim=tc["linear_conv_kernel_dim"], vocab_size=tc["vocab_size"])
80
+
81
+ def to_dict(self):
82
+ d = {k: getattr(self, k) for k in self.KEYS if k != "state_bidir" or self.state_bidir} # causal: as format 1
83
+ d["layer_types"] = list(self.layer_types)
84
+ return d
85
+
86
+
87
+ class VerdinConfig:
88
+ def __init__(self, d: dict, root: Path | None = None):
89
+ if d.get("format") != FORMAT:
90
+ raise ValueError("not a Verdin checkpoint (verdin_config.json format != 'verdin')")
91
+ if int(d.get("format_version", 0)) > FORMAT_VERSION:
92
+ raise ValueError(f"checkpoint format_version {d['format_version']} is newer than this Verdin ({FORMAT_VERSION})")
93
+ self.raw, self.root = d, root
94
+ self.arch = Arch.from_dict(d["architecture"])
95
+ if self.arch.state_bidir and int(d.get("format_version", 0)) < 2:
96
+ raise ValueError("architecture.state_bidir needs format_version 2")
97
+ self.model_name = d.get("model_name", "Verdin")
98
+ self.head = d["head"]
99
+ self.render = d["render"]
100
+ self.tokenizer = d["tokenizer"]
101
+ self.weights = d["weights"]
102
+
103
+ @classmethod
104
+ def load(cls, path):
105
+ p = Path(path)
106
+ f = p / CONFIG_NAME if p.is_dir() else p
107
+ return cls(json.loads(f.read_text(encoding="utf-8")), f.parent)
108
+
109
+ def file(self, name) -> Path:
110
+ return self.root / name
111
+
112
+ @property
113
+ def temperature(self) -> float:
114
+ return float(self.head.get("temperature", 1.0))
verdin/convert.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """kev run directory -> Verdin checkpoint directory.
2
+
3
+ python -m verdin.convert --run runs/exp-combo-s-di-4b-s1 --out runs/verdin-4b-s1 \\
4
+ --schema-first 1 --date-facts 1 --max-state 65536 --max-branch 66560 --max-packed 131072
5
+
6
+ Reads the run (adapter_model.safetensors + adapter_config.json + head.pt) and its pinned base snapshot (Qwen3.5
7
+ config.json + safetensors shards, from --base or the HF cache), then writes
8
+ model.safetensors the text backbone with the LoRA merged in fp32, cast once to --dtype (bf16 default). Only what
9
+ the forward reads: no vision tower, no MTP head, no LM head (tied, unused)
10
+ head.safetensors the pointer head, fp32 (q, k [, unk_key, unk_bias])
11
+ tokenizer.json the tokenizer exactly as kev runs it (transformers' backend tokenizer of the base, when
12
+ transformers is importable; else the run's own tokenizer.json)
13
+ verdin_config.json architecture, render settings (schema-first, date facts, caps), special tokens, temperature,
14
+ unknown-head flag, source run + md5s, conversion checks
15
+ NOTICE
16
+ minijev 10-24: a kev.train --full_ft run (head.pt "full_ft"; the whole backbone in the run's model.safetensors, or
17
+ model-0000i-of-0000n.safetensors + model.safetensors.index.json; no adapter) is converted the same way, with the run's own
18
+ tensors in place of base + merged LoRA: the base snapshot then only supplies config.json (and the tensor-name / shape
19
+ check), and the merge checks are skipped (the bf16-rounding check stays).
20
+ The render settings are NOT stored in a kev run (they were environment variables: KEV_SCHEMA_FIRST, KEV_DATE_FACTS /
21
+ --date-facts, KEV_MAX_*), so they are required flags here.
22
+
23
+ Checks (CPU, fp32): every adapter tensor is consumed and every merged weight is probed (x W_merged^T vs
24
+ x W^T + s (x A^T) B^T); with --verify N (default 3), N probe requests run through Verdin's own forward with the
25
+ base weights + unmerged LoRA and with the merged weights (and, for a bf16 artifact, with the bf16-rounded weights),
26
+ and the logit / probability differences are recorded in verdin_config.json.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import dataclasses
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import shutil
36
+ import sys
37
+ import time
38
+ from pathlib import Path
39
+
40
+ from .config import CONFIG_NAME, FORMAT, FORMAT_VERSION, Arch
41
+
42
+ QWEN_SPECIALS = {"state": "<|fim_prefix|>", "question": "<|fim_middle|>", "option": "<|box_start|>",
43
+ "option_end": "<|box_end|>", "decide": "<|fim_suffix|>"}
44
+ PREFIX = "model.language_model."
45
+ from . import __version__ as VERDIN_VERSION # noqa: E402
46
+
47
+
48
+ def md5(path, chunk=1 << 22):
49
+ h = hashlib.md5()
50
+ with open(path, "rb") as f:
51
+ while True:
52
+ b = f.read(chunk)
53
+ if not b: break
54
+ h.update(b)
55
+ return h.hexdigest()
56
+
57
+
58
+ def resolve_base(name, revision, base=None):
59
+ if base:
60
+ return Path(base)
61
+ hf_home = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface"))
62
+ snap = hf_home / "hub" / ("models--" + name.replace("/", "--")) / "snapshots" / (revision or "")
63
+ if revision and snap.is_dir():
64
+ return snap
65
+ from huggingface_hub import snapshot_download
66
+ return Path(snapshot_download(name, revision=revision, allow_patterns=["*.json", "*.safetensors", "*.txt"]))
67
+
68
+
69
+ def load_head_pt(path):
70
+ import torch
71
+ try:
72
+ return torch.load(path, map_location="cpu", weights_only=True)
73
+ except Exception: # noqa: BLE001 - older pickles with non-allowlisted objects
74
+ return torch.load(path, map_location="cpu", weights_only=False)
75
+
76
+
77
+ def probe_requests():
78
+ """A few realistic requests (every question type, a date pair for date facts, a long-ish state)."""
79
+ long_state = {"ticket": "Customer reports the invoice dated March 3, 2026 was charged twice; refund requested on 2026-03-20.",
80
+ "history": [{"from": "agent", "text": "We see two charges of $49.00."},
81
+ {"from": "customer", "text": "Please refund one. " * 40}]}
82
+ return [
83
+ {"state": "The package arrived on time but the box was crushed and one mug was broken.",
84
+ "questions": {"sentiment": {"type": "choice", "instructions": "Overall sentiment of the review?",
85
+ "criteria": {"positive": None, "neutral": None, "negative": "unhappy customer"}},
86
+ "damaged": {"type": "noul", "instructions": "Was anything damaged?"}}},
87
+ {"state": long_state,
88
+ "questions": {"team": {"type": "choice", "instructions": "Route the ticket.",
89
+ "criteria": {"billing": "charges, refunds", "shipping": None, "tech": "bugs"}},
90
+ "urgency": {"type": "score", "instructions": "How urgent is it?", "criteria": ["low", "medium", "high"]},
91
+ "late": {"type": "noul", "instructions": "Was the refund requested more than 14 days after the invoice?",
92
+ "criteria": {"true": "more than 14 days", "false": "14 days or fewer"}}}},
93
+ {"state": ["step 1: compile", "step 2: tests failed: 3 of 120", {"log": "AssertionError in test_parse_dates"}],
94
+ "questions": {"ok": {"type": "noul", "instructions": "Did the build pass?"}}},
95
+ ]
96
+
97
+
98
+ def main(argv=None):
99
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
100
+ ap.add_argument("--run", required=True, help="kev run directory (adapter_model.safetensors, adapter_config.json, head.pt)")
101
+ ap.add_argument("--out", required=True)
102
+ ap.add_argument("--base", help="base snapshot directory (default: the HF cache entry pinned by head.pt)")
103
+ ap.add_argument("--schema-first", type=int, choices=[0, 1], required=True, help="KEV_SCHEMA_FIRST the run was trained/served with")
104
+ ap.add_argument("--date-facts", type=int, choices=[0, 1], required=True, help="serve with kev's date facts preprocessing")
105
+ ap.add_argument("--max-state", type=int, default=65536)
106
+ ap.add_argument("--max-branch", type=int, default=66560)
107
+ ap.add_argument("--max-packed", type=int, default=131072)
108
+ ap.add_argument("--schema-max", type=int, default=512, help="KEV_SCHEMA_MAX")
109
+ ap.add_argument("--dtype", choices=["bf16", "fp32"], default="bf16")
110
+ ap.add_argument("--name", default="Verdin-4B")
111
+ ap.add_argument("--verify", type=int, default=3, help="probe requests for the merged-vs-unmerged check (0 = skip)")
112
+ ap.add_argument("--threads", type=int, default=int(os.environ.get("OMP_NUM_THREADS", "0") or 0))
113
+ ap.add_argument("--force", action="store_true", help="overwrite an existing --out")
114
+ a = ap.parse_args(argv)
115
+ import torch
116
+ from safetensors import safe_open
117
+ from safetensors.torch import save_file
118
+ if a.threads:
119
+ torch.set_num_threads(a.threads)
120
+ t0 = time.time()
121
+ run, out = Path(a.run), Path(a.out)
122
+ if out.exists() and any(out.iterdir()) and not a.force:
123
+ sys.exit(f"{out} exists and is not empty (use --force)")
124
+ out.mkdir(parents=True, exist_ok=True)
125
+
126
+ # -- the run ------------------------------------------------------------------------------------------------
127
+ meta = load_head_pt(run / "head.pt")
128
+ full = bool(meta.get("full_ft")) # minijev 10-24: a kev --full_ft run (whole backbone in the run, no adapter)
129
+ acfg = {} if full else json.loads((run / "adapter_config.json").read_text(encoding="utf-8"))
130
+ head = meta["head"]
131
+ if set(head) - {"q.weight", "q.bias", "k.weight", "k.bias", "unk_key", "unk_bias"}:
132
+ sys.exit(f"unsupported pointer head (KEV_LAYER_MIX / KEV_OPT_INTERACT?): {sorted(head)}")
133
+ if meta.get("option_isolation") or meta.get("special_embeddings") or acfg.get("trainable_token_indices"):
134
+ sys.exit("option_isolation / trained special embeddings are not supported")
135
+ if acfg.get("use_dora") or acfg.get("peft_type", "LORA") != "LORA":
136
+ sys.exit("only plain LoRA adapters are supported")
137
+ if full:
138
+ r, alpha, scale = 0, 0.0, 0.0
139
+ else:
140
+ r, alpha = int(acfg["r"]), float(acfg["lora_alpha"])
141
+ scale = alpha / (r ** 0.5 if acfg.get("use_rslora") else r)
142
+ base_name, base_rev = meta["base"], meta.get("base_revision")
143
+ base = resolve_base(base_name, base_rev, a.base)
144
+ bcfg = json.loads((base / "config.json").read_text(encoding="utf-8"))
145
+ tc = bcfg.get("text_config", bcfg)
146
+ arch = Arch.from_hf_text_config(tc)
147
+ bidir = int(meta.get("state_bidir", 0) or 0) # kev KEV_STATE_BIDIR, written to head.pt by training
148
+ if os.environ.get("KEV_STATE_BIDIR") not in (None, "") and int(os.environ["KEV_STATE_BIDIR"]) != bidir:
149
+ sys.exit(f"KEV_STATE_BIDIR={os.environ['KEV_STATE_BIDIR']} but the run was trained with state_bidir={bidir}")
150
+ if bidir:
151
+ arch = dataclasses.replace(arch, state_bidir=bidir)
152
+ trunc = [k for k in ("KEV_TRUNCATE", "KEV_LAYER_MIX", "KEV_OPT_INTERACT") if os.environ.get(k)]
153
+ if trunc:
154
+ sys.exit(f"{trunc} set in the environment: not supported by Verdin")
155
+ print(f"run {run} ({'full FT' if full else f'r={r}, alpha={alpha:g}, scale={scale:g}'}, T={meta.get('temperature', 1.0):.4f}{f', state_bidir={bidir}' if bidir else ''}); base {base_name}@{base_rev} at {base}", flush=True)
156
+
157
+ # -- base text weights in fp32 ---------------------------------------------------------------------------------
158
+ idx = base / "model.safetensors.index.json"
159
+ shards = sorted(set(json.loads(idx.read_text())["weight_map"].values())) if idx.exists() else ["model.safetensors"]
160
+ W, base_shapes = {}, {}
161
+ for sh in shards:
162
+ with safe_open(str(base / sh), framework="pt", device="cpu") as f:
163
+ for k in f.keys():
164
+ if k.startswith(PREFIX):
165
+ if full: # minijev 10-24: names / shapes only; the tensors come from the run
166
+ base_shapes[k[len(PREFIX):]] = tuple(f.get_slice(k).get_shape())
167
+ else:
168
+ W[k[len(PREFIX):]] = f.get_tensor(k).to(torch.float32)
169
+ n_layers = arch.num_hidden_layers
170
+ keep = lambda k: not k.startswith("layers.") or int(k.split(".")[1]) < n_layers
171
+ W = {k: v for k, v in W.items() if keep(k)}
172
+ rshards = []
173
+ if full:
174
+ ridx = run / "model.safetensors.index.json"
175
+ rshards = sorted(set(json.loads(ridx.read_text())["weight_map"].values())) if ridx.exists() else ["model.safetensors"]
176
+ for sh in rshards:
177
+ with safe_open(str(run / sh), framework="pt", device="cpu") as f:
178
+ for k in f.keys():
179
+ if keep(k):
180
+ W[k] = f.get_tensor(k).to(torch.float32)
181
+ base_shapes = {k: v for k, v in base_shapes.items() if keep(k)}
182
+ if base_shapes: # (a base snapshot without the multimodal "model.language_model." layout gives no names to check)
183
+ missing = sorted(set(base_shapes) - set(W))
184
+ bad = [k for k in base_shapes if k in W and tuple(W[k].shape) != base_shapes[k]]
185
+ if missing or bad:
186
+ sys.exit(f"full-FT run vs base: {len(missing)} base tensors missing (e.g. {missing[:2]}), {len(bad)} shape mismatches (e.g. {bad[:2]})")
187
+ W = {k: v for k, v in W.items() if k in base_shapes}
188
+ print(f"{'run (full FT)' if full else 'base'} text weights: {len(W)} tensors, {sum(v.numel() for v in W.values()) / 1e9:.3f} B params ({time.time() - t0:.0f} s)", flush=True)
189
+
190
+ # -- LoRA -----------------------------------------------------------------------------------------------------
191
+ lora = {}
192
+ if not full: # minijev 10-24: a full-FT run has no adapter
193
+ with safe_open(str(run / "adapter_model.safetensors"), framework="pt", device="cpu") as f:
194
+ keys = list(f.keys())
195
+ stems = sorted({k.rsplit(".lora_", 1)[0] for k in keys if ".lora_A." in k or ".lora_B." in k})
196
+ extra = [k for k in keys if ".lora_A." not in k and ".lora_B." not in k]
197
+ if extra:
198
+ sys.exit(f"adapter carries non-LoRA tensors: {extra[:3]}")
199
+ for stem in stems:
200
+ target = stem.replace("base_model.model.", "", 1) + ".weight"
201
+ if target not in W:
202
+ sys.exit(f"adapter tensor {stem} has no base weight {target}")
203
+ A = f.get_tensor(stem + ".lora_A.weight").to(torch.float32)
204
+ B = f.get_tensor(stem + ".lora_B.weight").to(torch.float32)
205
+ if B.shape[0] != W[target].shape[0] or A.shape[1] != W[target].shape[1] or A.shape[0] != r:
206
+ sys.exit(f"shape mismatch at {target}: W {tuple(W[target].shape)} A {tuple(A.shape)} B {tuple(B.shape)}")
207
+ lora[target] = (A, B, scale)
208
+ if full:
209
+ print("full FT: no LoRA to merge (the run's weights are used as trained)", flush=True)
210
+ else:
211
+ print(f"LoRA: {len(lora)} target weights ({len(keys)} adapter tensors)", flush=True)
212
+
213
+ # -- tokenizer ----------------------------------------------------------------------------------------------------
214
+ tok_src = None
215
+ try:
216
+ from transformers import AutoTokenizer
217
+ ht = AutoTokenizer.from_pretrained(str(base))
218
+ (out / "tokenizer.json").write_text(ht.backend_tokenizer.to_str(), encoding="utf-8")
219
+ tok_src = f"transformers {__import__('transformers').__version__} AutoTokenizer({base_name}@{base_rev}).backend_tokenizer (what kev runs)"
220
+ except Exception as e: # noqa: BLE001
221
+ if not (run / "tokenizer.json").exists():
222
+ sys.exit(f"no transformers ({e}) and no tokenizer.json in the run")
223
+ shutil.copyfile(run / "tokenizer.json", out / "tokenizer.json")
224
+ tok_src = f"copied from {run}/tokenizer.json (transformers unavailable: {type(e).__name__})"
225
+ for extra_file in ("tokenizer_config.json",):
226
+ if (base / extra_file).exists():
227
+ shutil.copyfile(base / extra_file, out / extra_file)
228
+ from .render import RenderConfig, Renderer, Tokenizer
229
+ tok = Tokenizer(out / "tokenizer.json", QWEN_SPECIALS)
230
+ render_cfg = {"schema_first": bool(a.schema_first), "date_facts": bool(a.date_facts), "max_state": a.max_state,
231
+ "max_branch": a.max_branch, "max_packed": a.max_packed, "schema_max": a.schema_max, "lead_ids": []}
232
+ renderer = Renderer(tok, RenderConfig.from_dict(render_cfg))
233
+
234
+ # -- verification: unmerged (base + LoRA) forward ----------------------------------------------------------------
235
+ checks = {}
236
+ head_t = {k: v.to(torch.float32) for k, v in head.items()}
237
+ encs = [renderer.encode_request(b) for b in probe_requests()[: max(0, a.verify)]]
238
+ from .torch_backend import TorchEngine, TorchModel, TorchOptions
239
+
240
+ def logits_with(weights, lora_terms):
241
+ m = TorchModel(arch, lambda n: weights[n], head_t, 1.0, TorchOptions(device="cpu", dtype="fp32", prefix_cache=0),
242
+ "fp32", lora=lora_terms, fuse=False)
243
+ res = TorchEngine(m).run(encs)
244
+ return [z for r in res for z in r.logits]
245
+
246
+ def compare(a_, b_):
247
+ import math
248
+ dl = max(abs(x - y) for za, zb in zip(a_, b_) for x, y in zip(za, zb))
249
+ dp, flips = 0.0, 0
250
+ for za, zb in zip(a_, b_):
251
+ pa = [math.exp(x - max(za)) for x in za]; pb = [math.exp(x - max(zb)) for x in zb]
252
+ sa, sb = sum(pa), sum(pb)
253
+ dp = max(dp, max(abs(x / sa - y / sb) for x, y in zip(pa, pb)))
254
+ flips += max(range(len(za)), key=lambda i: za[i]) != max(range(len(zb)), key=lambda i: zb[i])
255
+ return {"max_abs_dlogit": dl, "max_abs_dp": dp, "argmax_flips": flips, "questions": len(a_)}
256
+ if encs:
257
+ t1 = time.time()
258
+ z_unmerged = logits_with(W, lora or None)
259
+ print(f"verify: {'fp32' if full else 'unmerged'} forward on {len(encs)} probe requests ({time.time() - t1:.0f} s)", flush=True)
260
+
261
+ # -- merge (fp32, in place) with a per-tensor probe ---------------------------------------------------------------
262
+ g = torch.Generator().manual_seed(0)
263
+ worst = 0.0
264
+ for name, (A, B, s) in lora.items():
265
+ Wt = W[name]
266
+ x = torch.randn(4, Wt.shape[1], generator=g)
267
+ y_ref = x @ Wt.T + s * (x @ A.T) @ B.T
268
+ Wt.add_(s * (B @ A))
269
+ y = x @ Wt.T
270
+ worst = max(worst, float((y - y_ref).abs().max() / (y_ref.abs().max() + 1e-12)))
271
+ if full:
272
+ checks["full_ft"] = "weights taken from the run as trained (no merge)"
273
+ else:
274
+ checks["merge_probe_max_rel_err"] = worst
275
+ if worst > 1e-5:
276
+ sys.exit(f"merge probe failed: max relative error {worst:.2e}")
277
+ if not full: print(f"merged {len(lora)} weights in fp32 (probe max rel err {worst:.1e})", flush=True)
278
+ if encs and not full:
279
+ z_merged = logits_with(W, None)
280
+ checks["merged_vs_unmerged_fp32"] = compare(z_unmerged, z_merged)
281
+ print(f"verify merged vs unmerged (fp32): {checks['merged_vs_unmerged_fp32']}", flush=True)
282
+ out_dtype = torch.bfloat16 if a.dtype == "bf16" else torch.float32
283
+ if out_dtype == torch.bfloat16:
284
+ for k in W:
285
+ W[k] = W[k].to(torch.bfloat16)
286
+ if encs:
287
+ z_bf = logits_with(W, None) # TorchModel upcasts each bf16 tensor to fp32 (exact): fp32 compute on bf16 weights
288
+ checks["bf16_weights_vs_unmerged_fp32"] = compare(z_unmerged, z_bf)
289
+ print(f"verify bf16-rounded weights (fp32 compute) vs unmerged fp32: {checks['bf16_weights_vs_unmerged_fp32']}", flush=True)
290
+
291
+ # -- write ------------------------------------------------------------------------------------------------------
292
+ save_file({k: v.contiguous() for k, v in W.items()}, str(out / "model.safetensors"), metadata={"format": "pt", "verdin": FORMAT})
293
+ del W
294
+ head_out = {k: v.to(torch.float32).contiguous() for k, v in head.items()}
295
+ if "unk_bias" in head_out:
296
+ head_out["unk_bias"] = head_out["unk_bias"].reshape(())
297
+ save_file(head_out, str(out / "head.safetensors"), metadata={"format": "pt", "verdin": FORMAT})
298
+ lic = base / "LICENSE"
299
+ (out / "NOTICE").write_text(
300
+ f"{a.name}: converted with Verdin {VERDIN_VERSION} from the kev run {run.name}.\n"
301
+ f"Backbone: {base_name} (revision {base_rev}), Copyright the Qwen team, Alibaba Group, Apache License 2.0"
302
+ f"{' (see LICENSE.base)' if lic.exists() else ''}; {'full-parameter fine-tune' if full else f'LoRA fine-tune (r={r}) merged into these weights'}.\n"
303
+ "Training/inference recipe: kev (jaredpalmer/kev, Apache License 2.0) with mini-jev-lab patches.\n"
304
+ "The licence of these converted weights is given in the model card shipped with them.\n", encoding="utf-8")
305
+ if lic.exists():
306
+ shutil.copyfile(lic, out / "LICENSE.base")
307
+ cfg = {
308
+ "format": FORMAT, "format_version": FORMAT_VERSION if bidir else 1, "model_name": a.name,
309
+ "architecture": arch.to_dict(),
310
+ "weights": {"file": "model.safetensors", "dtype": "bfloat16" if a.dtype == "bf16" else "float32",
311
+ "md5": md5(out / "model.safetensors"), "lora_merged": not full,
312
+ **({"full_ft": True} if full else {})},
313
+ "head": {"file": "head.safetensors", "dim": int(head["q.weight"].shape[0]), "unknown": "unk_key" in head,
314
+ "temperature": float(meta.get("temperature", 1.0)), "md5": md5(out / "head.safetensors")},
315
+ "tokenizer": {"file": "tokenizer.json", "md5": md5(out / "tokenizer.json"), "source": tok_src,
316
+ "specials": QWEN_SPECIALS, "special_ids": dict(tok.ids)},
317
+ "render": render_cfg,
318
+ "source": {"kev_run": str(run), "base": base_name, "base_revision": base_rev,
319
+ "lora": None if full else {"r": r, "alpha": alpha, "scale": scale, "use_rslora": bool(acfg.get("use_rslora")),
320
+ "targets": sorted(acfg.get("target_modules") or []), "merged_weights": len(lora)},
321
+ "md5": ({"head.pt": md5(run / "head.pt"), **{f"run/{sh}": md5(run / sh) for sh in rshards}} if full else
322
+ {"adapter_model.safetensors": md5(run / "adapter_model.safetensors"), "head.pt": md5(run / "head.pt"),
323
+ "adapter_config.json": md5(run / "adapter_config.json")}) | {f"base/{sh}": md5(base / sh) for sh in shards},
324
+ "kev_weights_dtype": meta.get("weights_dtype"), "training_args": meta.get("args"),
325
+ "temperature_fit": meta.get("temperature_fit"), "suite_sha256": meta.get("suite_sha256")},
326
+ "conversion": {"verdin_version": VERDIN_VERSION, "time_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
327
+ "torch": torch.__version__, "checks": checks, "seconds": round(time.time() - t0, 1)},
328
+ }
329
+ (out / CONFIG_NAME).write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
330
+ print(f"wrote {out} ({a.dtype}, {time.time() - t0:.0f} s)", flush=True)
331
+
332
+
333
+ if __name__ == "__main__":
334
+ main()
verdin/convert.py.pre-fullft-1024 ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """kev run directory -> Verdin checkpoint directory.
2
+
3
+ python -m verdin.convert --run runs/exp-combo-s-di-4b-s1 --out runs/verdin-4b-s1 \\
4
+ --schema-first 1 --date-facts 1 --max-state 65536 --max-branch 66560 --max-packed 131072
5
+
6
+ Reads the run (adapter_model.safetensors + adapter_config.json + head.pt) and its pinned base snapshot (Qwen3.5
7
+ config.json + safetensors shards, from --base or the HF cache), then writes
8
+ model.safetensors the text backbone with the LoRA merged in fp32, cast once to --dtype (bf16 default). Only what
9
+ the forward reads: no vision tower, no MTP head, no LM head (tied, unused)
10
+ head.safetensors the pointer head, fp32 (q, k [, unk_key, unk_bias])
11
+ tokenizer.json the tokenizer exactly as kev runs it (transformers' backend tokenizer of the base, when
12
+ transformers is importable; else the run's own tokenizer.json)
13
+ verdin_config.json architecture, render settings (schema-first, date facts, caps), special tokens, temperature,
14
+ unknown-head flag, source run + md5s, conversion checks
15
+ NOTICE
16
+ The render settings are NOT stored in a kev run (they were environment variables: KEV_SCHEMA_FIRST, KEV_DATE_FACTS /
17
+ --date-facts, KEV_MAX_*), so they are required flags here.
18
+
19
+ Checks (CPU, fp32): every adapter tensor is consumed and every merged weight is probed (x W_merged^T vs
20
+ x W^T + s (x A^T) B^T); with --verify N (default 3), N probe requests run through Verdin's own forward with the
21
+ base weights + unmerged LoRA and with the merged weights (and, for a bf16 artifact, with the bf16-rounded weights),
22
+ and the logit / probability differences are recorded in verdin_config.json.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import dataclasses
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import shutil
32
+ import sys
33
+ import time
34
+ from pathlib import Path
35
+
36
+ from .config import CONFIG_NAME, FORMAT, FORMAT_VERSION, Arch
37
+
38
+ QWEN_SPECIALS = {"state": "<|fim_prefix|>", "question": "<|fim_middle|>", "option": "<|box_start|>",
39
+ "option_end": "<|box_end|>", "decide": "<|fim_suffix|>"}
40
+ PREFIX = "model.language_model."
41
+ from . import __version__ as VERDIN_VERSION # noqa: E402
42
+
43
+
44
+ def md5(path, chunk=1 << 22):
45
+ h = hashlib.md5()
46
+ with open(path, "rb") as f:
47
+ while True:
48
+ b = f.read(chunk)
49
+ if not b: break
50
+ h.update(b)
51
+ return h.hexdigest()
52
+
53
+
54
+ def resolve_base(name, revision, base=None):
55
+ if base:
56
+ return Path(base)
57
+ hf_home = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface"))
58
+ snap = hf_home / "hub" / ("models--" + name.replace("/", "--")) / "snapshots" / (revision or "")
59
+ if revision and snap.is_dir():
60
+ return snap
61
+ from huggingface_hub import snapshot_download
62
+ return Path(snapshot_download(name, revision=revision, allow_patterns=["*.json", "*.safetensors", "*.txt"]))
63
+
64
+
65
+ def load_head_pt(path):
66
+ import torch
67
+ try:
68
+ return torch.load(path, map_location="cpu", weights_only=True)
69
+ except Exception: # noqa: BLE001 - older pickles with non-allowlisted objects
70
+ return torch.load(path, map_location="cpu", weights_only=False)
71
+
72
+
73
+ def probe_requests():
74
+ """A few realistic requests (every question type, a date pair for date facts, a long-ish state)."""
75
+ long_state = {"ticket": "Customer reports the invoice dated March 3, 2026 was charged twice; refund requested on 2026-03-20.",
76
+ "history": [{"from": "agent", "text": "We see two charges of $49.00."},
77
+ {"from": "customer", "text": "Please refund one. " * 40}]}
78
+ return [
79
+ {"state": "The package arrived on time but the box was crushed and one mug was broken.",
80
+ "questions": {"sentiment": {"type": "choice", "instructions": "Overall sentiment of the review?",
81
+ "criteria": {"positive": None, "neutral": None, "negative": "unhappy customer"}},
82
+ "damaged": {"type": "noul", "instructions": "Was anything damaged?"}}},
83
+ {"state": long_state,
84
+ "questions": {"team": {"type": "choice", "instructions": "Route the ticket.",
85
+ "criteria": {"billing": "charges, refunds", "shipping": None, "tech": "bugs"}},
86
+ "urgency": {"type": "score", "instructions": "How urgent is it?", "criteria": ["low", "medium", "high"]},
87
+ "late": {"type": "noul", "instructions": "Was the refund requested more than 14 days after the invoice?",
88
+ "criteria": {"true": "more than 14 days", "false": "14 days or fewer"}}}},
89
+ {"state": ["step 1: compile", "step 2: tests failed: 3 of 120", {"log": "AssertionError in test_parse_dates"}],
90
+ "questions": {"ok": {"type": "noul", "instructions": "Did the build pass?"}}},
91
+ ]
92
+
93
+
94
+ def main(argv=None):
95
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
96
+ ap.add_argument("--run", required=True, help="kev run directory (adapter_model.safetensors, adapter_config.json, head.pt)")
97
+ ap.add_argument("--out", required=True)
98
+ ap.add_argument("--base", help="base snapshot directory (default: the HF cache entry pinned by head.pt)")
99
+ ap.add_argument("--schema-first", type=int, choices=[0, 1], required=True, help="KEV_SCHEMA_FIRST the run was trained/served with")
100
+ ap.add_argument("--date-facts", type=int, choices=[0, 1], required=True, help="serve with kev's date facts preprocessing")
101
+ ap.add_argument("--max-state", type=int, default=65536)
102
+ ap.add_argument("--max-branch", type=int, default=66560)
103
+ ap.add_argument("--max-packed", type=int, default=131072)
104
+ ap.add_argument("--schema-max", type=int, default=512, help="KEV_SCHEMA_MAX")
105
+ ap.add_argument("--dtype", choices=["bf16", "fp32"], default="bf16")
106
+ ap.add_argument("--name", default="Verdin-4B")
107
+ ap.add_argument("--verify", type=int, default=3, help="probe requests for the merged-vs-unmerged check (0 = skip)")
108
+ ap.add_argument("--threads", type=int, default=int(os.environ.get("OMP_NUM_THREADS", "0") or 0))
109
+ ap.add_argument("--force", action="store_true", help="overwrite an existing --out")
110
+ a = ap.parse_args(argv)
111
+ import torch
112
+ from safetensors import safe_open
113
+ from safetensors.torch import save_file
114
+ if a.threads:
115
+ torch.set_num_threads(a.threads)
116
+ t0 = time.time()
117
+ run, out = Path(a.run), Path(a.out)
118
+ if out.exists() and any(out.iterdir()) and not a.force:
119
+ sys.exit(f"{out} exists and is not empty (use --force)")
120
+ out.mkdir(parents=True, exist_ok=True)
121
+
122
+ # -- the run ------------------------------------------------------------------------------------------------
123
+ meta = load_head_pt(run / "head.pt")
124
+ acfg = json.loads((run / "adapter_config.json").read_text(encoding="utf-8"))
125
+ head = meta["head"]
126
+ if set(head) - {"q.weight", "q.bias", "k.weight", "k.bias", "unk_key", "unk_bias"}:
127
+ sys.exit(f"unsupported pointer head (KEV_LAYER_MIX / KEV_OPT_INTERACT?): {sorted(head)}")
128
+ if meta.get("option_isolation") or meta.get("special_embeddings") or acfg.get("trainable_token_indices"):
129
+ sys.exit("option_isolation / trained special embeddings are not supported")
130
+ if acfg.get("use_dora") or acfg.get("peft_type", "LORA") != "LORA":
131
+ sys.exit("only plain LoRA adapters are supported")
132
+ r, alpha = int(acfg["r"]), float(acfg["lora_alpha"])
133
+ scale = alpha / (r ** 0.5 if acfg.get("use_rslora") else r)
134
+ base_name, base_rev = meta["base"], meta.get("base_revision")
135
+ base = resolve_base(base_name, base_rev, a.base)
136
+ bcfg = json.loads((base / "config.json").read_text(encoding="utf-8"))
137
+ tc = bcfg.get("text_config", bcfg)
138
+ arch = Arch.from_hf_text_config(tc)
139
+ bidir = int(meta.get("state_bidir", 0) or 0) # kev KEV_STATE_BIDIR, written to head.pt by training
140
+ if os.environ.get("KEV_STATE_BIDIR") not in (None, "") and int(os.environ["KEV_STATE_BIDIR"]) != bidir:
141
+ sys.exit(f"KEV_STATE_BIDIR={os.environ['KEV_STATE_BIDIR']} but the run was trained with state_bidir={bidir}")
142
+ if bidir:
143
+ arch = dataclasses.replace(arch, state_bidir=bidir)
144
+ trunc = [k for k in ("KEV_TRUNCATE", "KEV_LAYER_MIX", "KEV_OPT_INTERACT") if os.environ.get(k)]
145
+ if trunc:
146
+ sys.exit(f"{trunc} set in the environment: not supported by Verdin")
147
+ print(f"run {run} (r={r}, alpha={alpha:g}, scale={scale:g}, T={meta.get('temperature', 1.0):.4f}{f', state_bidir={bidir}' if bidir else ''}); base {base_name}@{base_rev} at {base}", flush=True)
148
+
149
+ # -- base text weights in fp32 ---------------------------------------------------------------------------------
150
+ idx = base / "model.safetensors.index.json"
151
+ shards = sorted(set(json.loads(idx.read_text())["weight_map"].values())) if idx.exists() else ["model.safetensors"]
152
+ W = {}
153
+ for sh in shards:
154
+ with safe_open(str(base / sh), framework="pt", device="cpu") as f:
155
+ for k in f.keys():
156
+ if k.startswith(PREFIX):
157
+ W[k[len(PREFIX):]] = f.get_tensor(k).to(torch.float32)
158
+ n_layers = arch.num_hidden_layers
159
+ W = {k: v for k, v in W.items() if not k.startswith("layers.") or int(k.split(".")[1]) < n_layers}
160
+ print(f"base text weights: {len(W)} tensors, {sum(v.numel() for v in W.values()) / 1e9:.3f} B params ({time.time() - t0:.0f} s)", flush=True)
161
+
162
+ # -- LoRA -----------------------------------------------------------------------------------------------------
163
+ lora = {}
164
+ with safe_open(str(run / "adapter_model.safetensors"), framework="pt", device="cpu") as f:
165
+ keys = list(f.keys())
166
+ stems = sorted({k.rsplit(".lora_", 1)[0] for k in keys if ".lora_A." in k or ".lora_B." in k})
167
+ extra = [k for k in keys if ".lora_A." not in k and ".lora_B." not in k]
168
+ if extra:
169
+ sys.exit(f"adapter carries non-LoRA tensors: {extra[:3]}")
170
+ for stem in stems:
171
+ target = stem.replace("base_model.model.", "", 1) + ".weight"
172
+ if target not in W:
173
+ sys.exit(f"adapter tensor {stem} has no base weight {target}")
174
+ A = f.get_tensor(stem + ".lora_A.weight").to(torch.float32)
175
+ B = f.get_tensor(stem + ".lora_B.weight").to(torch.float32)
176
+ if B.shape[0] != W[target].shape[0] or A.shape[1] != W[target].shape[1] or A.shape[0] != r:
177
+ sys.exit(f"shape mismatch at {target}: W {tuple(W[target].shape)} A {tuple(A.shape)} B {tuple(B.shape)}")
178
+ lora[target] = (A, B, scale)
179
+ print(f"LoRA: {len(lora)} target weights ({len(keys)} adapter tensors)", flush=True)
180
+
181
+ # -- tokenizer ----------------------------------------------------------------------------------------------------
182
+ tok_src = None
183
+ try:
184
+ from transformers import AutoTokenizer
185
+ ht = AutoTokenizer.from_pretrained(str(base))
186
+ (out / "tokenizer.json").write_text(ht.backend_tokenizer.to_str(), encoding="utf-8")
187
+ tok_src = f"transformers {__import__('transformers').__version__} AutoTokenizer({base_name}@{base_rev}).backend_tokenizer (what kev runs)"
188
+ except Exception as e: # noqa: BLE001
189
+ if not (run / "tokenizer.json").exists():
190
+ sys.exit(f"no transformers ({e}) and no tokenizer.json in the run")
191
+ shutil.copyfile(run / "tokenizer.json", out / "tokenizer.json")
192
+ tok_src = f"copied from {run}/tokenizer.json (transformers unavailable: {type(e).__name__})"
193
+ for extra_file in ("tokenizer_config.json",):
194
+ if (base / extra_file).exists():
195
+ shutil.copyfile(base / extra_file, out / extra_file)
196
+ from .render import RenderConfig, Renderer, Tokenizer
197
+ tok = Tokenizer(out / "tokenizer.json", QWEN_SPECIALS)
198
+ render_cfg = {"schema_first": bool(a.schema_first), "date_facts": bool(a.date_facts), "max_state": a.max_state,
199
+ "max_branch": a.max_branch, "max_packed": a.max_packed, "schema_max": a.schema_max, "lead_ids": []}
200
+ renderer = Renderer(tok, RenderConfig.from_dict(render_cfg))
201
+
202
+ # -- verification: unmerged (base + LoRA) forward ----------------------------------------------------------------
203
+ checks = {}
204
+ head_t = {k: v.to(torch.float32) for k, v in head.items()}
205
+ encs = [renderer.encode_request(b) for b in probe_requests()[: max(0, a.verify)]]
206
+ from .torch_backend import TorchEngine, TorchModel, TorchOptions
207
+
208
+ def logits_with(weights, lora_terms):
209
+ m = TorchModel(arch, lambda n: weights[n], head_t, 1.0, TorchOptions(device="cpu", dtype="fp32", prefix_cache=0),
210
+ "fp32", lora=lora_terms, fuse=False)
211
+ res = TorchEngine(m).run(encs)
212
+ return [z for r in res for z in r.logits]
213
+
214
+ def compare(a_, b_):
215
+ import math
216
+ dl = max(abs(x - y) for za, zb in zip(a_, b_) for x, y in zip(za, zb))
217
+ dp, flips = 0.0, 0
218
+ for za, zb in zip(a_, b_):
219
+ pa = [math.exp(x - max(za)) for x in za]; pb = [math.exp(x - max(zb)) for x in zb]
220
+ sa, sb = sum(pa), sum(pb)
221
+ dp = max(dp, max(abs(x / sa - y / sb) for x, y in zip(pa, pb)))
222
+ flips += max(range(len(za)), key=lambda i: za[i]) != max(range(len(zb)), key=lambda i: zb[i])
223
+ return {"max_abs_dlogit": dl, "max_abs_dp": dp, "argmax_flips": flips, "questions": len(a_)}
224
+ if encs:
225
+ t1 = time.time()
226
+ z_unmerged = logits_with(W, lora)
227
+ print(f"verify: unmerged forward on {len(encs)} probe requests ({time.time() - t1:.0f} s)", flush=True)
228
+
229
+ # -- merge (fp32, in place) with a per-tensor probe ---------------------------------------------------------------
230
+ g = torch.Generator().manual_seed(0)
231
+ worst = 0.0
232
+ for name, (A, B, s) in lora.items():
233
+ Wt = W[name]
234
+ x = torch.randn(4, Wt.shape[1], generator=g)
235
+ y_ref = x @ Wt.T + s * (x @ A.T) @ B.T
236
+ Wt.add_(s * (B @ A))
237
+ y = x @ Wt.T
238
+ worst = max(worst, float((y - y_ref).abs().max() / (y_ref.abs().max() + 1e-12)))
239
+ checks["merge_probe_max_rel_err"] = worst
240
+ if worst > 1e-5:
241
+ sys.exit(f"merge probe failed: max relative error {worst:.2e}")
242
+ print(f"merged {len(lora)} weights in fp32 (probe max rel err {worst:.1e})", flush=True)
243
+ if encs:
244
+ z_merged = logits_with(W, None)
245
+ checks["merged_vs_unmerged_fp32"] = compare(z_unmerged, z_merged)
246
+ print(f"verify merged vs unmerged (fp32): {checks['merged_vs_unmerged_fp32']}", flush=True)
247
+ out_dtype = torch.bfloat16 if a.dtype == "bf16" else torch.float32
248
+ if out_dtype == torch.bfloat16:
249
+ for k in W:
250
+ W[k] = W[k].to(torch.bfloat16)
251
+ if encs:
252
+ z_bf = logits_with(W, None) # TorchModel upcasts each bf16 tensor to fp32 (exact): fp32 compute on bf16 weights
253
+ checks["bf16_weights_vs_unmerged_fp32"] = compare(z_unmerged, z_bf)
254
+ print(f"verify bf16-rounded weights (fp32 compute) vs unmerged fp32: {checks['bf16_weights_vs_unmerged_fp32']}", flush=True)
255
+
256
+ # -- write ------------------------------------------------------------------------------------------------------
257
+ save_file({k: v.contiguous() for k, v in W.items()}, str(out / "model.safetensors"), metadata={"format": "pt", "verdin": FORMAT})
258
+ del W
259
+ head_out = {k: v.to(torch.float32).contiguous() for k, v in head.items()}
260
+ if "unk_bias" in head_out:
261
+ head_out["unk_bias"] = head_out["unk_bias"].reshape(())
262
+ save_file(head_out, str(out / "head.safetensors"), metadata={"format": "pt", "verdin": FORMAT})
263
+ lic = base / "LICENSE"
264
+ (out / "NOTICE").write_text(
265
+ f"{a.name}: converted with Verdin {VERDIN_VERSION} from the kev run {run.name}.\n"
266
+ f"Backbone: {base_name} (revision {base_rev}), Copyright the Qwen team, Alibaba Group, Apache License 2.0"
267
+ f"{' (see LICENSE.base)' if lic.exists() else ''}; LoRA fine-tune (r={r}) merged into these weights.\n"
268
+ "Training/inference recipe: kev (jaredpalmer/kev, Apache License 2.0) with mini-jev-lab patches.\n"
269
+ "The licence of these converted weights is given in the model card shipped with them.\n", encoding="utf-8")
270
+ if lic.exists():
271
+ shutil.copyfile(lic, out / "LICENSE.base")
272
+ cfg = {
273
+ "format": FORMAT, "format_version": FORMAT_VERSION if bidir else 1, "model_name": a.name,
274
+ "architecture": arch.to_dict(),
275
+ "weights": {"file": "model.safetensors", "dtype": "bfloat16" if a.dtype == "bf16" else "float32",
276
+ "md5": md5(out / "model.safetensors"), "lora_merged": True},
277
+ "head": {"file": "head.safetensors", "dim": int(head["q.weight"].shape[0]), "unknown": "unk_key" in head,
278
+ "temperature": float(meta.get("temperature", 1.0)), "md5": md5(out / "head.safetensors")},
279
+ "tokenizer": {"file": "tokenizer.json", "md5": md5(out / "tokenizer.json"), "source": tok_src,
280
+ "specials": QWEN_SPECIALS, "special_ids": dict(tok.ids)},
281
+ "render": render_cfg,
282
+ "source": {"kev_run": str(run), "base": base_name, "base_revision": base_rev,
283
+ "lora": {"r": r, "alpha": alpha, "scale": scale, "use_rslora": bool(acfg.get("use_rslora")),
284
+ "targets": sorted(acfg.get("target_modules") or []), "merged_weights": len(lora)},
285
+ "md5": {"adapter_model.safetensors": md5(run / "adapter_model.safetensors"), "head.pt": md5(run / "head.pt"),
286
+ "adapter_config.json": md5(run / "adapter_config.json"),
287
+ **{f"base/{sh}": md5(base / sh) for sh in shards}},
288
+ "kev_weights_dtype": meta.get("weights_dtype"), "training_args": meta.get("args"),
289
+ "temperature_fit": meta.get("temperature_fit"), "suite_sha256": meta.get("suite_sha256")},
290
+ "conversion": {"verdin_version": VERDIN_VERSION, "time_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
291
+ "torch": torch.__version__, "checks": checks, "seconds": round(time.time() - t0, 1)},
292
+ }
293
+ (out / CONFIG_NAME).write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
294
+ print(f"wrote {out} ({a.dtype}, {time.time() - t0:.0f} s)", flush=True)
295
+
296
+
297
+ if __name__ == "__main__":
298
+ main()
verdin/core.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Python API.
2
+
3
+ from verdin import Verdin
4
+ v = Verdin.from_pretrained("runs/verdin-4b-s1") # CUDA if available, MLX on Apple silicon, else CPU
5
+ v.decide("The parcel arrived broken.", {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}})
6
+ # -> {"damaged": {"type": "noul", "noul": 0.97}}
7
+
8
+ Backends: "cuda" / "cpu" (torch_backend.py), "mlx" (mlx_backend.py, Apple silicon; what "auto" picks on a Mac with mlx
9
+ installed). The renderer and the answer formatting are backend-independent (render.py, answers.py).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+
15
+ from .answers import answers as format_answers
16
+ from .answers import softmax
17
+ from .config import VerdinConfig
18
+ from .render import Encoded, Renderer, RenderConfig, RequestError, Tokenizer
19
+
20
+ # 11-09 submission calibration: the board-style SGD intent requests carry an all-caps "NONE" option that the model
21
+ # over-selects (90.9% of questions answered NONE on our sgd-board-cat10 probe, acc 12.3). Scaling that option's
22
+ # probability by KEV_NONE_MULT before the argmax lifts the probe to 65.8 at c=0.2 (none_rate -> 0) and touches nothing
23
+ # else: no other eval corpus in our scan (po2/s-40/ss/phish/heldout suite) uses an exact "NONE" key -- they use
24
+ # 'none' / 'neither' / 'none_of_these' / 'Not known' / "Can't be determined". Default 1.0 = off (historical evals
25
+ # unchanged); the submission package sets KEV_NONE_MULT=0.2.
26
+ NONE_MULT = float(os.environ.get("KEV_NONE_MULT", "1.0"))
27
+ # temperature-compensated form: the multiplier as an EFFECTIVE probability ratio, applied as delta = T*ln(ratio)
28
+ NONE_MULT_EFF = float(os.environ.get("KEV_NONE_MULT_EFF", "0"))
29
+ NONE_KEY = "NONE"
30
+
31
+
32
+ def _scale_none(enc: Encoded, probs: list[list[float]], mult: float) -> list[list[float]]:
33
+ """Multiply the probability of an exact "NONE" option (if the question has one) and renormalise the options."""
34
+ out = [list(p) for p in probs]
35
+ for q, p in zip(enc.questions, out):
36
+ try:
37
+ keys = q.keys
38
+ except Exception:
39
+ continue
40
+ if NONE_KEY in keys:
41
+ j = keys.index(NONE_KEY)
42
+ if 0 <= j < len(p):
43
+ p[j] *= mult
44
+ s = sum(p)
45
+ if s > 0:
46
+ for k in range(len(p)):
47
+ p[k] /= s
48
+ return out
49
+
50
+
51
+ def _shift_none_logits(enc: Encoded, logits: list, mult: float, T: float = 1.0) -> list:
52
+ """Apply log(mult) to an exact "NONE" option's LOGIT (temperature-independent calibration, unlike scaling the
53
+ post-softmax probability: with the served head temperature T=0.32 a probability scale of 0.2 acts like a logit
54
+ shift of only -0.51 instead of log(0.2)=-1.61)."""
55
+ import math
56
+ delta = T * math.log(mult)
57
+ out = []
58
+ for q, z in zip(enc.questions, logits):
59
+ z = list(z)
60
+ try:
61
+ keys = q.keys
62
+ except Exception:
63
+ out.append(z)
64
+ continue
65
+ if NONE_KEY in keys:
66
+ j = keys.index(NONE_KEY)
67
+ if 0 <= j < len(z):
68
+ z[j] += delta
69
+ out.append(z)
70
+ return out
71
+
72
+
73
+ def mlx_available() -> bool:
74
+ """Apple silicon with mlx importable and Metal up."""
75
+ import platform
76
+ import sys
77
+ if sys.platform != "darwin" or platform.machine() != "arm64":
78
+ return False
79
+ try:
80
+ import mlx.core as mx
81
+ return bool(mx.metal.is_available())
82
+ except Exception: # noqa: BLE001 - any import failure: no MLX backend
83
+ return False
84
+
85
+
86
+ def pick_backend(backend: str | None, device: str | None = None) -> str:
87
+ b = (backend or "auto").lower()
88
+ if b == "mlx" or (b == "auto" and not device and mlx_available()):
89
+ return "mlx"
90
+ if b in ("torch", "auto"):
91
+ if device:
92
+ return "cuda" if str(device).startswith("cuda") else "cpu"
93
+ try:
94
+ import torch
95
+ return "cuda" if torch.cuda.is_available() else "cpu"
96
+ except ImportError:
97
+ raise RuntimeError("no backend: install torch (CUDA or CPU)") from None
98
+ if b not in ("cuda", "cpu"):
99
+ raise ValueError(f"unknown backend {backend!r} (auto | cuda | cpu | mlx)")
100
+ return b
101
+
102
+
103
+ class Verdin:
104
+ def __init__(self, cfg: VerdinConfig, renderer: Renderer, engine, backend: str):
105
+ self.cfg, self.renderer, self.engine, self.backend = cfg, renderer, engine, backend
106
+ self.name = cfg.model_name
107
+ self.temperature = cfg.temperature
108
+
109
+ @classmethod
110
+ def from_pretrained(cls, path, backend: str = "auto", device: str | None = None, dtype: str | None = None,
111
+ warmup: bool = False, **options):
112
+ """Load a converted checkpoint directory. `options` are TorchOptions fields (prefill_chunk, max_sweep_tokens,
113
+ prefix_cache, gdr, conv, ...) or, for backend "mlx", MLXOptions fields (torch-only ones are ignored there)."""
114
+ cfg = VerdinConfig.load(path)
115
+ tok = Tokenizer(cfg.file(cfg.tokenizer["file"]), cfg.tokenizer["specials"])
116
+ renderer = Renderer(tok, RenderConfig.from_dict(cfg.render))
117
+ b = pick_backend(backend, device)
118
+ if b == "mlx":
119
+ from .mlx_backend import MLXEngine, MLXOptions
120
+ engine = MLXEngine.load(cfg, MLXOptions.from_kwargs(dtype=dtype or "auto", **options))
121
+ else:
122
+ from .torch_backend import TorchEngine, TorchOptions
123
+ opts = TorchOptions(device=device or b, dtype=dtype or "auto", **options)
124
+ engine = TorchEngine.load(cfg, opts)
125
+ if warmup:
126
+ engine.warmup()
127
+ return cls(cfg, renderer, engine, b)
128
+
129
+ # -- requests -----------------------------------------------------------------------------------------------------
130
+
131
+ def encode(self, request: dict) -> Encoded:
132
+ """A /v1/systemone request body ({"state", "questions"}) -> Encoded (RequestError / Unsupported if refused)."""
133
+ return self.renderer.encode_request(request)
134
+
135
+ def run(self, encs: list[Encoded]):
136
+ return self.engine.run(encs)
137
+
138
+ def probabilities(self, enc: Encoded, result, temperature: float | None = None):
139
+ """-> (per-question option probabilities, per-question p(unknown) or None)."""
140
+ T = self.temperature if temperature is None else temperature
141
+ if NONE_MULT_EFF > 0:
142
+ logits = _shift_none_logits(enc, result.logits, NONE_MULT_EFF, T)
143
+ elif NONE_MULT != 1.0:
144
+ logits = _shift_none_logits(enc, result.logits, NONE_MULT, 1.0)
145
+ else:
146
+ logits = result.logits
147
+ probs = [softmax(z, T) for z in logits]
148
+ unk = None
149
+ if result.unknown is not None:
150
+ unk = [softmax(list(z) + [u], T)[-1] for z, u in zip(result.logits, result.unknown)]
151
+ return probs, unk
152
+
153
+ def answers(self, enc: Encoded, result, temperature: float | None = None) -> dict:
154
+ probs, unk = self.probabilities(enc, result, temperature)
155
+ return format_answers(enc.questions, probs, unk)
156
+
157
+ def decide(self, state, questions: dict, temperature: float | None = None) -> dict:
158
+ """One request -> its answers object (TypeSafe wire format). Raises RequestError / Unsupported if refused."""
159
+ enc = self.encode({"state": state, "questions": questions})
160
+ res = self.run([enc])[0]
161
+ if res.error is not None:
162
+ raise res.error
163
+ return self.answers(enc, res, temperature)
164
+
165
+ def decide_batch(self, requests: list[dict], temperature: float | None = None, batch_size: int = 32) -> list:
166
+ """Many request bodies in batched passes; each item is an answers dict or the RequestError that refused it."""
167
+ out, encs, where = [None] * len(requests), [], []
168
+ for i, body in enumerate(requests):
169
+ try:
170
+ encs.append(self.encode(body)); where.append(i)
171
+ except RequestError as e:
172
+ out[i] = e
173
+ for s in range(0, len(encs), batch_size):
174
+ part = encs[s:s + batch_size]
175
+ for j, (enc, res) in enumerate(zip(part, self.run(part))):
176
+ out[where[s + j]] = res.error if res.error is not None else self.answers(enc, res, temperature)
177
+ return out
178
+
179
+ def info(self) -> dict:
180
+ c = self.cfg
181
+ return {"id": self.name, "backend": self.backend, "engine": self.engine.describe(), "render": c.render,
182
+ "temperature": self.temperature, "weights_dtype": c.weights.get("dtype"),
183
+ "source": {k: c.raw.get("source", {}).get(k) for k in ("kev_run", "base", "base_revision")},
184
+ "format_version": c.raw.get("format_version")}
verdin/engine.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend-independent execution plan: requests -> sweeps -> flat token layouts (plain Python, no torch).
2
+
3
+ Every backend (torch now, MLX next) runs the same plans; it only implements `BaseEngine.execute(layout)` (one pass over
4
+ the layers for one Layout, returning the readout logits) and a few hooks. Shared here:
5
+ - the prefix state of a request (per-layer tensors live in it, whatever the backend's tensor type),
6
+ - the prefix cache (LRU across requests) and de-duplication of identical states inside a batch,
7
+ - sweep planning: prefill segments (long states split into prefill_chunk pieces, one piece per state per sweep)
8
+ and branch rows packed into passes of at most max_tokens tokens / max_rows rows,
9
+ - the flat layout of a sweep: token ids and positions, varlen boundaries, the causal-conv gather indices (each row
10
+ sees its request's last 3 pre-conv state tokens), readout indices,
11
+ - state lifetime (freed after its last sweep unless the cache keeps it) and the out-of-memory policy (retry one by
12
+ one; refuse only a request that does not fit alone).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ from array import array
18
+ from collections import OrderedDict
19
+ from dataclasses import dataclass, field
20
+
21
+ from .render import Encoded, Unsupported
22
+
23
+
24
+ class PrefixState:
25
+ """Everything the branches of one state need, per layer index: attention K/V, DeltaNet recurrent state, conv tail
26
+ (backend tensors). `n` = state tokens, `done` = state tokens processed so far."""
27
+
28
+ def __init__(self, n):
29
+ self.n, self.done = n, 0
30
+ self.kv, self.rec, self.tail = {}, {}, {}
31
+
32
+ def clear(self):
33
+ self.kv.clear(); self.rec.clear(); self.tail.clear()
34
+
35
+
36
+ class Req:
37
+ def __init__(self, enc: Encoded):
38
+ self.enc = enc
39
+ self.state = None
40
+ self.prefill = True # False: the state comes from the cache or from a duplicate earlier in the batch
41
+ self.key = None
42
+ self.hit = False
43
+ self.logits = [None] * len(enc.rows)
44
+ self.unknown = [None] * len(enc.rows)
45
+
46
+
47
+ @dataclass
48
+ class RunResult:
49
+ logits: list | None # per question: raw option logits (temperature 1)
50
+ unknown: list | None # per question: raw unknown logit, if the head has one
51
+ cache_hit: bool = False
52
+ error: Exception | None = None # set (logits None) when this request alone does not fit the device
53
+
54
+
55
+ class Sweep:
56
+ def __init__(self):
57
+ self.prefill, self.rows, self.tokens, self.n_rows, self.with_pre = [], [], 0, 0, set()
58
+ self.index, self.last_use = 0, {}
59
+
60
+
61
+ @dataclass
62
+ class Layout:
63
+ """One sweep as flat lists. Token order: every prefill segment, then every branch row (rows of a request
64
+ contiguous). `src` indices refer to [carried tails of the involved states (3 per state) ; the sweep's tokens]."""
65
+ ids: list = field(default_factory=list)
66
+ pos: list = field(default_factory=list)
67
+ involved: list = field(default_factory=list) # PrefixStates touched (requests sharing a state share one)
68
+ all_fresh: bool = True # every involved state starts in this sweep (zero history)
69
+ persist: dict = field(default_factory=dict) # id(state) -> must outlive this sweep (later sweep or cache)
70
+ pre_segs: list = field(default_factory=list) # (state, a, b, flat start)
71
+ pre_states: list = field(default_factory=list)
72
+ pre_fresh: list = field(default_factory=list)
73
+ involved_is_pre: bool = False # involved == pre_states (rows can take the prefill's final states)
74
+ n_pre: int = 0
75
+ cu_pre: list = field(default_factory=lambda: [0])
76
+ tail_idx: list = field(default_factory=list) # src indices of each prefill state's new conv tail (3 each)
77
+ row_blocks: list = field(default_factory=list) # (state, flat start, [row lengths])
78
+ cu_rows: list = field(default_factory=lambda: [0])
79
+ row_inv: list = field(default_factory=list) # per row: index into `involved`
80
+ conv: list = field(default_factory=list) # conv[j]: src index of tap j for each token (token t - (k-1-j))
81
+ ext: list = field(default_factory=list) # [history ; tokens] per segment / row (fused-conv kernels)
82
+ ext_out: list = field(default_factory=list) # position in `ext` of each token
83
+ dec: list = field(default_factory=list) # flat index of each row's <decide>
84
+ opt: list = field(default_factory=list) # flat index of each option's </opt>
85
+ opt_row: list = field(default_factory=list) # row of each option
86
+ row_refs: list = field(default_factory=list) # (Req, question index, n options) per row
87
+
88
+
89
+ def state_key(ids):
90
+ return hashlib.blake2b(array("i", ids).tobytes(), digest_size=16).digest()
91
+
92
+
93
+ def plan_sweeps(reqs, prefill_chunk, max_tokens, max_rows):
94
+ sweeps, cur = [], Sweep()
95
+
96
+ def flush():
97
+ nonlocal cur
98
+ if cur.prefill or cur.rows:
99
+ sweeps.append(cur)
100
+ cur = Sweep()
101
+ for r in reqs:
102
+ if r.prefill:
103
+ a, n = r.state.done, r.enc.n_state
104
+ while a < n:
105
+ b = min(n, a + prefill_chunk)
106
+ if id(r.state) in cur.with_pre or (cur.tokens and cur.tokens + (b - a) > max_tokens):
107
+ flush()
108
+ cur.prefill.append((r, a, b)); cur.tokens += b - a; cur.with_pre.add(id(r.state))
109
+ a = b
110
+ for qi, row in enumerate(r.enc.rows):
111
+ if cur.tokens and (cur.tokens + len(row.ids) > max_tokens or cur.n_rows + 1 > max_rows):
112
+ flush()
113
+ cur.rows.append((r, qi)); cur.tokens += len(row.ids); cur.n_rows += 1
114
+ flush()
115
+ last = {}
116
+ for k, sw in enumerate(sweeps):
117
+ for r, _, _ in sw.prefill: last[id(r.state)] = k
118
+ for r, _ in sw.rows: last[id(r.state)] = k
119
+ for k, sw in enumerate(sweeps):
120
+ sw.index, sw.last_use = k, last
121
+ return sweeps
122
+
123
+
124
+ def build_layout(sw: Sweep, kconv: int, keep=frozenset()) -> Layout:
125
+ L = Layout()
126
+ inv = {}
127
+ for r, _, _ in sw.prefill:
128
+ if id(r.state) not in inv: inv[id(r.state)] = len(L.involved); L.involved.append(r.state)
129
+ for r, _ in sw.rows:
130
+ if id(r.state) not in inv: inv[id(r.state)] = len(L.involved); L.involved.append(r.state)
131
+ L.all_fresh = all(st.done == 0 for st in L.involved)
132
+ L.persist = {id(st): id(st) in keep or sw.last_use[id(st)] > sw.index for st in L.involved}
133
+ km1 = kconv - 1
134
+ T0 = km1 * len(L.involved)
135
+ hist = {j: list(range(km1 * j, km1 * (j + 1))) for j in range(len(L.involved))}
136
+ L.conv = [[] for _ in range(kconv)]
137
+
138
+ def add_segment(H, f0, n):
139
+ toks = list(range(T0 + f0, T0 + f0 + n))
140
+ e = H[-km1:] + toks
141
+ for j in range(kconv):
142
+ L.conv[j].extend(e[j: j + n])
143
+ base = len(L.ext)
144
+ L.ext.extend(e); L.ext_out.extend(range(base + km1, base + km1 + n))
145
+ return toks
146
+ for r, a, b in sw.prefill:
147
+ j = inv[id(r.state)]; f0 = len(L.ids)
148
+ L.ids.extend(r.enc.state_ids[a:b]); L.pos.extend(range(a, b))
149
+ toks = add_segment(hist[j], f0, b - a)
150
+ hist[j] = (hist[j] + toks)[-km1:]
151
+ L.pre_segs.append((r.state, a, b, f0)); L.pre_states.append(r.state); L.pre_fresh.append(a == 0)
152
+ L.cu_pre.append(L.cu_pre[-1] + b - a)
153
+ L.n_pre = len(L.ids)
154
+ L.involved_is_pre = len(L.pre_states) == len(L.involved)
155
+ L.tail_idx = [x for st in L.pre_states for x in hist[inv[id(st)]]]
156
+ for r, qi in sw.rows:
157
+ row = r.enc.rows[qi]; f0 = len(L.ids); n = len(row.ids)
158
+ if not L.row_blocks or L.row_blocks[-1][0] is not r.state or L.row_blocks[-1][3] is not r:
159
+ L.row_blocks.append([r.state, f0, [], r])
160
+ L.row_blocks[-1][2].append(n)
161
+ L.ids.extend(row.ids); L.pos.extend(range(r.enc.n_state, r.enc.n_state + n))
162
+ add_segment(hist[inv[id(r.state)]], f0, n)
163
+ L.row_inv.append(inv[id(r.state)]); L.cu_rows.append(L.cu_rows[-1] + n)
164
+ L.dec.append(f0 + row.decide)
165
+ L.opt.extend(f0 + o for o in row.opts); L.opt_row.extend([len(L.row_refs)] * len(row.opts))
166
+ L.row_refs.append((r, qi, len(row.opts)))
167
+ L.row_blocks = [(st, f0, lens) for st, f0, lens, _ in L.row_blocks]
168
+ return L
169
+
170
+
171
+ class BaseEngine:
172
+ """Batches of Encoded requests -> raw logits. A backend implements execute(layout) -> (option logits flat list,
173
+ unknown logits per row or None), plus prefill_chunk / max_tokens / max_rows / kconv / unknown attributes, and may
174
+ override oom_errors, on_oom(), sync(), describe_backend(). Single-threaded: the server's batcher thread owns it."""
175
+
176
+ oom_errors: tuple = ()
177
+
178
+ def __init__(self, prefix_cache=4, prefix_cache_min_tokens=384, prefix_cache_max_tokens=262144):
179
+ self.cache = OrderedDict()
180
+ self.cache_tokens = 0
181
+ self.hits = self.misses = 0
182
+ self.cache_size, self.cache_min, self.cache_max = prefix_cache, prefix_cache_min_tokens, prefix_cache_max_tokens
183
+
184
+ # -- backend hooks --------------------------------------------------------------------------------------------
185
+ def execute(self, layout: Layout):
186
+ raise NotImplementedError
187
+
188
+ def on_oom(self):
189
+ pass
190
+
191
+ def sync(self):
192
+ pass
193
+
194
+ def describe_backend(self) -> dict:
195
+ return {}
196
+
197
+ # -- shared ---------------------------------------------------------------------------------------------------
198
+ def describe(self):
199
+ return {**self.describe_backend(), "prefix_cache": {"size": self.cache_size, "min_state_tokens": self.cache_min,
200
+ "max_tokens": self.cache_max, "cached_states": len(self.cache),
201
+ "hits": self.hits, "misses": self.misses}}
202
+
203
+ def _run(self, reqs, keep):
204
+ for sw in plan_sweeps(reqs, self.prefill_chunk, self.max_tokens, self.max_rows):
205
+ layout = build_layout(sw, self.kconv, keep)
206
+ z, zu = self.execute(layout)
207
+ for r, a, b in sw.prefill:
208
+ r.state.done = b
209
+ for st in layout.involved: # free what no later sweep and no cache entry needs
210
+ if not layout.persist[id(st)]:
211
+ st.clear()
212
+ if z is None:
213
+ continue
214
+ k = 0
215
+ for j, (r, qi, K) in enumerate(layout.row_refs):
216
+ r.logits[qi] = z[k:k + K]; k += K
217
+ if zu is not None:
218
+ r.unknown[qi] = zu[j]
219
+
220
+ def run(self, encs: list[Encoded]) -> list[RunResult]:
221
+ reqs = [Req(e) for e in encs]
222
+ fresh = {}
223
+ for r in reqs:
224
+ r.key = key = state_key(r.enc.state_ids)
225
+ if key in self.cache:
226
+ st = self.cache.pop(key); self.cache[key] = st # LRU touch
227
+ r.state, r.prefill, r.hit = st, False, True; self.hits += 1
228
+ elif key in fresh:
229
+ r.state, r.prefill = fresh[key], False # same state earlier in this batch
230
+ else:
231
+ r.state = PrefixState(r.enc.n_state); fresh[key] = r.state
232
+ self.misses += 1
233
+ keep = frozenset(id(st) for st in fresh.values() if self.cache_size and self.cache_min <= st.n <= self.cache_max)
234
+ # a state taken from the cache must survive this batch too: _run frees every involved state whose last use is
235
+ # over unless it is in `keep`, and a cached state is never in `fresh` - without this its tensors were cleared
236
+ # while it stayed in the cache, and the next hit on it failed with KeyError in the first layer (10-09, DI SGD)
237
+ keep |= frozenset(id(r.state) for r in reqs if r.hit)
238
+ try:
239
+ self._run(reqs, keep)
240
+ except self.oom_errors:
241
+ for r in reqs:
242
+ r.state = None
243
+ fresh.clear()
244
+ self.on_oom()
245
+ if len(encs) > 1: # retry one by one: only the request(s) that do not fit alone are refused
246
+ return [self.run([e])[0] for e in encs]
247
+ e = encs[0]
248
+ return [RunResult(None, None, False, Unsupported(f"request exceeds this device's memory ({e.n_tokens} tokens; state {e.n_state})"))]
249
+ if self.cache_size:
250
+ for key, st in fresh.items():
251
+ if id(st) in keep and st.done == st.n:
252
+ self.cache[key] = st; self.cache_tokens += st.n
253
+ while self.cache and (len(self.cache) > self.cache_size or self.cache_tokens > self.cache_max):
254
+ _, st = self.cache.popitem(last=False); self.cache_tokens -= st.n
255
+ return [RunResult(r.logits, r.unknown if self.unknown else None, r.hit) for r in reqs]
256
+
257
+ def warmup(self):
258
+ """Exercise the kernels on a few shapes (Triton kernels compile/autotune on first use)."""
259
+ from .render import Row
260
+ rows = [Row(list(range(2000, 2012)), 11, [3, 7]), Row(list(range(3000, 3009)), 8, [2, 5])]
261
+ for n in (17, 300, self.prefill_chunk + 64): # short, medium, and a two-chunk prefill (carried states)
262
+ e = Encoded([1000 + (t % 5000) for t in range(n)], rows)
263
+ self.run([e, e] if n < 1000 else [e])
264
+ self.cache.clear(); self.cache_tokens = 0; self.hits = self.misses = 0
265
+ self.sync()
verdin/mlx_backend.py ADDED
@@ -0,0 +1,947 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verdin MLX backend: the Qwen3.5 hybrid backbone + pointer head on Apple silicon (Metal), for prefill-only decisions.
2
+
3
+ It executes the same backend-independent plans as the torch backend (engine.py: sweeps, flat layouts, prefix states,
4
+ prefix cache, de-duplication, out-of-memory policy); only `execute(layout)` is MLX. Runtime dependencies: `mlx`, `numpy`
5
+ and `tokenizers` (render.py); weights are read with `mx.load`. No torch, transformers, mlx-lm or kev.
6
+
7
+ from verdin.mlx_backend import load_verdin
8
+ v = load_verdin("/Users/me/models/verdin-4b") # a verdin.core.Verdin on the MLX engine
9
+ v.decide("The mug arrived broken.", {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}})
10
+
11
+ python -m verdin.mlx_backend --model DIR [verdin.server flags] # the HTTP server on MLX (until the core hook lands)
12
+
13
+ How one sweep runs on Metal (mirrors torch_backend.py)
14
+ ------------------------------------------------------
15
+ - one bf16 GEMM per projection over every token of the sweep (fused q/k/v/z/b/a, fused q|gate/k/v, fused gate/up);
16
+ the LoRA is merged at conversion,
17
+ - residual stream, every norm / gate / softmax, RoPE and the causal-conv accumulation in fp32,
18
+ - Gated DeltaNet: a varlen Metal kernel (one launch for all prefill segments, carrying each state's recurrent state
19
+ in and out, one launch for all branch rows, each row starting from its request's state by index: nothing is
20
+ replicated per question). The kernel is mlx-lm's packed gated-delta kernel made varlen; it keeps q/k/v and the
21
+ state in fp32,
22
+ - causal conv + SiLU: one Metal kernel reading [carried tails ; tokens] by index (each row sees its request's last 3
23
+ pre-conv state tokens), fp32 accumulation,
24
+ - the elementwise chains (residual add + RMSNorm, SwiGLU, q/k L2 norm, gates, gated RMSNorm, attention gate) are
25
+ fused with mx.compile (shapeless: no recompilation as the token count changes),
26
+ - full attention: mx.fast.scaled_dot_product_attention (fused, no score matrix). A prefill segment attends its
27
+ state's K/V so far (bottom-right causal; state-bidirectional checkpoints: also the later keys of its own block,
28
+ mask-free when the segment is one block); all rows of a request attend [prefix K/V ; own row] under one
29
+ block-diagonal mask, so the prefix K/V is read once per request. Precision per state: fp32 q/K/V for states of up
30
+ to attn_fp32_max_state (4,096) tokens, bf16 above (fp32 halves the drift from the fp32 model; the bf16 kernel is
31
+ ~3x faster, which matters on long states only),
32
+ - the last layer's MLP / final norm / pointer head run on the readout tokens only; the pointer head runs in fp32 on
33
+ the CPU stream (tiny; exact fp32 whatever the GPU's GEMM precision mode).
34
+ MLX evaluates lazily and an unevaluated array cannot be evaluated from another thread, so every MLX call (loading,
35
+ planning + execution, cache frees) runs on one dedicated thread owned by the engine; `run()` hands work to it.
36
+
37
+ The gated-delta kernels are adapted from mlx-lm (mlx_lm/models/gated_delta.py, MIT License, Copyright (c) 2023 Apple
38
+ Inc.): made varlen (cu_seqlens), the initial state taken by index, the final state optional, fp32 inputs.
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import math
43
+ import os
44
+ import threading
45
+ from concurrent.futures import ThreadPoolExecutor
46
+ from dataclasses import dataclass, fields
47
+
48
+ # MLX runs fp32 GEMMs and fp32 attention as TF32 on GPUs with neural accelerators (M5: ~7e-4 relative error in a GEMM)
49
+ # unless this is "0". Verdin's bf16 GEMMs are unaffected; its fp32 attention (default for states up to 4,096 tokens) and
50
+ # --dtype fp32 must stay fp32. Set before MLX's first use.
51
+ os.environ.setdefault("MLX_ENABLE_TF32", "0")
52
+
53
+ import mlx.core as mx # noqa: E402
54
+ import numpy as np # noqa: E402
55
+
56
+ from .config import Arch, VerdinConfig
57
+ from .engine import BaseEngine, RunResult # noqa: F401 - RunResult re-exported for callers of this module
58
+
59
+ GiB = 1 << 30
60
+
61
+
62
+ # ---------------------------------------------------------------------------------------------------------------------
63
+ # Gated DeltaNet kernels (varlen). Layout: q, k [T, Hk, Dk]; v [T, Hv, Dv]; g (decay multiplier, exp of the log-gate)
64
+ # and beta [T, Hv]; states [S, Hv, Dv, Dk] fp32. Sequence s covers flat tokens cu[s] .. cu[s+1]-1 and starts from
65
+ # state_in[sidx[s]] (zeros when sidx[s] < 0). q is L2-normalised and pre-scaled by Dk^-0.5, k is L2-normalised.
66
+
67
+ _GDR_PACKED = r"""
68
+ // Dk == 128: 8 value rows per SIMD-group, 4 lanes per row, 32 state elements per lane (mlx-lm's packed kernel).
69
+ constexpr int lanes_per_row = 4;
70
+ constexpr int rows_per_simdgroup = 32 / lanes_per_row;
71
+ constexpr int values_per_lane = Dk / lanes_per_row;
72
+ constexpr int partials_per_lane = values_per_lane / 4;
73
+
74
+ uint n = thread_position_in_grid.z;
75
+ uint s = n / Hv;
76
+ uint hv = n % Hv;
77
+ uint hk = hv / (Hv / Hk);
78
+ uint lane = thread_index_in_simdgroup;
79
+ uint lane_in_row = lane & (lanes_per_row - 1);
80
+ uint dv = thread_position_in_grid.y * rows_per_simdgroup + lane / lanes_per_row;
81
+
82
+ int t0 = cu[s];
83
+ int t1 = cu[s + 1];
84
+ int src = sidx[s];
85
+
86
+ float st[values_per_lane];
87
+ if (src >= 0) {
88
+ auto p = state_in + ((size_t(src) * Hv + hv) * Dv + dv) * Dk + lane_in_row * values_per_lane;
89
+ for (int i = 0; i < values_per_lane; ++i) st[i] = static_cast<float>(p[i]);
90
+ } else {
91
+ for (int i = 0; i < values_per_lane; ++i) st[i] = 0.0f;
92
+ }
93
+ auto q_ = q + (size_t(t0) * Hk + hk) * Dk + lane_in_row * values_per_lane;
94
+ auto k_ = k + (size_t(t0) * Hk + hk) * Dk + lane_in_row * values_per_lane;
95
+ auto v_ = v + (size_t(t0) * Hv + hv) * Dv;
96
+ auto y_ = y + (size_t(t0) * Hv + hv) * Dv;
97
+ auto g_ = g + size_t(t0) * Hv;
98
+ auto b_ = beta + size_t(t0) * Hv;
99
+
100
+ for (int t = t0; t < t1; ++t) {
101
+ float gt = static_cast<float>(g_[hv]);
102
+ float part[partials_per_lane];
103
+ for (int pb = 0; pb < partials_per_lane; ++pb) {
104
+ float acc = 0.0f;
105
+ for (int i = 0; i < 4; ++i) {
106
+ int e = pb * 4 + i;
107
+ st[e] = st[e] * gt;
108
+ acc += st[e] * static_cast<float>(k_[e]);
109
+ }
110
+ part[pb] = acc;
111
+ }
112
+ float kv_mem = ((part[0] + part[1]) + (part[2] + part[3])) + ((part[4] + part[5]) + (part[6] + part[7]));
113
+ kv_mem += simd_shuffle_xor(kv_mem, 1);
114
+ kv_mem += simd_shuffle_xor(kv_mem, 2);
115
+ float delta = (static_cast<float>(v_[dv]) - kv_mem) * static_cast<float>(b_[hv]);
116
+ for (int pb = 0; pb < partials_per_lane; ++pb) {
117
+ float acc = 0.0f;
118
+ for (int i = 0; i < 4; ++i) {
119
+ int e = pb * 4 + i;
120
+ st[e] = st[e] + static_cast<float>(k_[e]) * delta;
121
+ acc += st[e] * static_cast<float>(q_[e]);
122
+ }
123
+ part[pb] = acc;
124
+ }
125
+ float out = ((part[0] + part[1]) + (part[2] + part[3])) + ((part[4] + part[5]) + (part[6] + part[7]));
126
+ out += simd_shuffle_xor(out, 1);
127
+ out += simd_shuffle_xor(out, 2);
128
+ if (lane_in_row == 0) {
129
+ y_[dv] = out;
130
+ }
131
+ q_ += Hk * Dk;
132
+ k_ += Hk * Dk;
133
+ v_ += Hv * Dv;
134
+ y_ += Hv * Dv;
135
+ g_ += Hv;
136
+ b_ += Hv;
137
+ }
138
+ if (WRITE) {
139
+ auto o = state_out + ((size_t(s) * Hv + hv) * Dv + dv) * Dk + lane_in_row * values_per_lane;
140
+ for (int i = 0; i < values_per_lane; ++i) o[i] = st[i];
141
+ }
142
+ """
143
+
144
+ _GDR_SCALAR = r"""
145
+ // any Dk: one thread per (sequence, value head, value row), the Dk state elements in registers.
146
+ uint n = thread_position_in_grid.z;
147
+ uint s = n / Hv;
148
+ uint hv = n % Hv;
149
+ uint hk = hv / (Hv / Hk);
150
+ uint dv = thread_position_in_grid.x;
151
+ if (dv >= Dv) return;
152
+ int t0 = cu[s];
153
+ int t1 = cu[s + 1];
154
+ int src = sidx[s];
155
+ float st[Dk];
156
+ for (int i = 0; i < Dk; ++i)
157
+ st[i] = src >= 0 ? static_cast<float>(state_in[((size_t(src) * Hv + hv) * Dv + dv) * Dk + i]) : 0.0f;
158
+ for (int t = t0; t < t1; ++t) {
159
+ auto q_ = q + (size_t(t) * Hk + hk) * Dk;
160
+ auto k_ = k + (size_t(t) * Hk + hk) * Dk;
161
+ float gt = static_cast<float>(g[size_t(t) * Hv + hv]);
162
+ float kv_mem = 0.0f;
163
+ for (int i = 0; i < Dk; ++i) {
164
+ st[i] = st[i] * gt;
165
+ kv_mem += st[i] * static_cast<float>(k_[i]);
166
+ }
167
+ float delta = (static_cast<float>(v[(size_t(t) * Hv + hv) * Dv + dv]) - kv_mem) * static_cast<float>(beta[size_t(t) * Hv + hv]);
168
+ float out = 0.0f;
169
+ for (int i = 0; i < Dk; ++i) {
170
+ st[i] = st[i] + static_cast<float>(k_[i]) * delta;
171
+ out += st[i] * static_cast<float>(q_[i]);
172
+ }
173
+ y[(size_t(t) * Hv + hv) * Dv + dv] = out;
174
+ }
175
+ if (WRITE) {
176
+ for (int i = 0; i < Dk; ++i) state_out[((size_t(s) * Hv + hv) * Dv + dv) * Dk + i] = st[i];
177
+ }
178
+ """
179
+
180
+ _GDR_SIMD = r"""
181
+ // Dk % 32 == 0: one SIMD-group per (sequence, value head, value row), Dk/32 state elements per lane (mlx-lm's
182
+ // generic kernel). 8x the SIMD-groups of the packed kernel: better for a few long prefill segments.
183
+ constexpr int n_per_t = Dk / 32;
184
+ uint n = thread_position_in_grid.z;
185
+ uint s = n / Hv;
186
+ uint hv = n % Hv;
187
+ uint hk = hv / (Hv / Hk);
188
+ uint dk_idx = thread_position_in_threadgroup.x;
189
+ uint dv = thread_position_in_grid.y;
190
+ int t0 = cu[s];
191
+ int t1 = cu[s + 1];
192
+ int src = sidx[s];
193
+ float st[n_per_t];
194
+ for (int i = 0; i < n_per_t; ++i) {
195
+ uint e = n_per_t * dk_idx + i;
196
+ st[i] = src >= 0 ? static_cast<float>(state_in[((size_t(src) * Hv + hv) * Dv + dv) * Dk + e]) : 0.0f;
197
+ }
198
+ auto q_ = q + (size_t(t0) * Hk + hk) * Dk;
199
+ auto k_ = k + (size_t(t0) * Hk + hk) * Dk;
200
+ auto v_ = v + (size_t(t0) * Hv + hv) * Dv;
201
+ auto y_ = y + (size_t(t0) * Hv + hv) * Dv;
202
+ auto g_ = g + size_t(t0) * Hv;
203
+ auto b_ = beta + size_t(t0) * Hv;
204
+ for (int t = t0; t < t1; ++t) {
205
+ float gt = static_cast<float>(g_[hv]);
206
+ float kv_mem = 0.0f;
207
+ for (int i = 0; i < n_per_t; ++i) {
208
+ uint e = n_per_t * dk_idx + i;
209
+ st[i] = st[i] * gt;
210
+ kv_mem += st[i] * static_cast<float>(k_[e]);
211
+ }
212
+ kv_mem = simd_sum(kv_mem);
213
+ float delta = (static_cast<float>(v_[dv]) - kv_mem) * static_cast<float>(b_[hv]);
214
+ float out = 0.0f;
215
+ for (int i = 0; i < n_per_t; ++i) {
216
+ uint e = n_per_t * dk_idx + i;
217
+ st[i] = st[i] + static_cast<float>(k_[e]) * delta;
218
+ out += st[i] * static_cast<float>(q_[e]);
219
+ }
220
+ out = simd_sum(out);
221
+ if (thread_index_in_simdgroup == 0) {
222
+ y_[dv] = out;
223
+ }
224
+ q_ += Hk * Dk;
225
+ k_ += Hk * Dk;
226
+ v_ += Hv * Dv;
227
+ y_ += Hv * Dv;
228
+ g_ += Hv;
229
+ b_ += Hv;
230
+ }
231
+ if (WRITE) {
232
+ for (int i = 0; i < n_per_t; ++i) {
233
+ uint e = n_per_t * dk_idx + i;
234
+ state_out[((size_t(s) * Hv + hv) * Dv + dv) * Dk + e] = st[i];
235
+ }
236
+ }
237
+ """
238
+
239
+ _KERNELS = {}
240
+
241
+
242
+ def _kernel(kind):
243
+ if kind not in _KERNELS:
244
+ src = {"packed": _GDR_PACKED, "simd": _GDR_SIMD, "scalar": _GDR_SCALAR}[kind]
245
+ _KERNELS[kind] = mx.fast.metal_kernel(name=f"verdin_gdr_varlen_{kind}",
246
+ input_names=["q", "k", "v", "g", "beta", "state_in", "cu", "sidx"],
247
+ output_names=["y", "state_out"], source=src)
248
+ return _KERNELS[kind]
249
+
250
+
251
+ def gdr_varlen_metal(q, k, v, g, beta, cu, sidx, state_in, n_seq, write_state, kind=None):
252
+ """-> (y [T, Hv, Dv] fp32, final states [n_seq, Hv, Dv, Dk] fp32 or None). `cu` int32 [n_seq + 1], `sidx` int32
253
+ [n_seq], `state_in` fp32 [*, Hv, Dv, Dk] (any array with >= 1 row when no sequence reads it). `kind`: packed (Dk 128;
254
+ 8 value rows per SIMD-group), simd (Dk % 32 == 0; a SIMD-group per value row), scalar (any Dk); default: packed when
255
+ it fits (fastest on an M5 Max for one 7.7k-token segment and for 64 short rows alike), else simd, else scalar."""
256
+ T, Hk, Dk = k.shape
257
+ Hv, Dv = v.shape[1], v.shape[2]
258
+ if kind is None:
259
+ kind = "packed" if Dk == 128 and Dv % 8 == 0 else ("simd" if Dk % 32 == 0 else "scalar")
260
+ if kind == "packed":
261
+ grid, tg = (32, Dv // 8, n_seq * Hv), (32, 2 if (Dv // 8) % 2 == 0 else 1, 1)
262
+ elif kind == "simd":
263
+ grid, tg = (32, Dv, n_seq * Hv), (32, 4 if Dv % 4 == 0 else 1, 1)
264
+ else:
265
+ grid, tg = (Dv, 1, n_seq * Hv), (min(Dv, 64), 1, 1)
266
+ y, fin = _kernel(kind)(
267
+ inputs=[q, k, v, g, beta, state_in, cu, sidx],
268
+ template=[("Dk", Dk), ("Dv", Dv), ("Hk", Hk), ("Hv", Hv), ("WRITE", int(bool(write_state)))],
269
+ grid=grid, threadgroup=tg,
270
+ output_shapes=[(T, Hv, Dv), (n_seq, Hv, Dv, Dk) if write_state else (1,)],
271
+ output_dtypes=[mx.float32, mx.float32])
272
+ return y, (fin if write_state else None)
273
+
274
+
275
+ def gdr_varlen_ops(q, k, v, g, beta, cu, sidx, state_in, n_seq, write_state):
276
+ """The same recurrence with plain MLX ops (any device; used on the CPU stream and by the tests). Sequences are
277
+ padded to the longest one; pads have g = 1 and beta = 0, so they neither decay nor write the state."""
278
+ cu_l = [int(x) for x in np.array(cu)]
279
+ sidx_l = [int(x) for x in np.array(sidx)]
280
+ T, Hk, Dk = k.shape
281
+ Hv, Dv = v.shape[1], v.shape[2]
282
+ rep = Hv // Hk
283
+ if rep > 1:
284
+ q = mx.repeat(q, rep, axis=1); k = mx.repeat(k, rep, axis=1)
285
+ lens = [cu_l[i + 1] - cu_l[i] for i in range(n_seq)]
286
+ Lm = max(lens) if lens else 0
287
+ idx = np.zeros((n_seq, max(Lm, 1)), dtype=np.int32)
288
+ valid = np.zeros((n_seq, max(Lm, 1)), dtype=bool)
289
+ for s, (a, n) in enumerate(zip(cu_l[:-1], lens)):
290
+ idx[s, :n] = np.arange(a, a + n); valid[s, :n] = True
291
+ idx_m, valid_m = mx.array(idx), mx.array(valid)
292
+ pad = lambda x: x[idx_m] # noqa: E731
293
+ qs, ks, vs = pad(q), pad(k), pad(v)
294
+ gs = mx.where(valid_m[..., None], pad(g), 1.0)
295
+ bs = mx.where(valid_m[..., None], pad(beta), 0.0)
296
+ init = [state_in[i] if i >= 0 else mx.zeros((Hv, Dv, Dk), dtype=mx.float32) for i in sidx_l]
297
+ S = mx.stack(init) if init else mx.zeros((0, Hv, Dv, Dk), dtype=mx.float32)
298
+ ys = []
299
+ for t in range(Lm):
300
+ S = S * gs[:, t][..., None, None]
301
+ kv_mem = (S * ks[:, t][:, :, None, :]).sum(-1)
302
+ delta = (vs[:, t] - kv_mem) * bs[:, t][..., None]
303
+ S = S + ks[:, t][:, :, None, :] * delta[..., None]
304
+ ys.append((S * qs[:, t][:, :, None, :]).sum(-1))
305
+ Y = mx.stack(ys, axis=1) if ys else mx.zeros((n_seq, 0, Hv, Dv), dtype=mx.float32)
306
+ y = mx.concatenate([Y[s, :n] for s, n in enumerate(lens)], axis=0) if n_seq else mx.zeros((0, Hv, Dv), dtype=mx.float32)
307
+ return y, (S if write_state else None)
308
+
309
+
310
+ # ---------------------------------------------------------------------------------------------------------------------
311
+ # Causal conv (width 4) + SiLU over [carried tails ; tokens], one thread per (token, channel). idx [4, N]: for tap j,
312
+ # the row of [tails (R rows) ; proj's first C columns] it reads; fp32 accumulation in kev's tap order (3, 2, 1, 0).
313
+
314
+ _CONV = r"""
315
+ uint c = thread_position_in_grid.x;
316
+ uint t = thread_position_in_grid.y;
317
+ if (c >= C) return;
318
+ float acc = 0.0f;
319
+ for (int j = 3; j >= 0; --j) {
320
+ int s = idx[size_t(j) * N + t];
321
+ float xv = s < R ? static_cast<float>(tails[size_t(s) * C + c])
322
+ : static_cast<float>(proj[size_t(s - R) * PS + c]);
323
+ acc = (j == 3) ? xv * w[j * C + c] : acc + xv * w[j * C + c];
324
+ }
325
+ out[size_t(t) * C + c] = acc / (1.0f + metal::precise::exp(-acc));
326
+ """
327
+
328
+
329
+ def conv_silu_metal(tails, proj, idx4, w4, C):
330
+ """-> silu(causal conv) [N, C] fp32. tails [R, C], proj [N, PS] (the conv input is its first C columns), idx4 int32
331
+ [4, N], w4 fp32 [4, C]."""
332
+ if "conv" not in _KERNELS:
333
+ _KERNELS["conv"] = mx.fast.metal_kernel(name="verdin_conv4_silu", input_names=["tails", "proj", "idx", "w", "R", "N"],
334
+ output_names=["out"], source=_CONV)
335
+ N, PS = proj.shape
336
+ return _KERNELS["conv"](inputs=[tails, proj, idx4, w4, tails.shape[0], N], template=[("C", C), ("PS", PS)],
337
+ grid=(C, N, 1), threadgroup=(256, 1, 1), output_shapes=[(N, C)], output_dtypes=[mx.float32])[0]
338
+
339
+
340
+ def conv_silu_ops(tails, proj, idx4, w4, C):
341
+ src = mx.concatenate([tails, proj[:, :C]], axis=0)
342
+ acc = src[idx4[3]].astype(mx.float32) * w4[3]
343
+ for j in (2, 1, 0):
344
+ acc = acc + src[idx4[j]].astype(mx.float32) * w4[j]
345
+ return acc * mx.sigmoid(acc)
346
+
347
+
348
+ def _compiled(eps, dt, dk, rot):
349
+ """The elementwise chains of a layer, each fused into one kernel by mx.compile (shape-independent)."""
350
+ comp = lambda f: mx.compile(f, shapeless=True) # noqa: E731
351
+
352
+ @comp
353
+ def add_norm(x, mix, w): # residual add (fp32) -> next pre-norm in the compute dtype
354
+ x = x + mix.astype(mx.float32)
355
+ return x, mx.fast.rms_norm(x, w, eps).astype(dt)
356
+
357
+ @comp
358
+ def norm(x, w):
359
+ return mx.fast.rms_norm(x, w, eps).astype(dt)
360
+
361
+ @comp
362
+ def swiglu(g, u):
363
+ g = g.astype(mx.float32)
364
+ return ((g * mx.sigmoid(g)) * u.astype(mx.float32)).astype(dt)
365
+
366
+ @comp
367
+ def l2qk(q, k): # fla's use_qk_l2norm_in_kernel (eps 1e-6) and the Dk^-0.5 query scale
368
+ q = q * mx.rsqrt((q * q).sum(-1, keepdims=True) + 1e-6) * (dk ** -0.5)
369
+ k = k * mx.rsqrt((k * k).sum(-1, keepdims=True) + 1e-6)
370
+ return q, k
371
+
372
+ @comp
373
+ def gates(a, b, negA, dt_bias): # beta = sigmoid(b); decay = exp(-exp(A_log) * softplus(a + dt_bias))
374
+ return mx.sigmoid(b.astype(mx.float32)), mx.exp(negA * mx.logaddexp(a.astype(mx.float32) + dt_bias, 0.0))
375
+
376
+ @comp
377
+ def gated_norm(y, w, z): # RMSNormGated: rms_norm(y) * w * silu(z), fp32 -> compute dtype
378
+ z = z.astype(mx.float32)
379
+ return (mx.fast.rms_norm(y, w, eps) * (z * mx.sigmoid(z))).astype(dt)
380
+
381
+ @comp
382
+ def norm32(x, w): # q/k zero-centred RMSNorm, fp32
383
+ return mx.fast.rms_norm(x.astype(mx.float32), w, eps)
384
+
385
+ def norm_rope(x, w, cos, sin): # ... then partial RoPE (rotate_half) on the first `rot` dims (slices: not shapeless)
386
+ x = norm32(x, w)
387
+ xr, rest = x[..., :rot], x[..., rot:]
388
+ r = mx.concatenate([-xr[..., rot // 2:], xr[..., : rot // 2]], axis=-1)
389
+ return mx.concatenate([xr * cos + r * sin, rest], axis=-1)
390
+
391
+ @comp
392
+ def attn_gate(o, gate):
393
+ return (o.astype(mx.float32) * mx.sigmoid(gate.astype(mx.float32))).astype(dt)
394
+
395
+ return add_norm, norm, swiglu, l2qk, gates, gated_norm, norm_rope, attn_gate
396
+
397
+
398
+ # ---------------------------------------------------------------------------------------------------------------------
399
+ # options
400
+
401
+ @dataclass
402
+ class MLXOptions:
403
+ dtype: str = "auto" # bf16 | fp32 | auto (= the checkpoint's stored dtype)
404
+ prefill_chunk: int = 0 # state tokens per prefill segment (0 = 4096)
405
+ max_sweep_tokens: int = 0 # tokens per layer pass (0 = 8192)
406
+ max_sweep_rows: int = 256 # branch rows per layer pass
407
+ attn_dtype: str = "auto" # q/K/V precision inside attention (the prefix K/V are cached in it): fp32 | bf16 | auto
408
+ # = fp32 for states of at most attn_fp32_max_state tokens, the compute dtype above
409
+ attn_fp32_max_state: int = 4096 # (fp32 attention halves the drift from the fp32 model; its fused kernel is ~3x slower
410
+ # than bf16, which only shows on long states: +35 % latency at 7k tokens)
411
+ attn_chunk_mb: int = 0 # bound for one multi-row block mask (query-chunked above; 0 = 256 M bools)
412
+ gdr: str = "auto" # auto (Metal kernel on the GPU, ops on the CPU) | metal | ops
413
+ device: str = "auto" # auto / gpu | cpu (the CPU runs everything in exact fp32 with the ops GDR: tests)
414
+ prefix_cache: int = 4 # states kept across requests (LRU); 0 disables
415
+ prefix_cache_min_tokens: int = 384
416
+ prefix_cache_max_tokens: int = 262144
417
+ memory_limit_gb: float = 0.0 # mx.set_memory_limit (0 = MLX's default)
418
+ cache_limit_gb: float = 1.0 # mx.set_cache_limit: freed buffers MLX keeps for reuse
419
+ wired_limit_gb: float = 0.0 # mx.set_wired_limit (0 = leave as is)
420
+
421
+ @classmethod
422
+ def from_kwargs(cls, **kw):
423
+ """verdin.server / Verdin.from_pretrained pass torch-backend options too (branch_gdr, conv, sdpa, threads,
424
+ cuda_graphs, ...): those are ignored (kept in .ignored when set to a non-default value)."""
425
+ names = {f.name for f in fields(cls)}
426
+ out, ignored = {}, {}
427
+ for key, val in kw.items():
428
+ if key in names:
429
+ if key == "gdr" and val in ("fla", "torch"): # torch-backend values of --gdr
430
+ val = "auto" if val == "fla" else "ops"
431
+ if key == "device" and val in (None, "", "mlx"):
432
+ val = "auto"
433
+ out[key] = val
434
+ elif val not in (None, False, 0, "", "auto", "chunk"):
435
+ ignored[key] = val
436
+ o = cls(**out)
437
+ o.ignored = ignored
438
+ return o
439
+
440
+
441
+ # ---------------------------------------------------------------------------------------------------------------------
442
+ # the model
443
+
444
+ class _Layer:
445
+ pass
446
+
447
+
448
+ def _rope_inv_freq(arch: Arch):
449
+ """inv_freq as transformers computes it (fp32), for the rotated dims of each head."""
450
+ rd = int(arch.head_dim * arch.partial_rotary_factor)
451
+ e = np.arange(0, rd, 2).astype(np.float32) / np.float32(rd)
452
+ return rd, (np.float32(1.0) / np.power(np.float32(arch.rope_theta), e, dtype=np.float32)).astype(np.float32)
453
+
454
+
455
+ class MLXModel:
456
+ """The backbone + pointer head as MLX arrays (fused projection weights in the compute dtype, small parameters fp32,
457
+ the head fp32)."""
458
+
459
+ def __init__(self, arch: Arch, get, head: dict, temperature: float, opts: MLXOptions, stored_dtype: str):
460
+ self.arch, self.opts = arch, opts
461
+ self.cpu = opts.device == "cpu"
462
+ self.dev = mx.cpu if self.cpu else mx.gpu
463
+ mx.set_default_device(self.dev)
464
+ want = opts.dtype if opts.dtype not in ("", "auto", None) else stored_dtype
465
+ self.dt = {"bf16": mx.bfloat16, "bfloat16": mx.bfloat16, "fp32": mx.float32, "float32": mx.float32}[want]
466
+ ad = opts.attn_dtype if opts.attn_dtype not in ("", None) else "auto"
467
+ if ad == "auto":
468
+ self.attn_fp32_max = int(opts.attn_fp32_max_state)
469
+ elif ad in ("fp32", "float32"):
470
+ self.attn_fp32_max = 1 << 62
471
+ elif ad in ("bf16", "bfloat16"):
472
+ self.attn_fp32_max = -1
473
+ else:
474
+ raise ValueError(f"attn_dtype {ad!r}: auto | fp32 | bf16")
475
+ self.attn_mode = ad if ad != "auto" else f"fp32 for states <= {self.attn_fp32_max} tokens, else {want}"
476
+ self.temperature = float(temperature)
477
+ A = arch
478
+ self.d, self.eps = A.hidden_size, A.rms_norm_eps
479
+ self.H, self.KV, self.D = A.num_attention_heads, A.num_key_value_heads, A.head_dim
480
+ self.nk, self.nv, self.dk, self.dv = A.linear_num_key_heads, A.linear_num_value_heads, A.linear_key_head_dim, A.linear_value_head_dim
481
+ self.key_dim, self.value_dim = self.nk * self.dk, self.nv * self.dv
482
+ self.conv_dim = 2 * self.key_dim + self.value_dim
483
+ self.kconv = A.linear_conv_kernel_dim
484
+ if self.kconv != 4:
485
+ raise ValueError("the conv plan assumes a width-4 causal conv (Qwen3.5)")
486
+ if self.nv % self.nk or self.H % self.KV:
487
+ raise ValueError("head counts must divide (GQA)")
488
+ dt = self.dt
489
+
490
+ def W(*names): # a (fused) matmul weight in the compute dtype, transposed once for x @ W
491
+ ws = [get(n).astype(dt) for n in names]
492
+ w = mx.concatenate(ws, axis=0) if len(ws) > 1 else ws[0]
493
+ w = mx.contiguous(w.T)
494
+ mx.eval(w)
495
+ return w
496
+
497
+ def P(name): # a small parameter, fp32
498
+ p = get(name).astype(mx.float32)
499
+ mx.eval(p)
500
+ return p
501
+
502
+ self.embed = get("embed_tokens.weight").astype(dt)
503
+ mx.eval(self.embed)
504
+ self.layers = []
505
+ for i, kind in enumerate(A.layer_types):
506
+ L = _Layer(); L.linear = kind == "linear_attention"
507
+ p = f"layers.{i}."
508
+ L.ln1 = 1.0 + P(p + "input_layernorm.weight")
509
+ L.ln2 = 1.0 + P(p + "post_attention_layernorm.weight")
510
+ if L.linear:
511
+ m = p + "linear_attn."
512
+ L.in_w = W(m + "in_proj_qkv.weight", m + "in_proj_z.weight", m + "in_proj_b.weight", m + "in_proj_a.weight")
513
+ L.out_w = W(m + "out_proj.weight")
514
+ L.conv_w = mx.contiguous(P(m + "conv1d.weight").reshape(self.conv_dim, self.kconv).T) # fp32 [4, C]
515
+ L.negA = -mx.exp(P(m + "A_log"))
516
+ L.dt_bias = P(m + "dt_bias")
517
+ L.norm = P(m + "norm.weight") # plain RMSNormGated weight
518
+ else:
519
+ m = p + "self_attn."
520
+ L.qkv_w = W(m + "q_proj.weight", m + "k_proj.weight", m + "v_proj.weight")
521
+ L.o_w = W(m + "o_proj.weight")
522
+ L.q_norm = 1.0 + P(m + "q_norm.weight")
523
+ L.k_norm = 1.0 + P(m + "k_norm.weight")
524
+ L.gu_w = W(p + "mlp.gate_proj.weight", p + "mlp.up_proj.weight")
525
+ L.down_w = W(p + "mlp.down_proj.weight")
526
+ mx.eval([v for v in vars(L).values() if isinstance(v, mx.array)])
527
+ self.layers.append(L)
528
+ self.final_norm = 1.0 + P("norm.weight")
529
+ self.rot, self.inv_freq = _rope_inv_freq(A)
530
+ # pointer head: fp32 on the CPU stream (exact fp32 GEMM)
531
+ h = {k: mx.array(np.asarray(v, dtype=np.float32)) for k, v in head.items()}
532
+ self.hq_wT, self.hq_b = mx.contiguous(h["q.weight"].T), h["q.bias"]
533
+ self.hk_wT, self.hk_b = mx.contiguous(h["k.weight"].T), h["k.bias"]
534
+ self.unknown = "unk_key" in h
535
+ if self.unknown:
536
+ self.unk_key, self.unk_bias = h["unk_key"], h["unk_bias"].reshape(())
537
+ self.head_scale = 1.0 / math.sqrt(h["q.weight"].shape[0])
538
+ mx.eval([x for x in vars(self).values() if isinstance(x, mx.array)])
539
+ gdr = opts.gdr if opts.gdr not in ("", None) else "auto"
540
+ if gdr == "metal" and (self.cpu or not mx.metal.is_available()):
541
+ raise RuntimeError("gdr=metal needs the GPU (Metal)")
542
+ self.gdr_kind = "ops" if (gdr == "ops" or self.cpu or not mx.metal.is_available()) else "metal"
543
+ self.gdr = gdr_varlen_metal if self.gdr_kind == "metal" else gdr_varlen_ops
544
+ self.conv = conv_silu_metal if self.gdr_kind == "metal" else conv_silu_ops
545
+ (self.f_add_norm, self.f_norm, self.f_swiglu, self.f_l2qk, self.f_gates, self.f_gated_norm, self.f_norm_rope,
546
+ self.f_attn_gate) = _compiled(self.eps, dt, self.dk, self.rot)
547
+ self.prefill_chunk = opts.prefill_chunk or 4096
548
+ # state-bidirectional checkpoints (kev KEV_STATE_BIDIR): plan_sweeps starts prefill segments at multiples of
549
+ # prefill_chunk, so a multiple of the block size keeps every block whole inside one segment
550
+ self.bidir = int(arch.state_bidir)
551
+ if self.bidir:
552
+ if opts.prefill_chunk and opts.prefill_chunk % self.bidir:
553
+ raise ValueError(f"prefill_chunk {opts.prefill_chunk} must be a multiple of the checkpoint's state_bidir block ({self.bidir})")
554
+ if not opts.prefill_chunk:
555
+ self.prefill_chunk = max(1, self.prefill_chunk // self.bidir) * self.bidir
556
+ self.max_tokens = opts.max_sweep_tokens or 8192
557
+ self.max_rows = opts.max_sweep_rows
558
+ self.mask_elems = (opts.attn_chunk_mb or 256) * (1 << 20)
559
+ self._zero_tail = mx.zeros((self.kconv - 1, self.conv_dim), dtype=dt)
560
+ self._zero_state = mx.zeros((1, self.nv, self.dv, self.dk), dtype=mx.float32)
561
+
562
+ # -- loading ----------------------------------------------------------------------------------------------------
563
+
564
+ @classmethod
565
+ def load(cls, cfg: VerdinConfig, opts: MLXOptions):
566
+ if opts.device == "cpu":
567
+ mx.set_default_device(mx.cpu)
568
+ weights = mx.load(str(cfg.file(cfg.weights["file"])))
569
+ head = {k: np.array(v.astype(mx.float32)) for k, v in mx.load(str(cfg.file(cfg.head["file"]))).items()}
570
+ model = cls(cfg.arch, lambda n: weights.pop(n), head, cfg.temperature, opts, cfg.weights["dtype"])
571
+ del weights
572
+ mx.clear_cache()
573
+ return model
574
+
575
+ def describe(self):
576
+ name = lambda t: "bf16" if t == mx.bfloat16 else "fp32" # noqa: E731
577
+ return {"device": "mlx-cpu" if self.cpu else f"mlx-gpu ({mx.device_info().get('device_name', 'metal')})",
578
+ "dtype": name(self.dt), "attention": self.attn_mode, "gdr": f"{self.gdr_kind}-varlen",
579
+ "prefill_chunk": self.prefill_chunk, "max_sweep_tokens": self.max_tokens, "max_sweep_rows": self.max_rows,
580
+ "unknown_head": self.unknown, "temperature": self.temperature, "head": "fp32 (cpu stream)",
581
+ "mlx": mx.__version__, **({"state_bidir": self.bidir} if self.bidir else {})}
582
+
583
+ # -- primitives -------------------------------------------------------------------------------------------------
584
+
585
+ def _sdpa(self, q, K, V, mask):
586
+ """q [Lq, H, D] (attention dtype), K/V [1, KV, Lk, D] -> [Lq, H, D]."""
587
+ o = mx.fast.scaled_dot_product_attention(q.transpose(1, 0, 2)[None], K, V, scale=self.D ** -0.5, mask=mask)
588
+ return o[0].transpose(1, 0, 2)
589
+
590
+ # -- layers -----------------------------------------------------------------------------------------------------
591
+
592
+ def _deltanet(self, i, L, h, P):
593
+ N, C, vd, nv = h.shape[0], self.conv_dim, self.value_dim, self.nv
594
+ proj = h @ L.in_w # [N, C | z | b | a]
595
+ # causal conv over [carried tails ; tokens] (+ SiLU), fp32
596
+ if P.all_fresh:
597
+ tails = P.zero_tails
598
+ else:
599
+ tails = mx.concatenate([st.tail.get(i, self._zero_tail) for st in P.involved], axis=0)
600
+ x = self.conv(tails, proj, P.conv_idx4, L.conv_w, C)
601
+ if P.pre_states: # each prefilled state's last 3 pre-conv tokens
602
+ src = proj[:, :C] if P.tails_from_tokens else mx.concatenate([tails, proj[:, :C]], axis=0)
603
+ new_tails = src[P.tail_idx].reshape(len(P.pre_states), self.kconv - 1, C)
604
+ for j, st in enumerate(P.pre_states):
605
+ st.tail[i] = new_tails[j]
606
+ q, k = self.f_l2qk(x[:, :self.key_dim].reshape(N, self.nk, self.dk), x[:, self.key_dim:2 * self.key_dim].reshape(N, self.nk, self.dk))
607
+ v = x[:, 2 * self.key_dim:].reshape(N, nv, self.dv)
608
+ beta, g = self.f_gates(proj[:, C + vd + nv:], proj[:, C + vd:C + vd + nv], L.negA, L.dt_bias)
609
+ outs, Np, fin = [], P.n_pre, None
610
+ if Np:
611
+ if all(P.pre_fresh):
612
+ init, sidx = self._zero_state, P.pre_sidx_fresh
613
+ else:
614
+ init = mx.stack([self._zero_state[0] if fresh else st.rec[i] for st, fresh in zip(P.pre_states, P.pre_fresh)])
615
+ sidx = P.pre_sidx
616
+ if P.n_rows_tok:
617
+ y, fin = self.gdr(q[:Np], k[:Np], v[:Np], g[:Np], beta[:Np], P.cu_pre, sidx, init, len(P.pre_states), True)
618
+ else:
619
+ y, fin = self.gdr(q, k, v, g, beta, P.cu_pre, sidx, init, len(P.pre_states), True)
620
+ for j, st in enumerate(P.pre_states):
621
+ st.rec[i] = fin[j]
622
+ outs.append(y)
623
+ if P.n_rows_tok:
624
+ cur = fin if P.involved_is_pre else mx.stack([st.rec[i] for st in P.involved])
625
+ if Np:
626
+ y, _ = self.gdr(q[Np:], k[Np:], v[Np:], g[Np:], beta[Np:], P.cu_rows, P.row_inv, cur, P.n_rows, False)
627
+ else:
628
+ y, _ = self.gdr(q, k, v, g, beta, P.cu_rows, P.row_inv, cur, P.n_rows, False)
629
+ outs.append(y)
630
+ o = mx.concatenate(outs, axis=0) if len(outs) > 1 else outs[0] # [N, nv, dv] fp32
631
+ o = self.f_gated_norm(o, L.norm, proj[:, C:C + vd].reshape(N, nv, self.dv))
632
+ return o.reshape(N, vd) @ L.out_w
633
+
634
+ def _attention(self, i, L, h, P, last):
635
+ N, H, KV, D = h.shape[0], self.H, self.KV, self.D
636
+ proj = h @ L.qkv_w
637
+ qg = proj[:, :H * 2 * D].reshape(N, H, 2 * D)
638
+ q = self.f_norm_rope(qg[..., :D], L.q_norm, P.cos, P.sin) # fp32
639
+ k = self.f_norm_rope(proj[:, H * 2 * D:H * 2 * D + KV * D].reshape(N, KV, D), L.k_norm, P.cos, P.sin)
640
+ v = proj[:, H * 2 * D + KV * D:].reshape(N, KV, D)
641
+ pieces = []
642
+ for st, a, b_, f0 in P.pre_segs:
643
+ if self.bidir and (a % self.bidir or (b_ != st.n and b_ % self.bidir)):
644
+ raise RuntimeError(f"prefill segment [{a}, {b_}) of a {st.n}-token state splits a {self.bidir}-token block")
645
+ n, adt = b_ - a, self._adt(st)
646
+ ks = mx.contiguous(k[f0:f0 + n].transpose(1, 0, 2)[None].astype(adt)) # [1, KV, n, D]
647
+ vs = mx.contiguous(v[f0:f0 + n].transpose(1, 0, 2)[None].astype(adt))
648
+ if a == 0 and b_ == st.n:
649
+ Kb, Vb = ks, vs
650
+ else:
651
+ if a == 0:
652
+ Kb = mx.zeros((1, KV, st.n, D), dtype=adt); Vb = mx.zeros((1, KV, st.n, D), dtype=adt)
653
+ else:
654
+ Kb, Vb = st.kv.pop(i)
655
+ Kb[:, :, a:b_, :] = ks
656
+ Vb[:, :, a:b_, :] = vs
657
+ st.kv[i] = (Kb, Vb)
658
+ if last: # the last layer's prefix outputs are never read (only its K/V)
659
+ pieces.append(mx.zeros((n, H, D), dtype=adt))
660
+ else:
661
+ Kc, Vc = (Kb, Vb) if b_ == st.n else (Kb[:, :, :b_], Vb[:, :, :b_])
662
+ pieces.append(self._attend_prefill(q[f0:f0 + n].astype(adt), Kc, Vc, a))
663
+ for st, f0, T, masks in P.row_blocks:
664
+ Kp, Vp = st.kv[i]
665
+ adt = Kp.dtype
666
+ Kc = mx.concatenate([Kp, k[f0:f0 + T].transpose(1, 0, 2)[None].astype(adt)], axis=2)
667
+ Vc = mx.concatenate([Vp, v[f0:f0 + T].transpose(1, 0, 2)[None].astype(adt)], axis=2)
668
+ for q0, q1, mask in masks:
669
+ pieces.append(self._sdpa(q[f0 + q0:f0 + q1].astype(adt), Kc, Vc, mask))
670
+ if len(pieces) > 1:
671
+ common = mx.float32 if any(p.dtype == mx.float32 for p in pieces) else self.dt
672
+ out = mx.concatenate([p.astype(common) for p in pieces], axis=0)
673
+ else:
674
+ out = pieces[0]
675
+ return self.f_attn_gate(out.reshape(N, H * D), qg[..., D:].reshape(N, H * D)) @ L.o_w
676
+
677
+ def _adt(self, st):
678
+ """Attention dtype of a state (its prefix K/V are cached in it): fp32 up to attn_fp32_max state tokens."""
679
+ return mx.float32 if st.n <= self.attn_fp32_max else self.dt
680
+
681
+ def _attend_prefill(self, q, K, V, a):
682
+ """Queries at state positions a..a+L-1 over keys 0..a+L-1: MLX's "causal" mask is aligned bottom-right, which is
683
+ exactly this for any a; the fused kernel never builds a score matrix (and is faster than an explicit mask).
684
+ State-bidirectional checkpoints: a query also sees the later keys of its own block (all of them are in K: segments
685
+ end on a block boundary or at the state's end), so a one-block segment needs no mask; a longer one gets
686
+ (k <= q) | same block, in query chunks of at most mask_elems."""
687
+ B = self.bidir
688
+ if not B:
689
+ return self._sdpa(q, K, V, "causal")
690
+ L, Tk = q.shape[0], K.shape[2]
691
+ if a // B == (a + L - 1) // B: # one block: every query sees every key 0..a+L-1
692
+ return self._sdpa(q, K, V, None)
693
+ kp = mx.arange(Tk)[None, :]
694
+ step = max(1, self.mask_elems // Tk)
695
+ out = []
696
+ for i0 in range(0, L, step):
697
+ i1 = min(L, i0 + step)
698
+ qp = mx.arange(a + i0, a + i1)[:, None]
699
+ out.append(self._sdpa(q[i0:i1], K, V, mx.logical_or(kp <= qp, kp // B == qp // B)))
700
+ return mx.concatenate(out, axis=0) if len(out) > 1 else out[0]
701
+
702
+ def _mlp(self, L, h):
703
+ gu = h @ L.gu_w
704
+ inter = gu.shape[-1] // 2
705
+ return self.f_swiglu(gu[:, :inter], gu[:, inter:]) @ L.down_w
706
+
707
+ def sweep(self, P):
708
+ """One pass over every layer. Returns final-normed fp32 hidden states at the readout tokens ([decide of each row ;
709
+ </opt> of each option]) or None for a prefill-only sweep."""
710
+ x = self.embed[P.ids].astype(mx.float32)
711
+ n = len(self.layers)
712
+ h = self.f_norm(x, self.layers[0].ln1)
713
+ for i, L in enumerate(self.layers):
714
+ last = i == n - 1
715
+ mix = self._deltanet(i, L, h, P) if L.linear else self._attention(i, L, h, P, last)
716
+ if last:
717
+ if P.readout is None:
718
+ return None
719
+ x, mix = x[P.readout], mix[P.readout]
720
+ x, h = self.f_add_norm(x, mix, L.ln2)
721
+ if last:
722
+ x = x + self._mlp(L, h).astype(mx.float32)
723
+ break
724
+ x, h = self.f_add_norm(x, self._mlp(L, h), self.layers[i + 1].ln1)
725
+ return mx.fast.rms_norm(x, self.final_norm, self.eps)
726
+
727
+ def head(self, hs, n_rows, opt_row):
728
+ """Pointer head on the readouts in fp32 on the CPU stream: option logits (rows concatenated) and the unknown
729
+ logit per row (or None). Raw logits (temperature 1)."""
730
+ with mx.stream(mx.cpu):
731
+ hd, ho = hs[:n_rows], hs[n_rows:]
732
+ qd = hd @ self.hq_wT + self.hq_b
733
+ ko = ho @ self.hk_wT + self.hk_b
734
+ z = (ko * qd[opt_row]).sum(-1) * self.head_scale
735
+ zu = (qd @ self.unk_key) * self.head_scale + self.unk_bias if self.unknown else None
736
+ return z, zu
737
+
738
+
739
+ # ---------------------------------------------------------------------------------------------------------------------
740
+ # the engine
741
+
742
+ class MLXMemoryError(MemoryError):
743
+ """An MLX allocation failed (the request does not fit this Mac's memory / the configured limit)."""
744
+
745
+
746
+ def _is_oom(e):
747
+ s = str(e).lower()
748
+ return any(w in s for w in ("out of memory", "insufficient memory", "malloc", "memory limit", "maximum allowed buffer"))
749
+
750
+
751
+ class _Plan:
752
+ pass
753
+
754
+
755
+ class MLXEngine(BaseEngine):
756
+ """Batches of Encoded requests -> raw logits on MLX. Every MLX call runs on the engine's own thread."""
757
+
758
+ backend = "mlx"
759
+ oom_errors = (MLXMemoryError,)
760
+
761
+ def __init__(self, model: MLXModel, pool: ThreadPoolExecutor, thread_ident: int):
762
+ o = model.opts
763
+ super().__init__(o.prefix_cache, o.prefix_cache_min_tokens, o.prefix_cache_max_tokens)
764
+ self.m, self._pool, self._tid = model, pool, thread_ident
765
+ self.prefill_chunk, self.max_tokens, self.max_rows = model.prefill_chunk, model.max_tokens, model.max_rows
766
+ self.kconv, self.unknown = model.kconv, model.unknown
767
+
768
+ @classmethod
769
+ def load(cls, cfg: VerdinConfig, opts: MLXOptions):
770
+ pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="verdin-mlx")
771
+ tid = pool.submit(threading.get_ident).result()
772
+
773
+ def boot():
774
+ if opts.memory_limit_gb:
775
+ mx.set_memory_limit(int(opts.memory_limit_gb * GiB))
776
+ if opts.cache_limit_gb is not None:
777
+ mx.set_cache_limit(int(opts.cache_limit_gb * GiB))
778
+ if opts.wired_limit_gb:
779
+ mx.set_wired_limit(int(opts.wired_limit_gb * GiB))
780
+ return MLXModel.load(cfg, opts)
781
+ return cls(pool.submit(boot).result(), pool, tid)
782
+
783
+ def _call(self, fn, *args):
784
+ if threading.get_ident() == self._tid:
785
+ return fn(*args)
786
+ return self._pool.submit(fn, *args).result()
787
+
788
+ # -- BaseEngine hooks -------------------------------------------------------------------------------------------
789
+
790
+ def run(self, encs):
791
+ return self._call(super().run, encs)
792
+
793
+ def warmup(self):
794
+ return self._call(super().warmup)
795
+
796
+ def sync(self):
797
+ self._call(mx.synchronize)
798
+
799
+ def on_oom(self):
800
+ mx.clear_cache()
801
+
802
+ def describe_backend(self):
803
+ def info():
804
+ return {**self.m.describe(), "active_memory_gb": round(mx.get_active_memory() / GiB, 3),
805
+ "peak_memory_gb": round(mx.get_peak_memory() / GiB, 3), "cache_memory_gb": round(mx.get_cache_memory() / GiB, 3)}
806
+ return self._call(info)
807
+
808
+ def reset_peak_memory(self):
809
+ self._call(mx.reset_peak_memory)
810
+
811
+ def clear_cache(self):
812
+ """Drop the prefix cache and MLX's buffer cache."""
813
+ def f():
814
+ self.cache.clear(); self.cache_tokens = 0
815
+ mx.clear_cache()
816
+ self._call(f)
817
+
818
+ # -- one sweep --------------------------------------------------------------------------------------------------
819
+
820
+ def _plan(self, L):
821
+ m = self.m
822
+ P = _Plan()
823
+ i32 = lambda xs: mx.array(np.asarray(xs, dtype=np.int32)) # noqa: E731
824
+ P.involved, P.all_fresh, P.persist = L.involved, L.all_fresh, L.persist
825
+ P.pre_segs, P.pre_states, P.pre_fresh, P.involved_is_pre, P.n_pre = L.pre_segs, L.pre_states, L.pre_fresh, L.involved_is_pre, L.n_pre
826
+ P.cu_pre = i32(L.cu_pre)
827
+ P.pre_sidx_fresh = i32([-1] * len(L.pre_states))
828
+ P.pre_sidx = i32([-1 if f else j for j, f in enumerate(L.pre_fresh)])
829
+ T0 = (self.kconv - 1) * len(L.involved) # rows of carried tails before the sweep's tokens
830
+ P.tails_from_tokens = all(x >= T0 for x in L.tail_idx)
831
+ P.tail_idx = i32([x - T0 for x in L.tail_idx] if P.tails_from_tokens else L.tail_idx)
832
+ P.zero_tails = mx.zeros((T0, m.conv_dim), dtype=m.dt) if L.all_fresh else None
833
+ P.cu_rows = i32(L.cu_rows)
834
+ P.row_inv = i32(L.row_inv)
835
+ P.n_rows = len(L.row_refs)
836
+ P.n_rows_tok = len(L.ids) - L.n_pre
837
+ P.row_blocks = []
838
+ for st, f0, lens in L.row_blocks:
839
+ T = sum(lens)
840
+ if len(lens) == 1: # one row: [prefix ; row] is exactly bottom-right causal
841
+ masks = [(0, T, "causal")]
842
+ else:
843
+ rid = np.repeat(np.arange(len(lens), dtype=np.int32), lens)
844
+ rid_m, ar = mx.array(rid), mx.arange(T)
845
+ step = max(1, m.mask_elems // (st.n + T))
846
+ masks = []
847
+ for q0 in range(0, T, step):
848
+ q1 = min(T, q0 + step)
849
+ own = (rid_m[q0:q1, None] == rid_m[None, :]) & (ar[None, :] <= ar[q0:q1, None])
850
+ masks.append((q0, q1, mx.concatenate([mx.ones((q1 - q0, st.n), dtype=mx.bool_), own], axis=1)))
851
+ P.row_blocks.append((st, f0, T, masks))
852
+ P.ids = i32(L.ids)
853
+ freqs = np.asarray(L.pos, dtype=np.float32)[:, None] * m.inv_freq[None, :]
854
+ emb = np.concatenate([freqs, freqs], axis=-1).astype(np.float64)
855
+ P.cos = mx.array(np.cos(emb).astype(np.float32))[:, None, :]
856
+ P.sin = mx.array(np.sin(emb).astype(np.float32))[:, None, :]
857
+ P.conv_idx4 = i32(L.conv) # [4, N]
858
+ P.readout = i32(L.dec + L.opt) if P.n_rows else None
859
+ P.opt_row = i32(L.opt_row) if P.n_rows else None
860
+ return P
861
+
862
+ def execute(self, layout):
863
+ try:
864
+ P = self._plan(layout)
865
+ hs = self.m.sweep(P)
866
+ keep = []
867
+ for st in layout.involved: # states used by a later sweep or kept by the cache: evaluate now
868
+ if layout.persist[id(st)]:
869
+ keep += [a for kv in st.kv.values() for a in kv] + list(st.rec.values()) + list(st.tail.values())
870
+ if hs is None:
871
+ mx.eval(keep)
872
+ return None, None
873
+ z, zu = self.m.head(hs, P.n_rows, P.opt_row)
874
+ mx.eval([z] + ([zu] if zu is not None else []) + keep)
875
+ return np.array(z).tolist(), (np.array(zu).tolist() if zu is not None else None)
876
+ except RuntimeError as e:
877
+ if _is_oom(e):
878
+ raise MLXMemoryError(str(e)) from e
879
+ raise
880
+
881
+
882
+ # ---------------------------------------------------------------------------------------------------------------------
883
+ # entry points
884
+
885
+ def load_verdin(path, warmup: bool = False, **options):
886
+ """A verdin.core.Verdin on the MLX engine (works before the core hook lands). `options` are MLXOptions fields; torch
887
+ backend options are accepted and ignored."""
888
+ from .core import Verdin
889
+ from .render import Renderer, RenderConfig, Tokenizer
890
+ cfg = VerdinConfig.load(path)
891
+ tok = Tokenizer(cfg.file(cfg.tokenizer["file"]), cfg.tokenizer["specials"])
892
+ renderer = Renderer(tok, RenderConfig.from_dict(cfg.render))
893
+ engine = MLXEngine.load(cfg, MLXOptions.from_kwargs(**options))
894
+ if warmup:
895
+ engine.warmup()
896
+ return Verdin(cfg, renderer, engine, "mlx")
897
+
898
+
899
+ def _install_core_hook(**extra):
900
+ """Route verdin.core.Verdin.from_pretrained(backend="mlx" | "auto" on Apple silicon) to this engine, adding `extra`
901
+ MLXOptions (what verdin/mlx_hook.patch does in core.py, for use before it is merged)."""
902
+ from . import core
903
+
904
+ orig = core.Verdin.from_pretrained.__func__
905
+
906
+ def from_pretrained(cls, path, backend="auto", device=None, dtype=None, warmup=False, **options):
907
+ if (backend or "auto").lower() in ("mlx", "auto") and not _cuda_available():
908
+ return load_verdin(path, warmup=warmup, dtype=dtype or "auto", **{**options, **extra})
909
+ return orig(cls, path, backend=backend, device=device, dtype=dtype, warmup=warmup, **options)
910
+ core.Verdin.from_pretrained = classmethod(from_pretrained)
911
+
912
+
913
+ def _cuda_available():
914
+ import sys
915
+ if sys.platform == "darwin":
916
+ return False
917
+ try:
918
+ import torch
919
+ return torch.cuda.is_available()
920
+ except ImportError:
921
+ return False
922
+
923
+
924
+ def main(argv=None):
925
+ """`python -m verdin.mlx_backend --model DIR [verdin.server flags] [MLX flags]`: verdin.server on the MLX engine.
926
+ MLX flags: --attn-dtype auto|fp32|bf16, --attn-fp32-max-state, --memory-limit-gb, --cache-limit-gb, --wired-limit-gb."""
927
+ import argparse
928
+ import sys
929
+ ap = argparse.ArgumentParser(add_help=False)
930
+ ap.add_argument("--attn-dtype", default="auto")
931
+ ap.add_argument("--attn-fp32-max-state", type=int, default=4096)
932
+ ap.add_argument("--memory-limit-gb", type=float, default=0.0)
933
+ ap.add_argument("--cache-limit-gb", type=float, default=1.0)
934
+ ap.add_argument("--wired-limit-gb", type=float, default=0.0)
935
+ mo, rest = ap.parse_known_args(list(sys.argv[1:] if argv is None else argv))
936
+ if "--backend" not in rest:
937
+ rest += ["--backend", "mlx"]
938
+ _install_core_hook(attn_dtype=mo.attn_dtype, attn_fp32_max_state=mo.attn_fp32_max_state, memory_limit_gb=mo.memory_limit_gb,
939
+ cache_limit_gb=mo.cache_limit_gb,
940
+ wired_limit_gb=mo.wired_limit_gb)
941
+ from . import server
942
+ return server.main(rest)
943
+
944
+
945
+ if __name__ == "__main__":
946
+ import sys
947
+ sys.exit(main())
verdin/mlx_hook.patch ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- a/verdin/core.py
2
+ +++ b/verdin/core.py
3
+ @@ -1,12 +1,12 @@
4
+ """The Python API.
5
+
6
+ from verdin import Verdin
7
+ - v = Verdin.from_pretrained("runs/verdin-4b-s1") # CUDA if available, else CPU
8
+ + v = Verdin.from_pretrained("runs/verdin-4b-s1") # CUDA if available, MLX on Apple silicon, else CPU
9
+ v.decide("The parcel arrived broken.", {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}})
10
+ # -> {"damaged": {"type": "noul", "noul": 0.97}}
11
+
12
+ -Backends: "cuda" / "cpu" (torch, this phase), "mlx" (reserved for the Apple-silicon port). The renderer and the answer
13
+ -formatting are backend-independent (render.py, answers.py).
14
+ +Backends: "cuda" / "cpu" (torch_backend.py), "mlx" (mlx_backend.py, Apple silicon; what "auto" picks on a Mac with mlx
15
+ +installed). The renderer and the answer formatting are backend-independent (render.py, answers.py).
16
+ """
17
+ from __future__ import annotations
18
+
19
+ @@ -16,10 +16,23 @@
20
+ from .render import Encoded, Renderer, RenderConfig, RequestError, Tokenizer
21
+
22
+
23
+ +def mlx_available() -> bool:
24
+ + """Apple silicon with mlx importable and Metal up."""
25
+ + import platform
26
+ + import sys
27
+ + if sys.platform != "darwin" or platform.machine() != "arm64":
28
+ + return False
29
+ + try:
30
+ + import mlx.core as mx
31
+ + return bool(mx.metal.is_available())
32
+ + except Exception: # noqa: BLE001 - any import failure: no MLX backend
33
+ + return False
34
+ +
35
+ +
36
+ def pick_backend(backend: str | None, device: str | None = None) -> str:
37
+ b = (backend or "auto").lower()
38
+ - if b == "mlx":
39
+ - raise NotImplementedError("the MLX backend is phase B (minijev/mlx_kev.py is the current Mac path)")
40
+ + if b == "mlx" or (b == "auto" and not device and mlx_available()):
41
+ + return "mlx"
42
+ if b in ("torch", "auto"):
43
+ if device:
44
+ return "cuda" if str(device).startswith("cuda") else "cpu"
45
+ @@ -43,14 +56,18 @@
46
+ def from_pretrained(cls, path, backend: str = "auto", device: str | None = None, dtype: str | None = None,
47
+ warmup: bool = False, **options):
48
+ """Load a converted checkpoint directory. `options` are TorchOptions fields (prefill_chunk, max_sweep_tokens,
49
+ - prefix_cache, gdr, conv, ...)."""
50
+ + prefix_cache, gdr, conv, ...) or, for backend "mlx", MLXOptions fields (torch-only ones are ignored there)."""
51
+ cfg = VerdinConfig.load(path)
52
+ tok = Tokenizer(cfg.file(cfg.tokenizer["file"]), cfg.tokenizer["specials"])
53
+ renderer = Renderer(tok, RenderConfig.from_dict(cfg.render))
54
+ b = pick_backend(backend, device)
55
+ - from .torch_backend import TorchEngine, TorchOptions
56
+ - opts = TorchOptions(device=device or b, dtype=dtype or "auto", **options)
57
+ - engine = TorchEngine.load(cfg, opts)
58
+ + if b == "mlx":
59
+ + from .mlx_backend import MLXEngine, MLXOptions
60
+ + engine = MLXEngine.load(cfg, MLXOptions.from_kwargs(dtype=dtype or "auto", **options))
61
+ + else:
62
+ + from .torch_backend import TorchEngine, TorchOptions
63
+ + opts = TorchOptions(device=device or b, dtype=dtype or "auto", **options)
64
+ + engine = TorchEngine.load(cfg, opts)
65
+ if warmup:
66
+ engine.warmup()
67
+ return cls(cfg, renderer, engine, b)
68
+ --- a/verdin/server.py
69
+ +++ b/verdin/server.py
70
+ @@ -1,7 +1,7 @@
71
+ """HTTP server: POST /v1/systemone, GET /v1/models (the TypeSafe wire format kev.serve and minijev.predictor_server
72
+ speak; the Decision Index http engine and JevBench's typesafe adapter work against it unchanged).
73
+
74
+ - python -m verdin.server --model runs/verdin-4b-s1 --port 8903 [--host 0.0.0.0] [--backend auto|cuda|cpu]
75
+ + python -m verdin.server --model runs/verdin-4b-s1 --port 8903 [--host 0.0.0.0] [--backend auto|cuda|cpu|mlx]
76
+
77
+ Concurrency: HTTP handler threads validate + render + tokenize; one batcher thread owns the model and runs whatever
78
+ requests are waiting as one batch (dynamic batching: while the GPU is busy, new requests queue up and go together in
79
+ @@ -160,7 +160,7 @@
80
+ ap.add_argument("--model", required=True, help="converted Verdin checkpoint directory")
81
+ ap.add_argument("--host", default="127.0.0.1", help="0.0.0.0 to serve the LAN")
82
+ ap.add_argument("--port", type=int, default=8903)
83
+ - ap.add_argument("--backend", default="auto", help="auto | cuda | cpu (mlx: phase B)")
84
+ + ap.add_argument("--backend", default="auto", help="auto | cuda | cpu | mlx (auto: cuda, else mlx on Apple silicon, else cpu)")
85
+ ap.add_argument("--device", default=None, help="e.g. cuda:0 (default: the backend's)")
86
+ ap.add_argument("--dtype", default="auto", help="bf16 | fp32 | auto (= the checkpoint's)")
87
+ ap.add_argument("--name", default=None, help="model id reported by /v1/models (default: the checkpoint's model_name)")
88
+ --- a/verdin/NOTICE
89
+ +++ b/verdin/NOTICE
90
+ @@ -25,5 +25,27 @@
91
+ The model architecture implemented here; base weights released under the Apache License, Version 2.0.
92
+
93
+ -------------------------------------------------------------------------------------------------------------------------
94
+ +Portions of this software are derived from the following work, licensed under the MIT License:
95
+ +
96
+ +mlx-lm (https://github.com/ml-explore/mlx-lm)
97
+ + Copyright (c) 2023 Apple Inc.
98
+ + verdin/mlx_backend.py adapts the gated delta rule Metal kernels of mlx_lm/models/gated_delta.py (made varlen, with
99
+ + the initial state taken by index and the final state optional).
100
+ +
101
+ + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
102
+ + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
103
+ + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
104
+ + persons to whom the Software is furnished to do so, subject to the following conditions:
105
+ +
106
+ + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
107
+ + Software.
108
+ +
109
+ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
110
+ + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
111
+ + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
112
+ + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
113
+ +
114
+ +-------------------------------------------------------------------------------------------------------------------------
115
+ Optional runtime dependencies (not distributed with Verdin): PyTorch (BSD-3-Clause), tokenizers (Apache-2.0),
116
+ -safetensors (Apache-2.0), flash-linear-attention / fla (MIT), causal-conv1d (BSD-3-Clause).
117
+ +safetensors (Apache-2.0), flash-linear-attention / fla (MIT), causal-conv1d (BSD-3-Clause), MLX (MIT; the Apple-silicon
118
+ +backend), NumPy (BSD-3-Clause).
verdin/render.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Request validation and rendering: a /v1/systemone request -> the token layout the model reads.
2
+
3
+ Pure Python + the `tokenizers` library (no torch, no transformers), so every backend (torch now, MLX next) shares it.
4
+ It reproduces kev's serving path token for token for a Verdin checkpoint's render settings:
5
+
6
+ request JSON --validate--> (state, typed questions) --date facts--> rendered text --tokenize--> Encoded
7
+ (kev.api.SystemOneRequest) (kev.api.with_date_facts) (kev.api.to_record) (kev.model.encode)
8
+
9
+ The text rules (render, option_text, date_facts, question keys) and the layout (delimiters, schema-first block, caps)
10
+ are ported from kev (jaredpalmer/kev, Apache-2.0: kev/api.py, kev/model.py) including the mini-jev-lab patches
11
+ (KEV_SCHEMA_FIRST, KEV_MAX_STATE/BRANCH/PACKED). Parity with kev is tested record by record (verdin/tests).
12
+
13
+ Layout (one record): [<state> schema... state...] then per question k: [<q> instr... (<opt> option... </opt>)... <decide>]
14
+ The state prefix is shared by every question; each question's branch continues the state's positions and never sees
15
+ another question, so the backend runs the state once and every branch as its own causal row from that prefix.
16
+ Readouts: the <decide> token of each branch and the </opt> token of each option.
17
+
18
+ Caps are hard: a request over a cap raises Unsupported ("too many tokens: ..."), never a silent truncation.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import re
24
+ from dataclasses import dataclass, field
25
+ from datetime import datetime
26
+
27
+ MAX_OPTIONS = 255
28
+ QUESTION_TYPES = ("noul", "choice", "score")
29
+
30
+
31
+ class RequestError(ValueError):
32
+ """The request is malformed or violates the wire format (HTTP 422)."""
33
+
34
+
35
+ class Unsupported(RequestError):
36
+ """A valid request this model cannot take (over a token cap): HTTP 422 with the 'too many tokens' capacity marker
37
+ the Decision Index http engine and JevBench recognise as an explicit refusal."""
38
+
39
+ def __init__(self, message):
40
+ super().__init__(message if message.startswith("too many tokens") else "too many tokens: " + message)
41
+
42
+
43
+ # ---------------------------------------------------------------------------------------------------------------------
44
+ # Text rules (kev/api.py, verbatim semantics)
45
+
46
+ def render(v, indent: int = 0) -> str:
47
+ """Flatten str | object | array into the text the model sees. Field names are kept as labels."""
48
+ pad = " " * indent
49
+ if v is None: return ""
50
+ if isinstance(v, (str, int, float, bool)): return str(v)
51
+ if isinstance(v, list): return "\n".join(f"{pad}- {render(x, indent + 1).lstrip()}" for x in v)
52
+ return "\n".join(f"{pad}{k}:\n{render(x, indent + 1)}" if isinstance(x, (dict, list)) else f"{pad}{k}: {render(x)}" for k, x in v.items())
53
+
54
+
55
+ def option_text(name: str, desc) -> str:
56
+ return name if desc is None or desc == "" else f"{name}: {render(desc)}"
57
+
58
+
59
+ MONTHS = "January|February|March|April|May|June|July|August|September|October|November|December"
60
+ _DATE = re.compile(rf"\b(?:{MONTHS}) \d{{1,2}}, \d{{4}}\b|\b\d{{4}}-\d{{2}}-\d{{2}}\b")
61
+
62
+
63
+ def date_facts(text: str) -> str:
64
+ """Every pair of absolute dates found in `text`, one sentence each ("August 3, 2026 is 12 days after July 22,
65
+ 2026."), in order of first appearance; "" with fewer than two dates."""
66
+ found = []
67
+ for m in _DATE.finditer(text):
68
+ raw = m.group(0)
69
+ try: d = datetime.strptime(raw, "%B %d, %Y") if "," in raw else datetime.strptime(raw, "%Y-%m-%d")
70
+ except ValueError: continue
71
+ if raw not in [r for r, _ in found]: found.append((raw, d))
72
+ facts = []
73
+ for i in range(len(found)):
74
+ for j in range(i + 1, len(found)):
75
+ n = (found[j][1] - found[i][1]).days
76
+ facts.append(f"{found[j][0]} is {abs(n)} day{'s' if abs(n) != 1 else ''} {'after' if n > 0 else 'before'} {found[i][0]}." if n else f"{found[j][0]} is the same day as {found[i][0]}.")
77
+ return " ".join(facts)
78
+
79
+
80
+ def with_date_facts(state):
81
+ """The state with a `date_facts` field (object), an appended item (array) or paragraph (string) when two or more
82
+ absolute dates appear in its rendered text; unchanged otherwise."""
83
+ facts = date_facts(render(state))
84
+ if not facts: return state
85
+ if isinstance(state, dict): return {**state, "date_facts": facts}
86
+ if isinstance(state, list): return state + [{"date_facts": facts}]
87
+ return f"{state}\n\ndate_facts: {facts}"
88
+
89
+
90
+ def question_keys(qtype: str, criteria) -> list[str]:
91
+ """The keys a question's probabilities are reported under, in option order: the criteria names (choice),
92
+ ["false", "true"] (noul), the level indices as strings (score)."""
93
+ if qtype == "choice": return list(criteria)
94
+ if qtype == "noul": return ["false", "true"]
95
+ return [str(i) for i in range(len(criteria))]
96
+
97
+
98
+ # ---------------------------------------------------------------------------------------------------------------------
99
+ # Validation (the constraints of kev.api.SystemOneRequest's pydantic model, without pydantic)
100
+
101
+ @dataclass
102
+ class Question:
103
+ id: str
104
+ type: str
105
+ instructions: object
106
+ criteria: object
107
+
108
+ @property
109
+ def keys(self) -> list[str]:
110
+ return question_keys(self.type, self.criteria)
111
+
112
+
113
+ def validate_request(body) -> tuple[object, list[Question]]:
114
+ """-> (state, questions in request order). Accepts exactly what kev's SystemOneRequest accepts: any JSON value as
115
+ state / instructions / criteria values; choice = object of 1..255 options, score = array of 2..255 levels, noul =
116
+ optional object (keys "false"/"true" describe the options). Unknown fields are ignored (as pydantic does)."""
117
+ if not isinstance(body, dict):
118
+ raise RequestError("invalid request: the body must be a JSON object")
119
+ if "state" not in body:
120
+ raise RequestError("invalid request: state is required")
121
+ qs = body.get("questions")
122
+ if not isinstance(qs, dict) or not qs:
123
+ raise RequestError("invalid request: questions must be a non-empty object")
124
+ out = []
125
+ for qid, q in qs.items():
126
+ where = f"questions.{qid}"
127
+ if not isinstance(q, dict):
128
+ raise RequestError(f"invalid request: {where} must be an object")
129
+ t = q.get("type")
130
+ if t not in QUESTION_TYPES:
131
+ raise RequestError(f"invalid request: {where}.type must be one of noul, choice, score (got {t!r})")
132
+ if "instructions" not in q:
133
+ raise RequestError(f"invalid request: {where}.instructions is required")
134
+ c = q.get("criteria")
135
+ if t == "choice":
136
+ if not isinstance(c, dict):
137
+ raise RequestError(f"invalid request: {where}.criteria must be an object of options")
138
+ if not c:
139
+ raise RequestError(f"invalid request: {where}.criteria must have 1..{MAX_OPTIONS} options (got 0)")
140
+ if len(c) > MAX_OPTIONS:
141
+ raise RequestError(f"invalid request: {where}: too many options per choice ({len(c)}; at most {MAX_OPTIONS})")
142
+ elif t == "score":
143
+ if not isinstance(c, list):
144
+ raise RequestError(f"invalid request: {where}.criteria must be an array of levels")
145
+ if not 2 <= len(c) <= MAX_OPTIONS:
146
+ raise RequestError(f"invalid request: {where}: a score takes 2 to {MAX_OPTIONS} levels (got {len(c)})")
147
+ elif c is not None and not isinstance(c, dict):
148
+ raise RequestError(f"invalid request: {where}.criteria must be an object or null for noul")
149
+ out.append(Question(str(qid), t, q["instructions"], c))
150
+ return body["state"], out
151
+
152
+
153
+ def to_record(state, questions: list[Question]) -> dict:
154
+ """kev.api.to_record: the internal record {"state": text, "questions": [{"instr", "options"}]}."""
155
+ qs = []
156
+ for q in questions:
157
+ if q.type == "noul":
158
+ c = q.criteria or {}
159
+ opts = [option_text("no", c.get("false")), option_text("yes", c.get("true"))]
160
+ elif q.type == "choice":
161
+ opts = [option_text(k, v) for k, v in q.criteria.items()]
162
+ else:
163
+ opts = [render(x) for x in q.criteria]
164
+ qs.append({"instr": render(q.instructions), "options": opts})
165
+ return {"state": render(state), "questions": qs}
166
+
167
+
168
+ # ---------------------------------------------------------------------------------------------------------------------
169
+ # Tokenization and layout (kev/model.py encode, option_isolation off, strict)
170
+
171
+ _SPECIAL_RE = re.compile(r"<\|([A-Za-z0-9_]+)\|>")
172
+ SPECIAL_NAMES = ("state", "question", "option", "option_end", "decide")
173
+
174
+
175
+ class Tokenizer:
176
+ """The checkpoint's tokenizer.json through the `tokenizers` library, plus kev's rule for caller-supplied text:
177
+ `<|name|>` is rewritten to `<¦name¦>` first, so user text can never produce a delimiter/control token."""
178
+
179
+ def __init__(self, path, specials: dict[str, str]):
180
+ from tokenizers import Tokenizer as _T
181
+ self.tk = _T.from_file(str(path))
182
+ self.specials = dict(specials)
183
+ self.ids = {}
184
+ for name in SPECIAL_NAMES:
185
+ i = self.tk.token_to_id(specials[name])
186
+ if i is None:
187
+ raise ValueError(f"tokenizer has no token {specials[name]!r} ({name})")
188
+ self.ids[name] = i
189
+
190
+ @staticmethod
191
+ def escape(text: str) -> str:
192
+ return _SPECIAL_RE.sub(r"<¦\1¦>", text)
193
+
194
+ def user_tokens(self, text: str) -> list[int]:
195
+ return self.tk.encode(self.escape(text), add_special_tokens=False).ids
196
+
197
+ def user_tokens_batch(self, texts: list[str]) -> list[list[int]]:
198
+ if not texts: return []
199
+ return [e.ids for e in self.tk.encode_batch([self.escape(t) for t in texts], add_special_tokens=False)]
200
+
201
+
202
+ @dataclass
203
+ class Row:
204
+ """One question's branch: its tokens (positions continue the state's), the <decide> offset and the </opt> offsets
205
+ within the branch."""
206
+ ids: list[int]
207
+ decide: int
208
+ opts: list[int]
209
+
210
+
211
+ @dataclass
212
+ class Encoded:
213
+ state_ids: list[int]
214
+ rows: list[Row]
215
+ questions: list[Question] = field(default_factory=list)
216
+
217
+ @property
218
+ def n_state(self) -> int:
219
+ return len(self.state_ids)
220
+
221
+ @property
222
+ def n_tokens(self) -> int:
223
+ """Tokens of the packed record (kev's len(enc["ids"])): state once + every branch."""
224
+ return len(self.state_ids) + sum(len(r.ids) for r in self.rows)
225
+
226
+ def packed(self) -> dict:
227
+ """kev.model.encode's packed form (ids, seg, pos, decide_idx, opt_idx) for parity tests."""
228
+ ids, seg, pos = list(self.state_ids), [0] * self.n_state, list(range(self.n_state))
229
+ decide_idx, opt_idx = [], []
230
+ for k, r in enumerate(self.rows, start=1):
231
+ base = len(ids)
232
+ ids += r.ids; seg += [k] * len(r.ids); pos += list(range(self.n_state, self.n_state + len(r.ids)))
233
+ decide_idx.append(base + r.decide); opt_idx.append([base + o for o in r.opts])
234
+ return {"ids": ids, "seg": seg, "pos": pos, "decide_idx": decide_idx, "opt_idx": opt_idx}
235
+
236
+
237
+ @dataclass
238
+ class RenderConfig:
239
+ schema_first: bool
240
+ date_facts: bool
241
+ max_state: int
242
+ max_branch: int
243
+ max_packed: int
244
+ schema_max: int = 512
245
+ lead_ids: tuple = () # tokens before <state> (Gemma's <bos>; empty for Qwen)
246
+
247
+ @classmethod
248
+ def from_dict(cls, d):
249
+ return cls(schema_first=bool(d["schema_first"]), date_facts=bool(d["date_facts"]), max_state=int(d["max_state"]),
250
+ max_branch=int(d["max_branch"]), max_packed=int(d["max_packed"]), schema_max=int(d.get("schema_max", 512)),
251
+ lead_ids=tuple(d.get("lead_ids", ())))
252
+
253
+
254
+ class Renderer:
255
+ def __init__(self, tokenizer: Tokenizer, cfg: RenderConfig):
256
+ self.tok, self.cfg = tokenizer, cfg
257
+ self._newline = tokenizer.user_tokens("\n")[-1:]
258
+
259
+ def encode_request(self, body) -> Encoded:
260
+ """Wire request (parsed JSON) -> Encoded, applying the checkpoint's date-facts setting. Raises RequestError /
261
+ Unsupported."""
262
+ state, questions = validate_request(body)
263
+ if self.cfg.date_facts:
264
+ state = with_date_facts(state)
265
+ enc = self.encode_record(to_record(state, questions))
266
+ enc.questions = questions
267
+ return enc
268
+
269
+ def encode_record(self, rec: dict) -> Encoded:
270
+ """kev.model.encode(tok, rec, strict=True) for a rendered record + the packed-length check of kev's predictors."""
271
+ c, tok, sp = self.cfg, self.tok, self.tok.ids
272
+ questions = rec["questions"]
273
+ # one batched tokenizer call for the state, the schema and every instruction/option string
274
+ texts = [rec["state"]]
275
+ if c.schema_first:
276
+ text = "Questions to answer about the state below:\n" + "\n".join(
277
+ f"{k}. {q['instr']} Options: " + " | ".join(q["options"]) for k, q in enumerate(questions, start=1))
278
+ texts.append(text + "\nState:\n")
279
+ for q in questions:
280
+ texts.append(q["instr"]); texts.extend(q["options"])
281
+ toks = tok.user_tokens_batch(texts)
282
+ state_tokens, i = toks[0], 1
283
+ schema = []
284
+ if c.schema_first:
285
+ schema = toks[1]; i = 2
286
+ if len(schema) > c.schema_max:
287
+ schema = schema[: c.schema_max - 1] + self._newline
288
+ lead = list(c.lead_ids)
289
+ kept = c.max_state - 1 - len(lead) - len(schema)
290
+ if len(state_tokens) > kept:
291
+ raise Unsupported(f"state exceeds {c.max_state} tokens: {len(state_tokens) + 1 + len(lead) + len(schema)}")
292
+ S = lead + [sp["state"]] + schema + state_tokens
293
+ rows, total = [], len(S)
294
+ for q in questions:
295
+ instr = [sp["question"]] + toks[i]; i += 1
296
+ spans = []
297
+ for _ in q["options"]:
298
+ spans.append([sp["option"]] + toks[i] + [sp["option_end"]]); i += 1
299
+ br = instr + [t for s in spans for t in s] + [sp["decide"]]
300
+ if len(br) > c.max_branch - len(S):
301
+ raise Unsupported(f"branch too long: {len(br)}")
302
+ ends, cursor = [], len(instr)
303
+ for s in spans:
304
+ cursor += len(s); ends.append(cursor - 1)
305
+ rows.append(Row(br, len(br) - 1, ends)); total += len(br)
306
+ if total > c.max_packed:
307
+ raise Unsupported(f"packed request exceeds frozen {c.max_packed}-token limit")
308
+ return Encoded(S, rows)
309
+
310
+
311
+ def parse_body(raw: bytes):
312
+ """JSON body -> object (RequestError on malformed JSON). Python's json, as FastAPI/kev and predictor_server use."""
313
+ try:
314
+ return json.loads(raw)
315
+ except (ValueError, UnicodeDecodeError) as e:
316
+ raise RequestError(f"invalid JSON body: {e}") from None
verdin/server.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP server: POST /v1/systemone, GET /v1/models (the TypeSafe wire format kev.serve and minijev.predictor_server
2
+ speak; the Decision Index http engine and JevBench's typesafe adapter work against it unchanged).
3
+
4
+ python -m verdin.server --model runs/verdin-4b-s1 --port 8903 [--host 0.0.0.0] [--backend auto|cuda|cpu|mlx]
5
+
6
+ Concurrency: HTTP handler threads validate + render + tokenize; one batcher thread owns the model and runs whatever
7
+ requests are waiting as one batch (dynamic batching: while the GPU is busy, new requests queue up and go together in
8
+ the next batch; --batch-wait-ms adds an optional collection window). --max-batch 1 gives strictly one request per
9
+ forward (bitwise-reproducible numbers regardless of load).
10
+
11
+ Errors: malformed / invalid requests -> 422 {"error", "detail"}; requests over a token cap or the device's memory ->
12
+ 422 with the "too many tokens" capacity marker; internal errors -> 500.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import queue
19
+ import sys
20
+ import threading
21
+ import time
22
+ import traceback
23
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
24
+
25
+ from .render import RequestError, Unsupported, parse_body
26
+
27
+
28
+ class _Job:
29
+ __slots__ = ("enc", "done", "result", "error", "t_in", "t_start", "t_end")
30
+
31
+ def __init__(self, enc):
32
+ self.enc, self.done, self.result, self.error = enc, threading.Event(), None, None
33
+ self.t_in = time.perf_counter()
34
+
35
+
36
+ class Batcher(threading.Thread):
37
+ def __init__(self, verdin, max_batch=32, max_batch_tokens=32768, wait_ms=0.0):
38
+ super().__init__(daemon=True, name="verdin-batcher")
39
+ self.v, self.q = verdin, queue.Queue()
40
+ self.max_batch, self.max_tokens, self.wait = max_batch, max_batch_tokens, wait_ms / 1000.0
41
+ self.stats = {"batches": 0, "requests": 0, "max_batch_seen": 0, "errors": 0}
42
+
43
+ def submit(self, enc):
44
+ job = _Job(enc)
45
+ self.q.put(job)
46
+ job.done.wait()
47
+ return job
48
+
49
+ def _collect(self):
50
+ batch = [self.q.get()]
51
+ tokens = batch[0].enc.n_tokens
52
+ deadline = time.perf_counter() + self.wait
53
+ while len(batch) < self.max_batch and tokens < self.max_tokens:
54
+ try:
55
+ left = deadline - time.perf_counter()
56
+ job = self.q.get(timeout=left) if left > 0 else self.q.get_nowait()
57
+ except queue.Empty:
58
+ break
59
+ batch.append(job); tokens += job.enc.n_tokens
60
+ return batch
61
+
62
+ def run(self):
63
+ while True:
64
+ batch = self._collect()
65
+ t = time.perf_counter()
66
+ for j in batch:
67
+ j.t_start = t
68
+ try:
69
+ results = self.v.run([j.enc for j in batch])
70
+ for j, r in zip(batch, results):
71
+ if r.error is not None: # this request alone does not fit the device's memory
72
+ j.error = r.error
73
+ else:
74
+ j.result = r
75
+ except Exception as e: # noqa: BLE001 - report, keep serving
76
+ traceback.print_exc()
77
+ self.stats["errors"] += 1
78
+ for j in batch:
79
+ j.error = e
80
+ try:
81
+ self.v.engine.sync()
82
+ except Exception: # noqa: BLE001 - never let the batcher thread die (callers would wait forever)
83
+ traceback.print_exc()
84
+ t_end = time.perf_counter()
85
+ self.stats["batches"] += 1; self.stats["requests"] += len(batch)
86
+ self.stats["max_batch_seen"] = max(self.stats["max_batch_seen"], len(batch))
87
+ for j in batch:
88
+ j.t_end = t_end
89
+ j.done.set()
90
+
91
+
92
+ class _Server(ThreadingHTTPServer):
93
+ daemon_threads = True
94
+ request_queue_size = 256 # listen backlog (set before bind/listen): concurrency-32 clients must not be refused
95
+ allow_reuse_address = True
96
+
97
+
98
+ def make_handler(v, batcher, served_name):
99
+ class H(BaseHTTPRequestHandler):
100
+ protocol_version = "HTTP/1.1"
101
+ server_version = "verdin"
102
+
103
+ def log_message(self, *args):
104
+ pass
105
+
106
+ def send(self, code, obj):
107
+ b = json.dumps(obj).encode()
108
+ self.send_response(code)
109
+ self.send_header("Content-Type", "application/json")
110
+ self.send_header("Content-Length", str(len(b)))
111
+ self.end_headers()
112
+ self.wfile.write(b)
113
+
114
+ def do_GET(self):
115
+ path = self.path.split("?")[0].rstrip("/")
116
+ if path == "/v1/models":
117
+ info = v.info()
118
+ eng = info["engine"]
119
+ if eng.get("device", "").startswith("cuda"):
120
+ import torch
121
+ eng["memory_allocated_bytes"] = torch.cuda.memory_allocated()
122
+ eng["max_memory_allocated_bytes"] = torch.cuda.max_memory_allocated()
123
+ card = {**info, "id": served_name, "object": "model", "owned_by": "verdin", "aliases": ["kev-latest", "jev-latest"],
124
+ "server": {**batcher.stats, "max_batch": batcher.max_batch, "max_batch_tokens": batcher.max_tokens,
125
+ "batch_wait_ms": batcher.wait * 1000}}
126
+ return self.send(200, {"object": "list", "data": [card], "models": [card]})
127
+ if path in ("/health", "/healthz"):
128
+ return self.send(200, {"ok": True})
129
+ self.send(404, {"error": f"no route {self.path}"})
130
+
131
+ def do_POST(self):
132
+ t0 = time.perf_counter()
133
+ path = self.path.split("?")[0].rstrip("/")
134
+ n = int(self.headers.get("Content-Length") or 0)
135
+ raw = self.rfile.read(n) if n else b""
136
+ if path != "/v1/systemone":
137
+ return self.send(404, {"error": f"no route {self.path}"})
138
+ try:
139
+ body = parse_body(raw)
140
+ enc = v.encode(body)
141
+ except Unsupported as e:
142
+ return self.send(422, {"error": str(e), "detail": str(e)})
143
+ except RequestError as e:
144
+ return self.send(422, {"error": str(e), "detail": str(e)})
145
+ job = batcher.submit(enc)
146
+ if job.error is not None:
147
+ if isinstance(job.error, RequestError):
148
+ return self.send(422, {"error": str(job.error), "detail": str(job.error)})
149
+ return self.send(500, {"error": f"internal error: {type(job.error).__name__}: {job.error}"})
150
+ ans = v.answers(enc, job.result)
151
+ model = body.get("model") if isinstance(body.get("model"), str) else served_name
152
+ self.send(200, {"model": model, "answers": ans, "usage": {"input_tokens": enc.n_tokens, "output_tokens": 0},
153
+ "latency_ms": round(1000 * (time.perf_counter() - t0), 2),
154
+ "compute_ms": round(1000 * (job.t_end - job.t_start), 2)})
155
+ return H
156
+
157
+
158
+ def main(argv=None):
159
+ ap = argparse.ArgumentParser(description="Verdin /v1/systemone server")
160
+ ap.add_argument("--model", required=True, help="converted Verdin checkpoint directory")
161
+ ap.add_argument("--host", default="127.0.0.1", help="0.0.0.0 to serve the LAN")
162
+ ap.add_argument("--port", type=int, default=8903)
163
+ ap.add_argument("--backend", default="auto", help="auto | cuda | cpu | mlx (auto: cuda, else mlx on Apple silicon, else cpu)")
164
+ ap.add_argument("--device", default=None, help="e.g. cuda:0 (default: the backend's)")
165
+ ap.add_argument("--dtype", default="auto", help="bf16 | fp32 | auto (= the checkpoint's)")
166
+ ap.add_argument("--name", default=None, help="model id reported by /v1/models (default: the checkpoint's model_name)")
167
+ ap.add_argument("--max-batch", type=int, default=32, help="requests per batch (1 = no cross-request batching)")
168
+ ap.add_argument("--max-batch-tokens", type=int, default=32768)
169
+ ap.add_argument("--batch-wait-ms", type=float, default=0.0)
170
+ ap.add_argument("--prefix-cache", type=int, default=4, help="states kept across requests (0 = off)")
171
+ ap.add_argument("--prefix-cache-min-tokens", type=int, default=384)
172
+ ap.add_argument("--prefill-chunk", type=int, default=0)
173
+ ap.add_argument("--max-sweep-tokens", type=int, default=0)
174
+ ap.add_argument("--max-sweep-rows", type=int, default=256)
175
+ ap.add_argument("--attn-chunk-mb", type=int, default=0)
176
+ ap.add_argument("--gdr", default="auto", choices=["auto", "fla", "torch"])
177
+ ap.add_argument("--branch-gdr", default="recurrent", choices=["chunk", "recurrent"]) # 10-10: recurrent = chunk on all 18 suites, faster
178
+ ap.add_argument("--conv", default="auto", choices=["auto", "kernel", "torch"])
179
+ ap.add_argument("--sdpa", default="auto", choices=["auto", "math"])
180
+ ap.add_argument("--threads", type=int, default=0, help="CPU threads (cpu backend)")
181
+ ap.add_argument("--cuda-graphs", action="store_true", help="reserved (phase B)")
182
+ ap.add_argument("--no-warmup", action="store_true")
183
+ a = ap.parse_args(argv)
184
+ from .core import Verdin
185
+ t = time.time()
186
+ v = Verdin.from_pretrained(a.model, backend=a.backend, device=a.device, dtype=a.dtype, prefix_cache=a.prefix_cache,
187
+ prefix_cache_min_tokens=a.prefix_cache_min_tokens, prefill_chunk=a.prefill_chunk,
188
+ max_sweep_tokens=a.max_sweep_tokens, max_sweep_rows=a.max_sweep_rows,
189
+ attn_chunk_mb=a.attn_chunk_mb, gdr=a.gdr, branch_gdr=a.branch_gdr, conv=a.conv, sdpa=a.sdpa,
190
+ threads=a.threads, cuda_graphs=a.cuda_graphs)
191
+ if not a.no_warmup:
192
+ v.engine.warmup()
193
+ name = a.name or v.name
194
+ batcher = Batcher(v, a.max_batch, a.max_batch_tokens, a.batch_wait_ms)
195
+ batcher.start()
196
+ srv = _Server((a.host, a.port), make_handler(v, batcher, name))
197
+ print(f"verdin: serving {name} from {a.model} on {a.host}:{a.port} ({json.dumps(v.engine.describe())}; "
198
+ f"render {json.dumps(v.cfg.render)}; loaded in {time.time() - t:.1f} s)", flush=True)
199
+ try:
200
+ srv.serve_forever()
201
+ except KeyboardInterrupt:
202
+ pass
203
+ return 0
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())
verdin/tests/__init__.py ADDED
File without changes
verdin/tests/bench.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serving benchmark for any /v1/systemone server (Verdin or kev's predictor_server), same requests for both.
2
+
3
+ python -m verdin.tests.bench build --out results/verdin/bench/requests.jsonl --n 400
4
+ python -m verdin.tests.bench run --url http://127.0.0.1:8911 --requests results/verdin/bench/requests.jsonl \\
5
+ --concurrency 1,8,32 --pid <server pid> --label verdin --out results/verdin/bench/verdin.json
6
+ python -m verdin.tests.bench table results/verdin/bench/kev.json results/verdin/bench/verdin.json
7
+
8
+ Requests: a fixed sample of our suites' requests (short single questions, multi-question records, long documents and
9
+ tool catalogs; date facts are left to the server). Per concurrency level: every request once through a pool of that
10
+ many client threads; client wall-clock latency p50/p95/mean, throughput (requests/s, input tokens/s), status counts.
11
+ Peak GPU memory of the server process from nvidia-smi (sampled every 0.2 s) when --pid is given.
12
+ """
13
+ import argparse
14
+ import json
15
+ import random
16
+ import statistics
17
+ import subprocess
18
+ import sys
19
+ import threading
20
+ import time
21
+ import urllib.error
22
+ import urllib.request
23
+ from concurrent.futures import ThreadPoolExecutor
24
+ from pathlib import Path
25
+
26
+ ROOT = Path(__file__).resolve().parents[2]
27
+ MIX = [("data/frozen/robust-v1.jsonl", 120), ("data/external/typed-decisions.jsonl", 60), ("data/scoregen/score-v1.heldout.jsonl", 40),
28
+ ("third_party/kev/evals/hard-v1/development.jsonl", 60), ("third_party/kev/evals/documents-v1/development.jsonl", 40),
29
+ ("data/frozen/jevbench-public-v1.jsonl", 40), ("data/diskills/diskills-v1.heldout.jsonl", 40)]
30
+
31
+
32
+ def build(a):
33
+ rng = random.Random(a.seed)
34
+ out = []
35
+ scale = a.n / sum(n for _, n in MIX)
36
+ for path, n in MIX:
37
+ rs = [json.loads(l) for l in open(ROOT / path, encoding="utf-8") if l.strip()]
38
+ for r in rng.sample(rs, min(len(rs), max(1, round(n * scale)))):
39
+ out.append({"state": r["state"], "questions": {k: {f: v for f, v in q.items() if f in ("type", "instructions", "criteria")}
40
+ for k, q in r["questions"].items()}, "_src": path})
41
+ rng.shuffle(out)
42
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
43
+ with open(a.out, "w", encoding="utf-8") as f:
44
+ for r in out: f.write(json.dumps(r, ensure_ascii=False) + "\n")
45
+ print(f"{len(out)} requests -> {a.out}")
46
+
47
+
48
+ def post(url, body, timeout=900):
49
+ data = json.dumps({k: v for k, v in body.items() if not k.startswith("_")}).encode()
50
+ req = urllib.request.Request(url + "/v1/systemone", data=data, headers={"Content-Type": "application/json"}, method="POST")
51
+ t = time.perf_counter()
52
+ try:
53
+ with urllib.request.urlopen(req, timeout=timeout) as r:
54
+ out = json.loads(r.read()); code = r.status
55
+ except urllib.error.HTTPError as e:
56
+ out, code = {}, e.code
57
+ except Exception: # noqa: BLE001
58
+ out, code = {}, -1
59
+ return code, time.perf_counter() - t, out
60
+
61
+
62
+ class MemSampler(threading.Thread):
63
+ def __init__(self, pid):
64
+ super().__init__(daemon=True); self.pid, self.peak, self.stop = str(pid), 0, False
65
+
66
+ def run(self):
67
+ while not self.stop:
68
+ try:
69
+ txt = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"],
70
+ capture_output=True, text=True, timeout=10).stdout
71
+ for line in txt.splitlines():
72
+ p, m = [x.strip() for x in line.split(",")[:2]]
73
+ if p == self.pid: self.peak = max(self.peak, int(m))
74
+ except Exception: # noqa: BLE001
75
+ pass
76
+ time.sleep(0.2)
77
+
78
+
79
+ def pct(xs, f):
80
+ xs = sorted(xs)
81
+ return xs[min(len(xs) - 1, int(round(f * (len(xs) - 1))))] if xs else None
82
+
83
+
84
+ def run(a):
85
+ reqs = [json.loads(l) for l in open(a.requests, encoding="utf-8")]
86
+ if a.limit: reqs = reqs[: a.limit]
87
+ sampler = None
88
+ if a.pid:
89
+ sampler = MemSampler(a.pid); sampler.start()
90
+ for body in reqs[:10]: # warm-up (not counted)
91
+ post(a.url, body)
92
+ res = {"label": a.label, "url": a.url, "requests": len(reqs), "levels": {}}
93
+ for c in [int(x) for x in a.concurrency.split(",")]:
94
+ lat, codes, toks = [], {}, 0
95
+ t0 = time.perf_counter()
96
+ with ThreadPoolExecutor(c) as ex:
97
+ for code, dt, out in ex.map(lambda b: post(a.url, b), reqs):
98
+ codes[code] = codes.get(code, 0) + 1
99
+ if code == 200:
100
+ lat.append(dt); toks += out.get("usage", {}).get("input_tokens", 0)
101
+ wall = time.perf_counter() - t0
102
+ lv = {"wall_s": round(wall, 2), "ok": codes.get(200, 0), "status_counts": {str(k): v for k, v in codes.items()},
103
+ "req_per_s": round(codes.get(200, 0) / wall, 2), "input_tokens_per_s": round(toks / wall),
104
+ "latency_ms": {"p50": round(1000 * pct(lat, 0.5), 1), "p95": round(1000 * pct(lat, 0.95), 1),
105
+ "p99": round(1000 * pct(lat, 0.99), 1), "mean": round(1000 * statistics.mean(lat), 1),
106
+ "max": round(1000 * max(lat), 1)} if lat else None}
107
+ res["levels"][str(c)] = lv
108
+ print(f"[{a.label}] concurrency {c:3d}: {lv['req_per_s']:7.2f} req/s, {lv['input_tokens_per_s']:8d} tok/s, "
109
+ f"p50 {lv['latency_ms']['p50'] if lat else '-'} ms, p95 {lv['latency_ms']['p95'] if lat else '-'} ms, statuses {lv['status_counts']}", flush=True)
110
+ if sampler:
111
+ sampler.stop = True; time.sleep(0.3)
112
+ res["peak_gpu_mem_mib"] = sampler.peak
113
+ try:
114
+ with urllib.request.urlopen(a.url + "/v1/models", timeout=30) as r:
115
+ res["models"] = json.loads(r.read())
116
+ except Exception: # noqa: BLE001
117
+ pass
118
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
119
+ Path(a.out).write_text(json.dumps(res, indent=1) + "\n")
120
+
121
+
122
+ def table(a):
123
+ rs = [json.loads(Path(p).read_text()) for p in a.files]
124
+ print(f"{'server':12s} {'conc':>4s} {'req/s':>8s} {'tok/s':>9s} {'p50 ms':>8s} {'p95 ms':>8s} {'ok':>5s} peak MiB")
125
+ for r in rs:
126
+ for c, lv in r["levels"].items():
127
+ L = lv["latency_ms"] or {}
128
+ print(f"{r['label']:12s} {c:>4s} {lv['req_per_s']:8.2f} {lv['input_tokens_per_s']:9d} {L.get('p50', 0):8.1f} {L.get('p95', 0):8.1f} "
129
+ f"{lv['ok']:5d} {r.get('peak_gpu_mem_mib', '-')}")
130
+ if len(rs) == 2:
131
+ base, new = rs
132
+ sp = {c: round(new["levels"][c]["req_per_s"] / max(1e-9, base["levels"][c]["req_per_s"]), 2) for c in base["levels"] if c in new["levels"]}
133
+ print(f"throughput {new['label']} / {base['label']}: {sp}")
134
+
135
+
136
+ def main():
137
+ ap = argparse.ArgumentParser()
138
+ sub = ap.add_subparsers(dest="cmd", required=True)
139
+ b = sub.add_parser("build"); b.add_argument("--out", required=True); b.add_argument("--n", type=int, default=400); b.add_argument("--seed", type=int, default=0)
140
+ r = sub.add_parser("run"); r.add_argument("--url", required=True); r.add_argument("--requests", required=True)
141
+ r.add_argument("--concurrency", default="1,8,32"); r.add_argument("--pid", type=int); r.add_argument("--label", default="server")
142
+ r.add_argument("--out", required=True); r.add_argument("--limit", type=int, default=0)
143
+ t = sub.add_parser("table"); t.add_argument("files", nargs="+")
144
+ a = ap.parse_args()
145
+ {"build": build, "run": run, "table": table}[a.cmd](a)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ sys.exit(main())
verdin/tests/eval_rows.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score Verdin on our eval suites and compare question by question with a kev run's stored rows (GPU acceptance).
2
+
3
+ python -m verdin.tests.eval_rows --model runs/verdin-4b-s1 --rows-root results/eval/minijev-combo-s-di-4b-s1 \\
4
+ --out results/verdin/eval-s1 [--suites robust-v1,hard-v1] [--batch 16]
5
+
6
+ For every suite whose stored rows.json exists: run all its records through Verdin (the checkpoint's render settings;
7
+ probabilities at T = 1 like the stored rows), then on the questions both answered: argmax agreement, |dp|
8
+ distribution, and accuracy of each (argmax == stored label). Acceptance (bf16 serving vs kev's evals): same argmax
9
+ >= 99.5 % and |accuracy difference| <= 0.2 pp per suite. Writes <out>/<suite>.json, <out>/<suite>.rows.json
10
+ (Verdin's own rows) and <out>/summary.json.
11
+ """
12
+ import argparse
13
+ import json
14
+ import math
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+
19
+ ROOT = Path(__file__).resolve().parents[2]
20
+ K = "third_party/kev/evals"
21
+ SUITES = { # stored-rows name -> records (as minijev.evaluate read them for the kev run's evals)
22
+ "decision-v7": f"{K}/v7/decision-v7/development.jsonl",
23
+ "transfer-v4": f"{K}/v4/transfer-v4/development.jsonl",
24
+ "transfer-v9": f"{K}/v9/transfer-v9/development.jsonl",
25
+ "minijev-frozen": "data/frozen/minijev-frozen-v1.jsonl",
26
+ "jevbench-public": "data/frozen/jevbench-public-v1.jsonl",
27
+ "typed-decisions": "data/external/typed-decisions.jsonl",
28
+ "multilingual-v1": "data/frozen/multilingual-v1.jsonl",
29
+ "transfer-v4-xl": "data/frozen/transfer-v4-xl.jsonl",
30
+ "robust-v1": "data/frozen/robust-v1.jsonl",
31
+ "hard-v1": f"{K}/hard-v1/development.jsonl",
32
+ "documents-v1": f"{K}/documents-v1/development.jsonl",
33
+ "devtools-v1": f"{K}/devtools-v1/development.jsonl",
34
+ "wg-v1.heldout": "data/newdata/wg-v1.heldout.clean.jsonl",
35
+ "dq-v1.heldout": "data/newdata/dq-v1.heldout.clean.jsonl",
36
+ "sg-v1.heldout": "data/newdata/sg-v1.heldout.clean.jsonl",
37
+ "safety-v1.heldout": "data/newdata/safety-v1.heldout.clean.jsonl",
38
+ "score-v1.heldout": "data/scoregen/score-v1.heldout.jsonl",
39
+ "diskills-v1.heldout": "data/diskills/diskills-v1.heldout.jsonl",
40
+ }
41
+ CORE5 = ("transfer-v4", "transfer-v9", "jevbench-public", "typed-decisions", "multilingual-v1")
42
+
43
+
44
+ def load(path):
45
+ out = []
46
+ for n, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines()):
47
+ if not line.strip(): continue
48
+ r = json.loads(line)
49
+ r["_id"] = r.get("_meta", {}).get("id", f"custom/{n}")
50
+ out.append(r)
51
+ return out
52
+
53
+
54
+ def api_request(r):
55
+ return {"state": r["state"], "questions": {k: {f: v for f, v in q.items() if f in ("type", "instructions", "criteria")}
56
+ for k, q in r["questions"].items()}}
57
+
58
+
59
+ def softmax(z):
60
+ m = max(z); e = [math.exp(x - m) for x in z]; s = sum(e)
61
+ return [x / s for x in e]
62
+
63
+
64
+ def main():
65
+ ap = argparse.ArgumentParser()
66
+ ap.add_argument("--model", required=True)
67
+ ap.add_argument("--rows-root", required=True, help="results/eval/<kev label>: <suite>/rows.json")
68
+ ap.add_argument("--out", required=True)
69
+ ap.add_argument("--suites", default="all")
70
+ ap.add_argument("--batch", type=int, default=16)
71
+ ap.add_argument("--dtype", default="auto")
72
+ ap.add_argument("--device", default=None)
73
+ ap.add_argument("--min-agree", type=float, default=0.995)
74
+ ap.add_argument("--max-acc-delta-pp", type=float, default=0.2)
75
+ ap.add_argument("--tie-margin", type=float, default=0.02, help="diagnostic: agreement where kev's top-2 gap exceeds this")
76
+ a, rest = ap.parse_known_args()
77
+ sys.path.insert(0, str(ROOT))
78
+ from verdin import Verdin
79
+ from verdin.render import RequestError
80
+ opts = {}
81
+ for kv in rest: # extra engine options: --opt key=value
82
+ k, _, v = kv.lstrip("-").partition("=")
83
+ opts[k.replace("-", "_")] = int(v) if v.isdigit() else v
84
+ v = Verdin.from_pretrained(a.model, device=a.device, dtype=a.dtype, prefix_cache=0, **opts)
85
+ v.engine.warmup()
86
+ print(f"verdin: {json.dumps(v.engine.describe())}", flush=True)
87
+ out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
88
+ names = list(SUITES) if a.suites == "all" else a.suites.split(",")
89
+ summary = {"model": a.model, "rows_root": a.rows_root, "engine": v.engine.describe(), "suites": {}}
90
+ for name in names:
91
+ rows_f = Path(a.rows_root) / name / "rows.json"
92
+ if not rows_f.exists() or not (ROOT / SUITES[name]).exists():
93
+ print(f"skip {name}: no stored rows or records", flush=True); continue
94
+ stored = {(x["id"], x["question"]): x for x in json.loads(rows_f.read_text())}
95
+ recs = load(ROOT / SUITES[name])
96
+ encs, keep, refused = [], [], 0
97
+ for r in recs:
98
+ try:
99
+ encs.append(v.encode(api_request(r))); keep.append(r)
100
+ except RequestError:
101
+ refused += 1
102
+ order = sorted(range(len(encs)), key=lambda i: encs[i].n_tokens)
103
+ res = [None] * len(encs)
104
+ t = time.time()
105
+ for s in range(0, len(order), a.batch):
106
+ idx = order[s:s + a.batch]
107
+ for i, rr in zip(idx, v.run([encs[i] for i in idx])):
108
+ res[i] = rr if rr.error is None else None
109
+ v.engine.sync()
110
+ secs = time.time() - t
111
+ my_rows, n, agree, ck, cv, dps, n_m, agree_m = [], 0, 0, 0, 0, [], 0, 0
112
+ for r, rr in zip(keep, res):
113
+ if rr is None: continue
114
+ for qid, z in zip(r["questions"], rr.logits):
115
+ p = softmax(z)
116
+ my_rows.append({"id": r["_id"], "question": qid, "p": p, "logits": z})
117
+ s_ = stored.get((r["_id"], qid))
118
+ if s_ is None: continue
119
+ n += 1
120
+ pk = s_["p"]
121
+ ak, av = max(range(len(pk)), key=lambda i: pk[i]), max(range(len(p)), key=lambda i: p[i])
122
+ agree += ak == av
123
+ ck += ak == s_["label"]; cv += av == s_["label"]
124
+ top = sorted(pk, reverse=True)
125
+ if len(top) < 2 or top[0] - top[1] > a.tie_margin: # kev's own decision is not a near-tie
126
+ n_m += 1; agree_m += ak == av
127
+ dps.append(max(abs(x - y) for x, y in zip(pk, p)))
128
+ dps.sort()
129
+ q = lambda f: dps[min(len(dps) - 1, int(f * len(dps)))] if dps else None
130
+ kev_report = json.loads((rows_f.parent / "report.json").read_text()) if (rows_f.parent / "report.json").exists() else {}
131
+ rep = {"records": len(recs), "verdin_answered": sum(x is not None for x in res), "verdin_refused": refused + sum(x is None for x in res),
132
+ "stored_questions": len(stored), "common_questions": n, "argmax_agree": agree / n if n else None,
133
+ f"argmax_agree_kev_margin_gt_{a.tie_margin}": agree_m / n_m if n_m else None, "questions_margin_gt": n_m,
134
+ "acc_kev": ck / n if n else None, "acc_verdin": cv / n if n else None,
135
+ "acc_delta_pp": 100 * (cv - ck) / n if n else None, "max_abs_dp": dps[-1] if dps else None,
136
+ "median_abs_dp": q(0.5), "p99_abs_dp": q(0.99), "seconds": round(secs, 1),
137
+ "records_per_s": round(len(encs) / secs, 1) if secs else None,
138
+ "kev_report_acc": kev_report.get("clean", {}).get("acc")}
139
+ rep["pass"] = bool(n) and rep["argmax_agree"] >= a.min_agree and abs(rep["acc_delta_pp"]) <= a.max_acc_delta_pp
140
+ (out / f"{name}.json").write_text(json.dumps(rep, indent=1) + "\n")
141
+ (out / f"{name}.rows.json").write_text(json.dumps(my_rows))
142
+ summary["suites"][name] = rep
143
+ print(f"{name:22s} n={n:5d} agree={rep['argmax_agree']:.4f} acc kev={rep['acc_kev']:.4f} verdin={rep['acc_verdin']:.4f} "
144
+ f"(d {rep['acc_delta_pp']:+.2f} pp) max|dp|={rep['max_abs_dp']:.4f} med={rep['median_abs_dp']:.1e} "
145
+ f"{rep['records_per_s']} rec/s {'PASS' if rep['pass'] else 'FAIL'}", flush=True)
146
+ s = summary["suites"]
147
+ c5 = [s[x] for x in CORE5 if x in s]
148
+ if len(c5) == len(CORE5):
149
+ summary["core5_acc_kev"] = sum(x["acc_kev"] for x in c5) / 5
150
+ summary["core5_acc_verdin"] = sum(x["acc_verdin"] for x in c5) / 5
151
+ summary["all_pass"] = all(x["pass"] for x in s.values()) if s else False
152
+ (out / "summary.json").write_text(json.dumps(summary, indent=1) + "\n")
153
+ print(json.dumps({k: summary[k] for k in summary if k not in ("suites", "engine")}, indent=1))
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
verdin/tests/make_tiny.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A random tiny Verdin checkpoint around a real tokenizer.json (server / wire-format tests without the 4B weights).
2
+
3
+ python -m verdin.tests.make_tiny --tokenizer runs/verdin-4b-s1/tokenizer.json --out /tmp/verdin-tiny
4
+ """
5
+ import argparse
6
+ import json
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ from verdin.config import CONFIG_NAME, FORMAT, FORMAT_VERSION
11
+ from verdin.convert import QWEN_SPECIALS
12
+
13
+
14
+ def make_tiny_checkpoint(out, tokenizer_json, seed=0, render=None, vocab=248320, unknown=False):
15
+ import torch
16
+ from safetensors.torch import save_file
17
+ torch.manual_seed(seed)
18
+ out = Path(out); out.mkdir(parents=True, exist_ok=True)
19
+ d, inter, lt = 64, 96, ["linear_attention"] * 3 + ["full_attention"]
20
+ H, KV, D, nk, nv, dk, dv = 4, 2, 32, 2, 4, 16, 16
21
+ arch = {"type": "qwen3_5_text", "hidden_size": d, "num_hidden_layers": len(lt), "layer_types": lt, "intermediate_size": inter,
22
+ "num_attention_heads": H, "num_key_value_heads": KV, "head_dim": D, "rms_norm_eps": 1e-6, "rope_theta": 10000000,
23
+ "partial_rotary_factor": 0.25, "linear_num_key_heads": nk, "linear_num_value_heads": nv, "linear_key_head_dim": dk,
24
+ "linear_value_head_dim": dv, "linear_conv_kernel_dim": 4, "vocab_size": vocab, "attn_output_gate": True, "hidden_act": "silu"}
25
+ r = lambda *s: torch.randn(*s) * 0.08
26
+ W = {"embed_tokens.weight": r(vocab, d), "norm.weight": r(d)}
27
+ C = 2 * nk * dk + nv * dv
28
+ for i, kind in enumerate(lt):
29
+ p = f"layers.{i}."
30
+ W[p + "input_layernorm.weight"] = r(d); W[p + "post_attention_layernorm.weight"] = r(d)
31
+ W[p + "mlp.gate_proj.weight"] = r(inter, d); W[p + "mlp.up_proj.weight"] = r(inter, d); W[p + "mlp.down_proj.weight"] = r(d, inter)
32
+ if kind == "linear_attention":
33
+ m = p + "linear_attn."
34
+ W[m + "in_proj_qkv.weight"] = r(C, d); W[m + "in_proj_z.weight"] = r(nv * dv, d)
35
+ W[m + "in_proj_b.weight"] = r(nv, d); W[m + "in_proj_a.weight"] = r(nv, d)
36
+ W[m + "out_proj.weight"] = r(d, nv * dv); W[m + "conv1d.weight"] = r(C, 1, 4) * 4
37
+ W[m + "A_log"] = torch.rand(nv) * 2 - 1; W[m + "dt_bias"] = r(nv); W[m + "norm.weight"] = 1 + r(dv)
38
+ else:
39
+ m = p + "self_attn."
40
+ W[m + "q_proj.weight"] = r(2 * H * D, d); W[m + "k_proj.weight"] = r(KV * D, d); W[m + "v_proj.weight"] = r(KV * D, d)
41
+ W[m + "o_proj.weight"] = r(d, H * D); W[m + "q_norm.weight"] = r(D); W[m + "k_norm.weight"] = r(D)
42
+ save_file({k: v.contiguous() for k, v in W.items()}, str(out / "model.safetensors"))
43
+ head = {"q.weight": r(16, d) * 3, "q.bias": r(16), "k.weight": r(16, d) * 3, "k.bias": r(16)}
44
+ if unknown:
45
+ head["unk_key"] = r(16) * 5; head["unk_bias"] = torch.tensor(0.1)
46
+ save_file(head, str(out / "head.safetensors"))
47
+ shutil.copyfile(tokenizer_json, out / "tokenizer.json")
48
+ render = render or {"schema_first": True, "date_facts": True, "max_state": 65536, "max_branch": 66560,
49
+ "max_packed": 131072, "schema_max": 512, "lead_ids": []}
50
+ cfg = {"format": FORMAT, "format_version": FORMAT_VERSION, "model_name": "Verdin-tiny-random", "architecture": arch,
51
+ "weights": {"file": "model.safetensors", "dtype": "float32"},
52
+ "head": {"file": "head.safetensors", "dim": 16, "unknown": unknown, "temperature": 1.5},
53
+ "tokenizer": {"file": "tokenizer.json", "specials": QWEN_SPECIALS}, "render": render,
54
+ "source": {"kev_run": None, "note": "random weights for tests"}}
55
+ (out / CONFIG_NAME).write_text(json.dumps(cfg, indent=1))
56
+ return out
57
+
58
+
59
+ if __name__ == "__main__":
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--tokenizer", required=True)
62
+ ap.add_argument("--out", required=True)
63
+ a = ap.parse_args()
64
+ print(make_tiny_checkpoint(a.out, a.tokenizer))
verdin/tests/mlx_bench.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mac serving benchmark for any /v1/systemone server (Verdin on MLX, or the old minijev.mac_serve_mlx path), same
2
+ requests for both. Run the client on the Mac itself (localhost), one server at a time.
3
+
4
+ python -m verdin.tests.mlx_bench build --model ~/models/verdin-4b --out results/verdin/mlx/bench-requests.jsonl
5
+ python -m verdin.tests.mlx_bench run --url http://127.0.0.1:8911 --requests .../bench-requests.jsonl --pid <server pid> \\
6
+ --label verdin-mlx --out results/verdin/mlx/bench-verdin.json [--concurrency 1,4,8]
7
+ python -m verdin.tests.mlx_bench table results/verdin/mlx/bench-old.json results/verdin/mlx/bench-verdin.json
8
+
9
+ Request classes (token counts with the checkpoint's renderer, date facts applied by the server):
10
+ short one question, state < 300 tokens (robust-v1, multilingual-v1)
11
+ medium 2-6 questions, state 400-4,000 tokens (typed-decisions, diskills held-out)
12
+ long states >= 5,000 tokens and <= 8,100 tokens in all (diskills held-out, jevbench-public): within kev.serve's
13
+ 8,192-token caps, so both servers answer every one
14
+ xlong over 8,192 tokens (diskills held-out, jevbench-public up to 20k, and documents-v1 states concatenated to
15
+ ~25k tokens): Verdin's caps only; kev.serve refuses them (422)
16
+ Measured: per class, single-request latency (client wall clock, requests one after another, every state new to the
17
+ server) p50 / p95 / mean; throughput on the short+medium+long mix at each concurrency; the server process's peak memory
18
+ footprint (macOS `footprint`, includes Metal buffers), sampled every 0.5 s; for Verdin also MLX's own peak counter.
19
+ Each phase starts after --cooldown idle seconds: on an M5 Max MacBook Pro the GPU drops from ~55 to ~26 bf16 TFLOPS after
20
+ about 5 s of sustained load, so bursts and sustained runs differ by up to 2x.
21
+ """
22
+ import argparse
23
+ import json
24
+ import random
25
+ import re
26
+ import statistics
27
+ import subprocess
28
+ import sys
29
+ import threading
30
+ import time
31
+ import urllib.request
32
+ from concurrent.futures import ThreadPoolExecutor
33
+ from pathlib import Path
34
+
35
+ ROOT = Path(__file__).resolve().parents[2]
36
+ sys.path.insert(0, str(ROOT))
37
+
38
+ from verdin.tests.bench import pct, post # noqa: E402
39
+
40
+
41
+ def _load(path):
42
+ return [json.loads(l) for l in open(ROOT / path, encoding="utf-8") if l.strip()]
43
+
44
+
45
+ def build(a):
46
+ from verdin.config import VerdinConfig
47
+ from verdin.render import Renderer, RenderConfig, RequestError, Tokenizer
48
+ from verdin.tests.eval_rows import api_request
49
+ cfg = VerdinConfig.load(a.model)
50
+ rd = Renderer(Tokenizer(cfg.file(cfg.tokenizer["file"]), cfg.tokenizer["specials"]), RenderConfig.from_dict(cfg.render))
51
+ rng = random.Random(a.seed)
52
+
53
+ def info(req):
54
+ try:
55
+ e = rd.encode_request(req)
56
+ except RequestError:
57
+ return None
58
+ return e.n_state, e.n_tokens, len(e.rows)
59
+ out = []
60
+
61
+ def take(cls, path, n, pred):
62
+ recs = _load(path)
63
+ rng.shuffle(recs)
64
+ k = 0
65
+ for r in recs:
66
+ req = api_request(r)
67
+ x = info(req)
68
+ if x and pred(*x):
69
+ out.append({**req, "_class": cls, "_src": path, "_state_tokens": x[0], "_tokens": x[1], "_questions": x[2]}); k += 1
70
+ if k == n:
71
+ break
72
+ take("short", "data/frozen/robust-v1.jsonl", a.n_short // 2, lambda s, t, q: q == 1 and s < 300)
73
+ take("short", "data/frozen/multilingual-v1.jsonl", a.n_short - a.n_short // 2, lambda s, t, q: q == 1 and s < 300)
74
+ take("medium", "data/external/typed-decisions.jsonl", a.n_medium // 2, lambda s, t, q: q >= 2 and 400 <= s <= 4000)
75
+ take("medium", "data/diskills/diskills-v1.heldout.jsonl", a.n_medium - a.n_medium // 2, lambda s, t, q: q >= 2 and 400 <= s <= 4000)
76
+ take("long", "data/diskills/diskills-v1.heldout.jsonl", a.n_long, lambda s, t, q: s >= 5000 and t <= 8100)
77
+ take("long", "data/frozen/jevbench-public-v1.jsonl", 4, lambda s, t, q: s >= 5000 and t <= 8100)
78
+ take("xlong", "data/diskills/diskills-v1.heldout.jsonl", 6, lambda s, t, q: t > 8192)
79
+ take("xlong", "data/frozen/jevbench-public-v1.jsonl", 3, lambda s, t, q: t > 8192)
80
+ # xlong: documents-v1 states concatenated to ~32k tokens, one question
81
+ docs = _load("third_party/kev/evals/documents-v1/development.jsonl")
82
+ rng.shuffle(docs)
83
+ for j in range(a.n_xlong):
84
+ parts, n = [], 0
85
+ for d in docs[j * 60:]:
86
+ st = d["state"] if isinstance(d["state"], str) else json.dumps(d["state"], ensure_ascii=False)
87
+ parts.append(st)
88
+ n += len(st) // 3
89
+ if n > 34000:
90
+ break
91
+ req = {"state": {"documents": parts}, "questions": {"q": {"type": "noul", "instructions": "Does any of these documents mention a deadline?"}}}
92
+ x = info(req)
93
+ while x is None or x[0] > 32768: # trim to the 32k target
94
+ parts = parts[:-1]; req["state"]["documents"] = parts; x = info(req)
95
+ out.append({**req, "_class": "xlong", "_src": "documents-v1 concatenated", "_state_tokens": x[0], "_tokens": x[1], "_questions": x[2]})
96
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
97
+ with open(a.out, "w", encoding="utf-8") as f:
98
+ for r in out:
99
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
100
+ for cls in ("short", "medium", "long", "xlong"):
101
+ xs = [r for r in out if r["_class"] == cls]
102
+ st = sorted(r["_state_tokens"] for r in xs)
103
+ print(f"{cls:7s} {len(xs):3d} requests, state tokens median {st[len(st) // 2]}, max {st[-1]}, questions {sum(r['_questions'] for r in xs)}")
104
+ print(f"-> {a.out}")
105
+
106
+
107
+ _FP = re.compile(r"Footprint:\s*([\d.]+)\s*([KMGT]?B)")
108
+ _UNIT = {"B": 1, "KB": 1 << 10, "MB": 1 << 20, "GB": 1 << 30, "TB": 1 << 40}
109
+
110
+
111
+ def footprint(pid):
112
+ try:
113
+ txt = subprocess.run(["footprint", "-p", str(pid)], capture_output=True, text=True, timeout=20).stdout
114
+ m = _FP.search(txt)
115
+ return float(m.group(1)) * _UNIT[m.group(2)] if m else None
116
+ except Exception: # noqa: BLE001
117
+ return None
118
+
119
+
120
+ class MemSampler(threading.Thread):
121
+ def __init__(self, pid):
122
+ super().__init__(daemon=True); self.pid, self.peak, self.stop, self.n = pid, 0.0, False, 0
123
+
124
+ def run(self):
125
+ while not self.stop:
126
+ f = footprint(self.pid)
127
+ if f:
128
+ self.peak = max(self.peak, f); self.n += 1
129
+ time.sleep(0.5)
130
+
131
+
132
+ def models(url):
133
+ try:
134
+ with urllib.request.urlopen(url + "/v1/models", timeout=30) as r:
135
+ return json.loads(r.read())
136
+ except Exception: # noqa: BLE001
137
+ return None
138
+
139
+
140
+ def lat_stats(xs):
141
+ return {"n": len(xs), "p50": round(1000 * pct(xs, 0.5), 1), "p95": round(1000 * pct(xs, 0.95), 1),
142
+ "mean": round(1000 * statistics.mean(xs), 1), "max": round(1000 * max(xs), 1)} if xs else None
143
+
144
+
145
+ def run(a):
146
+ reqs = [json.loads(l) for l in open(a.requests, encoding="utf-8")]
147
+ res = {"label": a.label, "url": a.url, "requests": len(reqs), "single": {}, "concurrency": {}}
148
+ sampler = None
149
+ if a.pid:
150
+ res["footprint_idle_gb"] = round((footprint(a.pid) or 0) / 2**30, 2)
151
+ sampler = MemSampler(a.pid); sampler.start()
152
+ for body in [r for r in reqs if r["_class"] == "short"][:5]: # warm-up (not counted)
153
+ post(a.url, body)
154
+ # single-request latency, one class after another
155
+ for cls in ("short", "medium", "long", "xlong"):
156
+ xs = [r for r in reqs if r["_class"] == cls]
157
+ time.sleep(a.cooldown) # the M5 Max sustains ~half its burst GPU throughput after ~5 s of load
158
+ lat, codes, server_ms = [], {}, []
159
+ for body in xs:
160
+ code, dt, out = post(a.url, body)
161
+ codes[code] = codes.get(code, 0) + 1
162
+ if code == 200:
163
+ lat.append(dt)
164
+ if "compute_ms" in out or "latency_ms" in out:
165
+ server_ms.append(out.get("compute_ms", out.get("latency_ms")))
166
+ res["single"][cls] = {"latency_ms": lat_stats(lat), "status_counts": {str(k): v for k, v in codes.items()},
167
+ "server_ms_median": statistics.median(server_ms) if server_ms else None,
168
+ "state_tokens_median": statistics.median(r["_state_tokens"] for r in xs) if xs else None}
169
+ L = res["single"][cls]["latency_ms"] or {}
170
+ print(f"[{a.label}] single {cls:7s}: p50 {L.get('p50')} ms, p95 {L.get('p95')} ms, mean {L.get('mean')} ms, statuses {codes}", flush=True)
171
+ # throughput on the mix
172
+ mix = [r for r in reqs if r["_class"] in ("short", "medium", "long")]
173
+ for c in [int(x) for x in a.concurrency.split(",")]:
174
+ time.sleep(a.cooldown)
175
+ lat, codes, toks = [], {}, 0
176
+ t0 = time.perf_counter()
177
+ with ThreadPoolExecutor(c) as ex:
178
+ for code, dt, out in ex.map(lambda b: post(a.url, b), mix):
179
+ codes[code] = codes.get(code, 0) + 1
180
+ if code == 200:
181
+ lat.append(dt); toks += out.get("usage", {}).get("input_tokens", 0)
182
+ wall = time.perf_counter() - t0
183
+ lv = {"wall_s": round(wall, 2), "ok": codes.get(200, 0), "status_counts": {str(k): v for k, v in codes.items()},
184
+ "req_per_s": round(codes.get(200, 0) / wall, 2), "input_tokens_per_s": round(toks / wall), "latency_ms": lat_stats(lat)}
185
+ res["concurrency"][str(c)] = lv
186
+ print(f"[{a.label}] concurrency {c}: {lv['req_per_s']} req/s, {lv['input_tokens_per_s']} tok/s, "
187
+ f"p50 {(lv['latency_ms'] or {}).get('p50')} ms, p95 {(lv['latency_ms'] or {}).get('p95')} ms, statuses {codes}", flush=True)
188
+ if sampler:
189
+ sampler.stop = True; time.sleep(0.6)
190
+ res["footprint_peak_gb"] = round(sampler.peak / 2**30, 2)
191
+ res["footprint_samples"] = sampler.n
192
+ res["models"] = models(a.url)
193
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
194
+ Path(a.out).write_text(json.dumps(res, indent=1) + "\n")
195
+ print(f"[{a.label}] footprint idle {res.get('footprint_idle_gb')} GB, peak {res.get('footprint_peak_gb')} GB -> {a.out}")
196
+
197
+
198
+ def table(a):
199
+ rs = [json.loads(Path(p).read_text()) for p in a.files]
200
+ print(f"{'server':14s} {'class':7s} {'p50 ms':>9s} {'p95 ms':>9s} {'mean ms':>9s} {'ok':>4s}")
201
+ for r in rs:
202
+ for cls, v in r["single"].items():
203
+ L = v["latency_ms"] or {}
204
+ print(f"{r['label']:14s} {cls:7s} {L.get('p50', '-'):>9} {L.get('p95', '-'):>9} {L.get('mean', '-'):>9} {L.get('n', 0):>4} {v['status_counts']}")
205
+ print(f"{'server':14s} {'conc':>4s} {'req/s':>7s} {'tok/s':>8s} {'p50 ms':>9s} {'p95 ms':>9s}")
206
+ for r in rs:
207
+ for c, lv in r["concurrency"].items():
208
+ L = lv["latency_ms"] or {}
209
+ print(f"{r['label']:14s} {c:>4s} {lv['req_per_s']:7.2f} {lv['input_tokens_per_s']:8d} {L.get('p50', '-'):>9} {L.get('p95', '-'):>9} {lv['status_counts']}")
210
+ for r in rs:
211
+ print(f"{r['label']:14s} footprint idle {r.get('footprint_idle_gb')} GB, peak {r.get('footprint_peak_gb')} GB")
212
+
213
+
214
+ def main():
215
+ ap = argparse.ArgumentParser()
216
+ sub = ap.add_subparsers(dest="cmd", required=True)
217
+ b = sub.add_parser("build"); b.add_argument("--model", required=True); b.add_argument("--out", required=True)
218
+ b.add_argument("--n-short", type=int, default=60); b.add_argument("--n-medium", type=int, default=40)
219
+ b.add_argument("--n-long", type=int, default=10); b.add_argument("--n-xlong", type=int, default=3); b.add_argument("--seed", type=int, default=0)
220
+ r = sub.add_parser("run"); r.add_argument("--url", required=True); r.add_argument("--requests", required=True)
221
+ r.add_argument("--concurrency", default="1,4,8"); r.add_argument("--pid", type=int); r.add_argument("--label", default="server")
222
+ r.add_argument("--out", required=True); r.add_argument("--cooldown", type=float, default=30, help="idle seconds before each phase")
223
+ t = sub.add_parser("table"); t.add_argument("files", nargs="+")
224
+ a = ap.parse_args()
225
+ {"build": build, "run": run, "table": table}[a.cmd](a)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
verdin/tests/mlx_parity.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MLX backend (Apple silicon) tests and parity against kev.
2
+
3
+ # 1. unit tests on tiny random models: MLX (GPU bf16 / GPU fp32 / CPU fp32) against Verdin's torch CPU fp32 backend,
4
+ # plus the varlen gated-delta Metal kernels against the ops recurrence and the state-bidirectional cases (needs
5
+ # torch + mlx; seconds; `bidir` runs only the state-bidirectional cases)
6
+ python -m verdin.tests.mlx_parity tiny
7
+
8
+ # 2. the record set (suite records whose stored kev GPU rows exist; all records of each suite by default)
9
+ python -m verdin.tests.mlx_parity select --rows-root results/verdin/mlx/kev-gpu-rows --out results/verdin/mlx/set.jsonl
10
+ # 3. Verdin MLX on the set (writes logits + T=1 probabilities per question)
11
+ python -m verdin.tests.mlx_parity verdin --model ~/models/verdin-4b --set .../set.jsonl --out .../rows-verdin.json
12
+ # 4. the old Mac path on the same set (minijev.mlx_kev: mlx-lm backbone, LoRA merged in bf16; T = 1)
13
+ PYTHONPATH=third_party/kev KEV_SCHEMA_FIRST=1 python -m verdin.tests.mlx_parity kev --run ~/models/<kev run> \\
14
+ --set .../set.jsonl --out .../rows-kev-mlx.json
15
+ # 5. per suite: argmax agreement / accuracy / |dp| against the stored kev GPU rows (and against the old Mac path)
16
+ python -m verdin.tests.mlx_parity compare --set .../set.jsonl --rows-root .../kev-gpu-rows --verdin .../rows-verdin.json \\
17
+ [--kev-mlx .../rows-kev-mlx.json] --out .../parity.json
18
+ # 6. any row sets against one reference (a rows file, numeric_parity's exact kev fp32 json, or "gpu" = stored rows)
19
+ python -m verdin.tests.mlx_parity vs --ref .../kev-fp32-cpu.json gpu .../rows-a.json .../rows-b.json
20
+
21
+ Steps 3 and 4 each load a 4B model: run them one after the other (one model at a time on the Mac).
22
+ """
23
+ import argparse
24
+ import json
25
+ import math
26
+ import os
27
+ import random
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ ROOT = Path(__file__).resolve().parents[2]
33
+ sys.path.insert(0, str(ROOT))
34
+
35
+ PARITY_SUITES = ("robust-v1", "jevbench-public", "typed-decisions", "hard-v1", "score-v1.heldout", "multilingual-v1")
36
+
37
+
38
+ def softmax(z):
39
+ m = max(z); e = [math.exp(x - m) for x in z]; s = sum(e)
40
+ return [x / s for x in e]
41
+
42
+
43
+ # ---------------------------------------------------------------------------------------------------------------------
44
+ # 1. tiny unit tests
45
+
46
+ def _tiny_weights(seed, d=128, inter=192, H=4, KV=2, D=64, nk=2, nv=4, dk=128, dv=128, vocab=300, n_layers=8, unknown=False):
47
+ import numpy as np
48
+ from verdin.config import Arch
49
+ rng = np.random.default_rng(seed)
50
+ lt = (["linear_attention"] * 3 + ["full_attention"]) * (n_layers // 4)
51
+ arch = Arch.from_dict({"type": "qwen3_5_text", "hidden_size": d, "num_hidden_layers": len(lt), "layer_types": lt,
52
+ "intermediate_size": inter, "num_attention_heads": H, "num_key_value_heads": KV, "head_dim": D,
53
+ "rms_norm_eps": 1e-6, "rope_theta": 10000000.0, "partial_rotary_factor": 0.25,
54
+ "linear_num_key_heads": nk, "linear_num_value_heads": nv, "linear_key_head_dim": dk,
55
+ "linear_value_head_dim": dv, "linear_conv_kernel_dim": 4, "vocab_size": vocab,
56
+ "attn_output_gate": True, "hidden_act": "silu"})
57
+ r = lambda *s, sd=0.08: (rng.standard_normal(s) * sd).astype(np.float32) # noqa: E731
58
+ W = {"embed_tokens.weight": r(vocab, d, sd=0.5), "norm.weight": r(d, sd=0.2)}
59
+ C = 2 * nk * dk + nv * dv
60
+ for i, kind in enumerate(lt):
61
+ p = f"layers.{i}."
62
+ W[p + "input_layernorm.weight"] = r(d, sd=0.2); W[p + "post_attention_layernorm.weight"] = r(d, sd=0.2)
63
+ W[p + "mlp.gate_proj.weight"] = r(inter, d); W[p + "mlp.up_proj.weight"] = r(inter, d); W[p + "mlp.down_proj.weight"] = r(d, inter)
64
+ if kind == "linear_attention":
65
+ m = p + "linear_attn."
66
+ W[m + "in_proj_qkv.weight"] = r(C, d); W[m + "in_proj_z.weight"] = r(nv * dv, d)
67
+ W[m + "in_proj_b.weight"] = r(nv, d); W[m + "in_proj_a.weight"] = r(nv, d)
68
+ W[m + "out_proj.weight"] = r(d, nv * dv); W[m + "conv1d.weight"] = r(C, 1, 4, sd=0.3)
69
+ W[m + "A_log"] = rng.uniform(-1, 1, nv).astype(np.float32); W[m + "dt_bias"] = r(nv, sd=0.5)
70
+ W[m + "norm.weight"] = 1 + r(dv, sd=0.2)
71
+ else:
72
+ m = p + "self_attn."
73
+ W[m + "q_proj.weight"] = r(2 * H * D, d); W[m + "k_proj.weight"] = r(KV * D, d); W[m + "v_proj.weight"] = r(KV * D, d)
74
+ W[m + "o_proj.weight"] = r(d, H * D); W[m + "q_norm.weight"] = r(D, sd=0.2); W[m + "k_norm.weight"] = r(D, sd=0.2)
75
+ head = {"q.weight": r(16, d, sd=0.2), "q.bias": r(16, sd=0.1), "k.weight": r(16, d, sd=0.2), "k.bias": r(16, sd=0.1)}
76
+ if unknown:
77
+ head["unk_key"] = r(16, sd=0.5); head["unk_bias"] = np.array(0.3, dtype=np.float32)
78
+ return arch, W, head
79
+
80
+
81
+ def _rand_request(rng, n_state, n_q, vocab=300):
82
+ from verdin.render import Encoded, Row
83
+ S = [rng.randrange(1, vocab) for _ in range(n_state)]
84
+ rows = []
85
+ for _ in range(n_q):
86
+ K = rng.randint(1, 5)
87
+ ids, opts = [rng.randrange(1, vocab) for _ in range(rng.randint(1, 6))], []
88
+ for _ in range(K):
89
+ ids += [rng.randrange(1, vocab) for _ in range(rng.randint(1, 7))]
90
+ opts.append(len(ids) - 1)
91
+ ids.append(rng.randrange(1, vocab))
92
+ rows.append(Row(ids, len(ids) - 1, opts))
93
+ return Encoded(S, rows)
94
+
95
+
96
+ def _torch_engine(arch, W, head, dtype="fp32", **kw):
97
+ import torch
98
+ from verdin.torch_backend import TorchEngine, TorchModel, TorchOptions
99
+ sd = {k: torch.from_numpy(v.copy()) for k, v in W.items()}
100
+ hd = {k: torch.from_numpy(v.copy()) for k, v in head.items()}
101
+ return TorchEngine(TorchModel(arch, lambda n: sd[n], hd, 1.0, TorchOptions(device="cpu", dtype=dtype, prefix_cache=0, **kw), "fp32"))
102
+
103
+
104
+ def _mlx_engine(arch, W, head, **kw):
105
+ import threading
106
+ from concurrent.futures import ThreadPoolExecutor
107
+
108
+ import mlx.core as mx
109
+ from verdin.mlx_backend import MLXEngine, MLXModel, MLXOptions
110
+ pool = ThreadPoolExecutor(max_workers=1)
111
+ tid = pool.submit(threading.get_ident).result()
112
+ opts = MLXOptions.from_kwargs(**{"prefix_cache": 0, **kw})
113
+ m = pool.submit(lambda: MLXModel(arch, lambda n: mx.array(W[n]), head, 1.0, opts, "float32")).result()
114
+ return MLXEngine(m, pool, tid)
115
+
116
+
117
+ def _maxdiff(ra, rb):
118
+ w = 0.0
119
+ for a, b in zip(ra, rb):
120
+ assert len(a.logits) == len(b.logits)
121
+ for za, zb in zip(a.logits, b.logits):
122
+ assert len(za) == len(zb)
123
+ w = max(w, max(abs(x - y) for x, y in zip(za, zb)))
124
+ if a.unknown is not None or b.unknown is not None:
125
+ w = max(w, max(abs(x - y) for x, y in zip(a.unknown, b.unknown)))
126
+ return w
127
+
128
+
129
+ def _kernel_test():
130
+ import mlx.core as mx
131
+ import numpy as np
132
+ from verdin.mlx_backend import gdr_varlen_metal, gdr_varlen_ops
133
+ rng = np.random.default_rng(0)
134
+ worst = {}
135
+ for Dk, Dv, Hk, Hv in ((128, 128, 2, 4), (64, 64, 2, 4), (16, 16, 2, 4), (128, 128, 16, 32)):
136
+ lens = [1, 7, 70, 129, 3]
137
+ T, S = sum(lens), len(lens)
138
+ cu = mx.array(np.concatenate([[0], np.cumsum(lens)]).astype(np.int32))
139
+ q = rng.standard_normal((T, Hk, Dk)).astype(np.float32); k = rng.standard_normal((T, Hk, Dk)).astype(np.float32)
140
+ q /= np.linalg.norm(q, axis=-1, keepdims=True) * Dk ** 0.5; k /= np.linalg.norm(k, axis=-1, keepdims=True)
141
+ v = rng.standard_normal((T, Hv, Dv)).astype(np.float32)
142
+ g = np.exp(-rng.uniform(0, 0.5, (T, Hv))).astype(np.float32); beta = rng.uniform(0, 1, (T, Hv)).astype(np.float32)
143
+ st = (rng.standard_normal((3, Hv, Dv, Dk)) * 0.3).astype(np.float32)
144
+ args = [mx.array(x) for x in (q, k, v, g, beta)]
145
+ for sidx, write in (([-1, 0, 2, -1, 1], True), ([0, 0, 1, 2, 2], False)):
146
+ si = mx.array(np.array(sidx, dtype=np.int32))
147
+ ym, fm = gdr_varlen_metal(*args, cu, si, mx.array(st), S, write)
148
+ with mx.stream(mx.cpu):
149
+ yo, fo = gdr_varlen_ops(*args, cu, si, mx.array(st), S, write)
150
+ mx.eval(yo, fo) if write else mx.eval(yo)
151
+ mx.eval(ym)
152
+ d = float(mx.abs(ym - yo).max())
153
+ if write:
154
+ d = max(d, float(mx.abs(fm - fo).max()))
155
+ worst[(Dk, Dv, Hk, Hv)] = max(worst.get((Dk, Dv, Hk, Hv), 0.0), d)
156
+ for key, d in worst.items():
157
+ kind = "packed" if key[0] == 128 else "scalar"
158
+ print(f" gdr varlen kernel ({kind}) Dk={key[0]} Dv={key[1]} Hk={key[2]} Hv={key[3]}: max |d| vs ops (CPU) = {d:.2e}")
159
+ assert d < 2e-4, key
160
+ return worst
161
+
162
+
163
+ def _bidir_test(B=16):
164
+ """State-bidirectional checkpoints (arch.state_bidir = B): MLX against the torch CPU fp32 backend with the same B
165
+ (itself checked against a hand-masked transformers reference by verdin/tests/test_bidir.py). States shorter than,
166
+ equal to and several times the block; one-block segments (mask-free), multi-block segments (explicit mask, query
167
+ chunked), several sweeps, prefix cache, duplicate states."""
168
+ import dataclasses
169
+ from verdin.render import Encoded
170
+ rng = random.Random(2)
171
+ reqs = [_rand_request(rng, n, q) for n, q in ((1, 1), (5, 2), (B, 3), (B + 1, 1), (40, 4), (3 * B + 7, 2), (70, 3), (200, 2))]
172
+ arch, W, head = _tiny_weights(0)
173
+ ab = dataclasses.replace(arch, state_bidir=B)
174
+ base = _torch_engine(ab, W, head).run(reqs)
175
+ moved = _maxdiff(_torch_engine(arch, W, head).run(reqs), base)
176
+ tb = _maxdiff(_torch_engine(ab, W, head, dtype="bf16").run(reqs), base)
177
+ print(f"state_bidir={B}: reference = verdin torch CPU fp32 bidir (bidir vs causal {moved:.2f}; torch bf16 drifts {tb:.2f})")
178
+ assert moved > 1e-2
179
+ failures = []
180
+ for label, mo, tol in (("cpu fp32", {"device": "cpu", "dtype": "fp32"}, 2e-4), ("gpu fp32", {"dtype": "fp32"}, 2e-3),
181
+ ("gpu bf16", {"dtype": "bf16"}, 2 * tb)):
182
+ scen = []
183
+ e = _mlx_engine(ab, W, head, **mo)
184
+ assert e.m.prefill_chunk % B == 0, e.m.prefill_chunk
185
+ scen.append(("one sweep (multi-block segments)", e.run(reqs), base))
186
+ scen.append(("one by one", [e.run([r])[0] for r in reqs], base))
187
+ e2 = _mlx_engine(ab, W, head, prefill_chunk=B, max_sweep_tokens=40, max_sweep_rows=3, **mo)
188
+ scen.append(("prefill_chunk = block, several sweeps", e2.run(reqs), base))
189
+ e3 = _mlx_engine(ab, W, head, prefill_chunk=3 * B, max_sweep_tokens=60, **mo)
190
+ e3.m.mask_elems = 7 * 64 # query-chunked prefill masks (and multi-row block masks)
191
+ scen.append(("prefill_chunk = 3 blocks, mask chunking", e3.run(reqs), base))
192
+ e4 = _mlx_engine(ab, W, head, prefix_cache=8, prefix_cache_min_tokens=0, prefill_chunk=B, max_sweep_tokens=40, **mo)
193
+ first = e4.run(reqs); again = e4.run(reqs)
194
+ assert all(r.cache_hit for r in again) and not any(r.cache_hit for r in first)
195
+ scen.append(("prefix cache second pass", again, base))
196
+ dup = Encoded(reqs[5].state_ids, reqs[4].rows)
197
+ batch = [reqs[5], dup, reqs[1], dup]
198
+ scen.append(("duplicate states in a batch", _mlx_engine(ab, W, head, prefill_chunk=B, max_sweep_tokens=30, **mo).run(batch),
199
+ _torch_engine(ab, W, head).run(batch)))
200
+ for name, got, want in scen:
201
+ d = _maxdiff(got, want)
202
+ print(f" bidir {label:10s} {name:42s} max |dlogit| {d:.2e}{'' if d < tol else ' FAIL (tol %g)' % tol}")
203
+ if d >= tol:
204
+ failures.append(("bidir", label, name, d))
205
+ # a prefill_chunk that splits a block is refused; the default (4096) is rounded to a multiple of the block
206
+ try:
207
+ _mlx_engine(ab, W, head, prefill_chunk=B + 3)
208
+ raise AssertionError("prefill_chunk not a multiple of the block was accepted")
209
+ except ValueError:
210
+ pass
211
+ assert _mlx_engine(dataclasses.replace(arch, state_bidir=24), W, head).m.prefill_chunk == 4080 # 170 x 24
212
+ assert _mlx_engine(dataclasses.replace(arch, state_bidir=8192), W, head).m.prefill_chunk == 8192
213
+ print(" bidir prefill_chunk checks: OK")
214
+ return failures
215
+
216
+
217
+ def bidir(a):
218
+ import mlx.core as mx
219
+ print(f"mlx {mx.__version__} on {mx.device_info().get('device_name')}")
220
+ failures = _bidir_test()
221
+ assert not failures, failures
222
+ print("mlx bidir tests: OK")
223
+
224
+
225
+ def tiny(a):
226
+ import mlx.core as mx
227
+ print(f"mlx {mx.__version__} on {mx.device_info().get('device_name')}")
228
+ _kernel_test()
229
+ rng = random.Random(0)
230
+ reqs = [_rand_request(rng, n, q) for n, q in ((1, 1), (5, 2), (70, 3), (130, 1), (64, 4), (200, 2), (333, 5))]
231
+ # (label, mlx options, tolerance on max |dlogit| vs torch CPU fp32); logits reach ~5-15 on these random models
232
+ modes = [("cpu fp32 (ops gdr, exact fp32 GEMM)", {"device": "cpu", "dtype": "fp32"}, 2e-4),
233
+ ("gpu fp32 (Metal kernels, MLX_ENABLE_TF32=0)", {"dtype": "fp32"}, 2e-3),
234
+ ("gpu bf16 (default: fp32 attention here)", {"dtype": "bf16"}, None), # None: 2 x the drift of Verdin's
235
+ ("gpu bf16, fp32 attention for states <= 64", {"dtype": "bf16", "attn_fp32_max_state": 64}, None), # torch bf16
236
+ ("gpu bf16 + bf16 attention", {"dtype": "bf16", "attn_dtype": "bf16"}, None)] # path's
237
+ failures = []
238
+ for dims in ({}, {"dk": 64, "dv": 64}):
239
+ kind = "packed" if dims.get("dk", 128) == 128 else "scalar"
240
+ arch, W, head = _tiny_weights(0, **dims)
241
+ ref = _torch_engine(arch, W, head)
242
+ base = ref.run(reqs)
243
+ zmax = max(abs(x) for r in base for z in r.logits for x in z)
244
+ tb = _maxdiff(_torch_engine(arch, W, head, dtype="bf16").run(reqs), base)
245
+ print(f"tiny model dk={arch.linear_key_head_dim} ({kind} kernel): reference = verdin torch CPU fp32 (max |logit| {zmax:.1f}; "
246
+ f"verdin torch CPU bf16 drifts {tb:.2f} from it)")
247
+ for label, mo, tol in modes:
248
+ tol = tol if tol is not None else 2 * tb
249
+ scen = []
250
+ e = _mlx_engine(arch, W, head, **mo)
251
+ scen.append(("batch of 7", e.run(reqs), base))
252
+ scen.append(("one by one", [e.run([r])[0] for r in reqs], base))
253
+ e2 = _mlx_engine(arch, W, head, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3, **mo)
254
+ scen.append(("multi-sweep (chunk 48, 80 tok, 3 rows)", e2.run(reqs), base))
255
+ e3 = _mlx_engine(arch, W, head, prefill_chunk=100, **mo)
256
+ e3.m.mask_elems = 40 * 64 # forces query-chunked masks of multi-row blocks
257
+ scen.append(("mask chunking", e3.run(reqs), base))
258
+ e4 = _mlx_engine(arch, W, head, prefix_cache=8, prefix_cache_min_tokens=0, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3, **mo)
259
+ first = e4.run(reqs); again = e4.run(reqs)
260
+ assert all(r.cache_hit for r in again) and not any(r.cache_hit for r in first)
261
+ scen.append(("prefix cache second pass (multi-sweep)", again, base))
262
+ from verdin.render import Encoded
263
+ dup = Encoded(reqs[4].state_ids, reqs[2].rows)
264
+ batch = [reqs[4], dup, reqs[1], dup]
265
+ scen.append(("duplicate states in a batch", _mlx_engine(arch, W, head, prefill_chunk=40, max_sweep_tokens=60, **mo).run(batch),
266
+ ref.run(batch)))
267
+ for name, got, want in scen:
268
+ d = _maxdiff(got, want)
269
+ print(f" {label:46s} {name:42s} max |dlogit| {d:.2e}{'' if d < tol else ' FAIL (tol %g)' % tol}")
270
+ if d >= tol:
271
+ failures.append((dims, label, name, d))
272
+ # unknown head
273
+ arch_u, W_u, head_u = _tiny_weights(1, unknown=True, **dims)
274
+ d = _maxdiff(_mlx_engine(arch_u, W_u, head_u, device="cpu", dtype="fp32").run(reqs[:4]), _torch_engine(arch_u, W_u, head_u).run(reqs[:4]))
275
+ print(f" unknown head (cpu fp32): max |d| {d:.2e}")
276
+ assert d < 2e-4
277
+ # out-of-memory policy (simulated): only the request that does not fit alone is refused
278
+ from verdin.mlx_backend import MLXMemoryError
279
+ arch, W, head = _tiny_weights(0)
280
+ e5 = _mlx_engine(arch, W, head)
281
+ real = e5._run
282
+
283
+ def fake(rs, keep=frozenset()):
284
+ if any(r.enc.n_state > 150 for r in rs):
285
+ raise MLXMemoryError("simulated")
286
+ return real(rs, keep)
287
+ e5._run = fake
288
+ res = e5.run(reqs)
289
+ assert [r.error is not None for r in res] == [e.n_state > 150 for e in reqs]
290
+ assert "too many tokens" in str(next(r.error for r in res if r.error is not None))
291
+ print(" simulated OOM: only the oversized requests refused")
292
+ failures += _bidir_test()
293
+ assert not failures, failures
294
+ print("mlx tiny tests: OK")
295
+
296
+
297
+ # ---------------------------------------------------------------------------------------------------------------------
298
+ # 2-5. the 4B parity
299
+
300
+ def select(a):
301
+ from verdin.tests.eval_rows import SUITES, api_request, load
302
+ names = a.suites.split(",") if a.suites else list(PARITY_SUITES)
303
+ out, rng = [], random.Random(a.seed)
304
+ for name in names:
305
+ rows_f = Path(a.rows_root) / name / "rows.json"
306
+ stored = {x["id"] for x in json.loads(rows_f.read_text())}
307
+ recs = [r for r in load(ROOT / SUITES[name]) if r["_id"] in stored]
308
+ if a.per_suite and len(recs) > a.per_suite:
309
+ recs = rng.sample(recs, a.per_suite)
310
+ for r in recs:
311
+ out.append({"suite": name, "id": r["_id"], "request": api_request(r)})
312
+ print(f"{name:20s} {len(recs)} records")
313
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
314
+ with open(a.out, "w", encoding="utf-8") as f:
315
+ for x in out:
316
+ f.write(json.dumps(x, ensure_ascii=False) + "\n")
317
+ print(f"{len(out)} records -> {a.out}")
318
+
319
+
320
+ def _read_set(path):
321
+ return [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()]
322
+
323
+
324
+ def run_verdin(a):
325
+ import mlx.core as mx
326
+ from verdin.mlx_backend import load_verdin
327
+ from verdin.render import RequestError
328
+ items = _read_set(a.set)
329
+ t0 = time.time()
330
+ v = load_verdin(a.model, prefix_cache=0, memory_limit_gb=a.memory_limit_gb, attn_dtype=a.attn_dtype, dtype=a.dtype,
331
+ prefill_chunk=a.prefill_chunk, max_sweep_tokens=a.max_sweep_tokens)
332
+ print(f"loaded in {time.time() - t0:.1f} s: {json.dumps(v.engine.describe())}", flush=True)
333
+ encs, keep, refused = [], [], []
334
+ for it in items:
335
+ try:
336
+ encs.append(v.encode(it["request"])); keep.append(it)
337
+ except RequestError as e:
338
+ refused.append({"suite": it["suite"], "id": it["id"], "error": str(e)})
339
+ order = sorted(range(len(encs)), key=lambda i: encs[i].n_tokens)
340
+ res = [None] * len(encs)
341
+ t = time.time(); done_tok = 0
342
+ batches = []
343
+ cur, cur_tok = [], 0
344
+ for i in order: # batches of <= a.batch requests and <= a.batch_tokens tokens
345
+ n = encs[i].n_tokens
346
+ if cur and (len(cur) >= a.batch or cur_tok + n > a.batch_tokens):
347
+ batches.append(cur); cur, cur_tok = [], 0
348
+ cur.append(i); cur_tok += n
349
+ if cur:
350
+ batches.append(cur)
351
+ for bi, idx in enumerate(batches):
352
+ for i, rr in zip(idx, v.run([encs[i] for i in idx])):
353
+ res[i] = rr
354
+ done_tok += encs[i].n_tokens
355
+ if encs[idx[-1]].n_tokens > 8192 or bi % 50 == 0:
356
+ v.engine.clear_cache()
357
+ print(f" batch {bi + 1}/{len(batches)}: {sum(x is not None for x in res)} records, {done_tok} tokens, "
358
+ f"{time.time() - t:.0f} s, peak {mx.get_peak_memory() / 2**30:.1f} GB", flush=True)
359
+ secs = time.time() - t
360
+ rows = []
361
+ for it, enc, rr in zip(keep, encs, res):
362
+ if rr.error is not None:
363
+ refused.append({"suite": it["suite"], "id": it["id"], "error": str(rr.error)}); continue
364
+ for qid, z in zip(it["request"]["questions"], rr.logits):
365
+ rows.append({"suite": it["suite"], "id": it["id"], "question": qid, "logits": z, "p": softmax(z)})
366
+ info = {"engine": v.engine.describe(), "seconds": round(secs, 1), "records": len(keep), "refused": refused,
367
+ "tokens": sum(e.n_tokens for e in encs), "peak_memory_gb": round(mx.get_peak_memory() / 2**30, 2)}
368
+ Path(a.out).write_text(json.dumps({"info": info, "rows": rows}))
369
+ print(json.dumps({k: info[k] for k in ("seconds", "records", "tokens", "peak_memory_gb")}), f"refused {len(refused)}", flush=True)
370
+
371
+
372
+ def run_kev_mlx(a):
373
+ """The old Mac path (minijev.mlx_kev, as minijev.mac_serve_mlx serves it) at T = 1 on the same requests, rendered
374
+ as kev.serve renders them (date facts on, strict encode with the Verdin caps)."""
375
+ if os.environ.get("KEV_SCHEMA_FIRST") != "1":
376
+ sys.exit("set KEV_SCHEMA_FIRST=1 (as COMBO-S runs were trained)")
377
+ import mlx.core as mx
378
+ from kev.api import SystemOneRequest, to_record, with_date_facts
379
+ from minijev.mlx_kev import load
380
+ if a.memory_limit_gb:
381
+ mx.set_memory_limit(int(a.memory_limit_gb * 2**30))
382
+ items = _read_set(a.set)
383
+ t0 = time.time()
384
+ ck, tok, model = load(a.run, temperature=1.0)
385
+ print(f"loaded in {time.time() - t0:.1f} s", flush=True)
386
+ rows, refused, t = [], [], time.time()
387
+ for n, it in enumerate(items):
388
+ req = SystemOneRequest(**it["request"])
389
+ req = req.model_copy(update={"state": with_date_facts(req.state)})
390
+ rec, _ = to_record(req)
391
+ try:
392
+ enc = model.encode(tok, rec, max_state=a.max_state, max_branch=a.max_branch, strict=True)
393
+ if len(enc["ids"]) > a.max_packed:
394
+ raise ValueError("packed too long")
395
+ except ValueError as e:
396
+ refused.append({"suite": it["suite"], "id": it["id"], "error": str(e)}); continue
397
+ zs = model.forward(enc)
398
+ for qid, z in zip(it["request"]["questions"], zs):
399
+ z = [float(x) for x in z.tolist()]
400
+ rows.append({"suite": it["suite"], "id": it["id"], "question": qid, "logits": z, "p": softmax(z)})
401
+ mx.clear_cache()
402
+ if n % 200 == 0:
403
+ print(f" {n + 1}/{len(items)} records, {time.time() - t:.0f} s, peak {mx.get_peak_memory() / 2**30:.1f} GB", flush=True)
404
+ info = {"seconds": round(time.time() - t, 1), "records": len(items) - len(refused), "refused": refused,
405
+ "peak_memory_gb": round(mx.get_peak_memory() / 2**30, 2), "path": "minijev.mlx_kev (mlx-lm backbone, bf16)"}
406
+ Path(a.out).write_text(json.dumps({"info": info, "rows": rows}))
407
+ print(json.dumps({k: info[k] for k in ("seconds", "records", "peak_memory_gb")}), f"refused {len(refused)}", flush=True)
408
+
409
+
410
+ def _stats(pairs, tie_margin=0.02):
411
+ """pairs: [(p_ref, p_new, label)] -> agreement, accuracies, |dp| distribution."""
412
+ n = len(pairs)
413
+ if not n:
414
+ return None
415
+ agree = ck = cv = n_m = agree_m = 0
416
+ dps = []
417
+ for pk, pv, lab in pairs:
418
+ ak = max(range(len(pk)), key=lambda i: pk[i]); av = max(range(len(pv)), key=lambda i: pv[i])
419
+ agree += ak == av
420
+ if lab is not None:
421
+ ck += ak == lab; cv += av == lab
422
+ top = sorted(pk, reverse=True)
423
+ if len(top) < 2 or top[0] - top[1] > tie_margin:
424
+ n_m += 1; agree_m += ak == av
425
+ dps.append(max(abs(x - y) for x, y in zip(pk, pv)))
426
+ dps.sort()
427
+ q = lambda f: dps[min(n - 1, int(f * n))] # noqa: E731
428
+ return {"questions": n, "argmax_agree": agree / n, "disagreements": n - agree, f"argmax_agree_ref_margin_gt_{tie_margin}": agree_m / n_m if n_m else None,
429
+ "acc_ref": ck / n, "acc_new": cv / n, "acc_delta_pp": 100 * (cv - ck) / n,
430
+ "max_abs_dp": dps[-1], "median_abs_dp": q(0.5), "p99_abs_dp": q(0.99), "mean_abs_dp": sum(dps) / n}
431
+
432
+
433
+ def compare(a):
434
+ items = _read_set(a.set)
435
+ suites = sorted({it["suite"] for it in items}, key=lambda s: list(PARITY_SUITES).index(s) if s in PARITY_SUITES else 99)
436
+ gpu = {}
437
+ for s in suites:
438
+ for x in json.loads((Path(a.rows_root) / s / "rows.json").read_text()):
439
+ gpu[(s, x["id"], x["question"])] = x
440
+ ver = json.loads(Path(a.verdin).read_text())
441
+ vrows = {(x["suite"], x["id"], x["question"]): x for x in ver["rows"]}
442
+ old = None
443
+ if a.kev_mlx:
444
+ oj = json.loads(Path(a.kev_mlx).read_text())
445
+ old = {(x["suite"], x["id"], x["question"]): x for x in oj["rows"]}
446
+ out = {"set": a.set, "verdin_info": ver["info"], "kev_mlx_info": oj["info"] if old else None, "suites": {}}
447
+ tot = {"verdin_vs_gpu": [], "kevmlx_vs_gpu": [], "verdin_vs_kevmlx": []}
448
+ print(f"{'suite':18s} {'recs':>5s} {'qs':>5s} | Verdin-MLX vs kev GPU fp32 rows: {'agree':>7s} {'acc kev':>7s} {'acc V':>7s} {'d pp':>6s} {'max|dp|':>8s} {'med|dp|':>8s}"
449
+ + (" | old MLX path vs GPU: agree, max|dp|, med|dp| | Verdin vs old: agree, max|dp|" if old else ""))
450
+ for s in suites:
451
+ keys = [k for k in vrows if k[0] == s and k in gpu]
452
+ rec = len({k[1] for k in keys})
453
+ r = {"records": rec}
454
+ r["verdin_vs_gpu"] = _stats([(gpu[k]["p"], vrows[k]["p"], gpu[k]["label"]) for k in keys])
455
+ tot["verdin_vs_gpu"] += [(gpu[k]["p"], vrows[k]["p"], gpu[k]["label"]) for k in keys]
456
+ if old:
457
+ ko = [k for k in keys if k in old]
458
+ r["kevmlx_vs_gpu"] = _stats([(gpu[k]["p"], old[k]["p"], gpu[k]["label"]) for k in ko])
459
+ r["verdin_vs_kevmlx"] = _stats([(old[k]["p"], vrows[k]["p"], gpu[k]["label"]) for k in ko])
460
+ tot["kevmlx_vs_gpu"] += [(gpu[k]["p"], old[k]["p"], gpu[k]["label"]) for k in ko]
461
+ tot["verdin_vs_kevmlx"] += [(old[k]["p"], vrows[k]["p"], gpu[k]["label"]) for k in ko]
462
+ v = r["verdin_vs_gpu"]
463
+ r["pass"] = v["argmax_agree"] >= a.min_agree and abs(v["acc_delta_pp"]) <= a.max_acc_delta_pp
464
+ out["suites"][s] = r
465
+ line = (f"{s:18s} {rec:5d} {v['questions']:5d} | {'':33s} {v['argmax_agree']:7.4f} {v['acc_ref']:7.4f} {v['acc_new']:7.4f} "
466
+ f"{v['acc_delta_pp']:+6.2f} {v['max_abs_dp']:8.4f} {v['median_abs_dp']:8.1e}")
467
+ if old:
468
+ o, vo = r["kevmlx_vs_gpu"], r["verdin_vs_kevmlx"]
469
+ line += f" | {o['argmax_agree']:.4f} {o['max_abs_dp']:.4f} {o['median_abs_dp']:.1e} | {vo['argmax_agree']:.4f} {vo['max_abs_dp']:.4f}"
470
+ print(line + (" PASS" if r["pass"] else " FAIL"))
471
+ out["overall"] = {k: _stats(v) for k, v in tot.items() if v}
472
+ out["all_pass"] = all(x["pass"] for x in out["suites"].values()) and out["overall"]["verdin_vs_gpu"]["argmax_agree"] >= a.min_agree
473
+ o = out["overall"]["verdin_vs_gpu"]
474
+ print(f"overall: {o['questions']} questions, agree {o['argmax_agree']:.4f} ({o['disagreements']} flips), acc {o['acc_ref']:.4f} -> {o['acc_new']:.4f} "
475
+ f"({o['acc_delta_pp']:+.2f} pp), max|dp| {o['max_abs_dp']:.4f}, median {o['median_abs_dp']:.1e}; all_pass={out['all_pass']}")
476
+ if old:
477
+ o = out["overall"]["kevmlx_vs_gpu"]
478
+ print(f"old MLX path vs GPU: agree {o['argmax_agree']:.4f} ({o['disagreements']} flips), acc {o['acc_ref']:.4f} -> {o['acc_new']:.4f}, "
479
+ f"max|dp| {o['max_abs_dp']:.4f}, median {o['median_abs_dp']:.1e}")
480
+ Path(a.out).write_text(json.dumps(out, indent=1) + "\n")
481
+
482
+
483
+ def _rows_any(path, rows_root=None, keys=None):
484
+ """{(suite, id, question): p} from a rows file of this script, numeric_parity's kev json ({"suite|id": {"logits",
485
+ "qids"}}), or "gpu" (the stored kev GPU rows under rows_root, for `keys`' suites)."""
486
+ if path == "gpu":
487
+ out = {}
488
+ for s in {k[0] for k in keys}:
489
+ f = Path(rows_root) / s / "rows.json"
490
+ if f.exists():
491
+ for x in json.loads(f.read_text()):
492
+ out[(s, x["id"], x["question"])] = x["p"]
493
+ return out
494
+ j = json.loads(Path(path).read_text())
495
+ if isinstance(j, dict) and "rows" in j:
496
+ return {(x["suite"], x["id"], x["question"]): x["p"] for x in j["rows"]}
497
+ out = {}
498
+ for key, v in j.items(): # numeric_parity kev-<dtype>-<device>.json
499
+ if "logits" not in v:
500
+ continue
501
+ s, rid_ = key.split("|", 1)
502
+ for q, z in zip(v["qids"], v["logits"]):
503
+ out[(s, rid_, q)] = softmax(z)
504
+ return out
505
+
506
+
507
+ def vs(a):
508
+ """Several row sets against one reference: argmax flips and |dp| at T = 1."""
509
+ ref = _rows_any(a.ref)
510
+ print(f"reference {a.ref}: {len(ref)} questions")
511
+ res = {}
512
+ for f in a.others:
513
+ other = _rows_any(f, a.rows_root, ref.keys())
514
+ ks = [k for k in ref if k in other]
515
+ st = _stats([(ref[k], other[k], None) for k in ks])
516
+ if st is None:
517
+ print(f" {f}: no common questions"); continue
518
+ res[f] = st
519
+ print(f" {f:58s} n={st['questions']:5d} flips={st['disagreements']:3d} agree={st['argmax_agree']:.4f} "
520
+ f"max|dp|={st['max_abs_dp']:.4f} p99={st['p99_abs_dp']:.4f} median={st['median_abs_dp']:.1e} mean={st['mean_abs_dp']:.1e}")
521
+ if a.out:
522
+ Path(a.out).write_text(json.dumps({"reference": a.ref, "results": res}, indent=1) + "\n")
523
+
524
+
525
+ def main():
526
+ ap = argparse.ArgumentParser()
527
+ sub = ap.add_subparsers(dest="cmd", required=True)
528
+ sub.add_parser("tiny")
529
+ sub.add_parser("bidir")
530
+ s = sub.add_parser("select"); s.add_argument("--rows-root", required=True); s.add_argument("--out", required=True)
531
+ s.add_argument("--suites", default=""); s.add_argument("--per-suite", type=int, default=0); s.add_argument("--seed", type=int, default=0)
532
+ v = sub.add_parser("verdin"); v.add_argument("--model", required=True); v.add_argument("--set", required=True); v.add_argument("--out", required=True)
533
+ v.add_argument("--batch", type=int, default=16); v.add_argument("--batch-tokens", type=int, default=16384)
534
+ v.add_argument("--memory-limit-gb", type=float, default=64); v.add_argument("--attn-dtype", default="auto")
535
+ v.add_argument("--dtype", default="auto", help="fp32: the bf16-stored weights upcast, every GEMM in fp32 (MLX_ENABLE_TF32=0)")
536
+ v.add_argument("--prefill-chunk", type=int, default=0); v.add_argument("--max-sweep-tokens", type=int, default=0)
537
+ k = sub.add_parser("kev"); k.add_argument("--run", required=True); k.add_argument("--set", required=True); k.add_argument("--out", required=True)
538
+ k.add_argument("--memory-limit-gb", type=float, default=64)
539
+ k.add_argument("--max-state", type=int, default=65536); k.add_argument("--max-branch", type=int, default=66560)
540
+ k.add_argument("--max-packed", type=int, default=131072)
541
+ c = sub.add_parser("compare"); c.add_argument("--set", required=True); c.add_argument("--rows-root", required=True)
542
+ c.add_argument("--verdin", required=True); c.add_argument("--kev-mlx"); c.add_argument("--out", required=True)
543
+ c.add_argument("--min-agree", type=float, default=0.995); c.add_argument("--max-acc-delta-pp", type=float, default=0.2)
544
+ w = sub.add_parser("vs"); w.add_argument("--ref", required=True); w.add_argument("others", nargs="+")
545
+ w.add_argument("--rows-root", default="results/verdin/mlx/kev-gpu-rows"); w.add_argument("--out")
546
+ a = ap.parse_args()
547
+ {"tiny": tiny, "bidir": bidir, "select": select, "verdin": run_verdin, "kev": run_kev_mlx, "compare": compare, "vs": vs}[a.cmd](a)
548
+
549
+
550
+ if __name__ == "__main__":
551
+ main()
verdin/tests/numeric_parity.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numeric parity, Verdin vs kev's DecisionModel on the same checkpoint and records (CPU fp32 on a host; or GPU).
2
+
3
+ # 1. kev reference (fp32 backbone, LoRA unmerged, torch reference kernels): selects the records and writes logits
4
+ KEV_SCHEMA_FIRST=1 KEV_MAX_STATE=65536 KEV_MAX_BRANCH=66560 KEV_MAX_PACKED=131072 KEV_ROW_BUDGET=16384 \\
5
+ python -m verdin.tests.numeric_parity kev --run runs/exp-combo-s-di-4b-s1 --date-facts 1 --out DIR
6
+ # 2. Verdin on the same records (a converted checkpoint; --dtype fp32 for the exact comparison)
7
+ python -m verdin.tests.numeric_parity verdin --model runs/verdin-4b-s1-fp32 --dtype fp32 --out DIR
8
+ # 3. compare (and against the stored GPU eval rows of the same run: --rows results/eval/<label>)
9
+ python -m verdin.tests.numeric_parity compare --dir DIR --temperature 2.7638 --rows results/eval/minijev-combo-s-di-4b-s1
10
+
11
+ kev's own loader serves a checkpoint trained with a bf16 backbone (weights_dtype "bf16", as every DI run) in bf16 with
12
+ the LoRA unmerged, whatever --dtype says; the fp32 reference here overrides that (meta.weights_dtype = "fp32",
13
+ merge off), i.e. base weights upcast exactly and the adapter applied unmerged in fp32: the mathematically exact model.
14
+ The stored GPU rows were produced by kev's default path (bf16 backbone), so they differ from both at bf16 level.
15
+ """
16
+ import argparse
17
+ import json
18
+ import math
19
+ import os
20
+ import random
21
+ import sys
22
+ import time
23
+ from pathlib import Path
24
+
25
+ ROOT = Path(__file__).resolve().parents[2]
26
+
27
+ # (name, path, how many, prefer multi-question, long-state quota: (chars threshold, count))
28
+ PICK = [
29
+ ("robust-v1", "data/frozen/robust-v1.jsonl", 8, False, None),
30
+ ("jevbench-public", "data/frozen/jevbench-public-v1.jsonl", 6, False, (12000, 2)),
31
+ ("typed-decisions", "data/external/typed-decisions.jsonl", 8, True, None),
32
+ ("hard-v1", "third_party/kev/evals/hard-v1/development.jsonl", 8, True, (12000, 2)),
33
+ ("score-v1.heldout", "data/scoregen/score-v1.heldout.jsonl", 6, True, None),
34
+ ("diskills-v1.heldout", "data/diskills/diskills-v1.heldout.jsonl", 10, True, (12000, 4)),
35
+ ("documents-v1", "third_party/kev/evals/documents-v1/development.jsonl", 6, True, (12000, 2)),
36
+ ("transfer-v4", "third_party/kev/evals/v4/transfer-v4/development.jsonl", 6, False, None),
37
+ ("transfer-v9", "third_party/kev/evals/v9/transfer-v9/development.jsonl", 6, False, None),
38
+ ]
39
+
40
+
41
+ def chars(r):
42
+ return len(r["state"] if isinstance(r["state"], str) else json.dumps(r["state"]))
43
+
44
+
45
+ def select(seed=0):
46
+ out = []
47
+ for name, path, n, multi, longq in PICK:
48
+ rs = [json.loads(l) for l in open(ROOT / path, encoding="utf-8") if l.strip()]
49
+ rng = random.Random(f"{seed}/{name}")
50
+ picked = []
51
+ if longq:
52
+ thr, k = longq
53
+ longs = [r for r in rs if chars(r) >= thr]
54
+ picked += rng.sample(longs, min(k, len(longs)))
55
+ pool = [r for r in rs if r not in picked and chars(r) < 12000]
56
+ if multi:
57
+ mq = [r for r in pool if len(r["questions"]) > 1]
58
+ picked += rng.sample(mq, min(n - len(picked) - n // 4, len(mq)))
59
+ pool = [r for r in pool if r not in picked]
60
+ picked += rng.sample(pool, n - len(picked))
61
+ for r in picked:
62
+ for q in r["questions"].values():
63
+ q.setdefault("src", f"{name}_{q['type']}") # kev.data.load_records' default (materialize needs it)
64
+ out.append({**r, "_suite": name})
65
+ return out
66
+
67
+
68
+ def api_request(r):
69
+ return {"state": r["state"], "questions": {k: {f: v for f, v in q.items() if f in ("type", "instructions", "criteria")}
70
+ for k, q in r["questions"].items()}}
71
+
72
+
73
+ def rid(r):
74
+ return r.get("_meta", {}).get("id")
75
+
76
+
77
+ def cmd_kev(a):
78
+ if a.device == "cpu":
79
+ sys.modules["fla"] = None # CPU: transformers' torch reference kernels (fla is GPU-only)
80
+ sys.modules["causal_conv1d"] = None
81
+ sys.path.insert(0, str(ROOT / "third_party" / "kev"))
82
+ import torch
83
+ torch.set_num_threads(a.threads)
84
+ if a.device.startswith("cuda"): # exactly kev.predictors.LocalPredictor's evaluation settings
85
+ torch.backends.cuda.matmul.allow_tf32 = False; torch.backends.cudnn.allow_tf32 = False
86
+ torch.backends.cuda.enable_flash_sdp(False); torch.backends.cuda.enable_mem_efficient_sdp(False)
87
+ from kev.api import with_date_facts
88
+ from kev.checkpoint import Checkpoint, LoadOptions
89
+ from kev.data import materialize
90
+ from kev.model import MAX_PACKED
91
+ out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
92
+ src = a.records or (out / "records.jsonl" if (out / "records.jsonl").exists() else None)
93
+ recs = [json.loads(l) for l in open(src, encoding="utf-8")] if src else select(a.seed)
94
+ if a.limit: recs = recs[: a.limit]
95
+ if not (out / "records.jsonl").exists():
96
+ with open(out / "records.jsonl", "w", encoding="utf-8") as f:
97
+ for r in recs: f.write(json.dumps(r, ensure_ascii=False) + "\n")
98
+ ck = Checkpoint(a.run)
99
+ if a.kev_dtype == "fp32":
100
+ ck.meta.weights_dtype = "fp32" # exact fp32 reference (see module doc)
101
+ opts = LoadOptions(dtype=None, merge=False, temperature=1.0)
102
+ else: # kev's own default for this checkpoint: bf16 backbone, LoRA unmerged
103
+ opts = LoadOptions(dtype=torch.bfloat16, temperature=1.0)
104
+ t = time.time()
105
+ tok, model = ck.load(a.device, opts)
106
+ model.return_unknown = model.head.unknown
107
+ print(f"kev loaded ({a.kev_dtype}, {a.device}) in {time.time() - t:.0f} s; dtype {next(model.lm.parameters()).dtype}", flush=True)
108
+ dest = out / f"kev-{a.kev_dtype}-{a.device}.json"
109
+ res = json.loads(dest.read_text()) if dest.exists() else {} # resume
110
+ for i, r in enumerate(recs):
111
+ key = f"{r['_suite']}|{rid(r)}"
112
+ if key in res:
113
+ continue
114
+ rr = {**r, "state": with_date_facts(r["state"])} if a.date_facts else r
115
+ for q in rr["questions"].values():
116
+ q.setdefault("src", f"{r['_suite']}_{q['type']}")
117
+ try:
118
+ enc = model.encode(tok, materialize(rr), strict=True)
119
+ if len(enc["ids"]) > MAX_PACKED:
120
+ raise ValueError("packed request exceeds limit")
121
+ except Exception as e: # noqa: BLE001
122
+ res[key] = {"refused": f"{type(e).__name__}: {e}"[:200]}; continue
123
+ t = time.time()
124
+ with torch.no_grad():
125
+ z = model.forward(enc)
126
+ res[key] = {"logits": [x.float().tolist() for x in z], "qids": list(r["questions"]), "tokens": len(enc["ids"]),
127
+ "state_tokens": enc["seg"].count(0), "seconds": round(time.time() - t, 2)}
128
+ print(f"[{i + 1}/{len(recs)}] {key} tokens={len(enc['ids'])} state={enc['seg'].count(0)} q={len(z)} {time.time() - t:.1f}s", flush=True)
129
+ dest.write_text(json.dumps(res)) # after every record: a crash loses nothing
130
+ dest.write_text(json.dumps(res))
131
+
132
+
133
+ def cmd_verdin(a):
134
+ sys.path.insert(0, str(ROOT))
135
+ import torch
136
+ torch.set_num_threads(a.threads)
137
+ from verdin import Verdin
138
+ out = Path(a.out)
139
+ recs = [json.loads(l) for l in open(out / "records.jsonl", encoding="utf-8")]
140
+ t = time.time()
141
+ v = Verdin.from_pretrained(a.model, device=a.device, dtype=a.dtype, prefix_cache=0, threads=a.threads,
142
+ gdr=a.gdr, conv=a.conv, branch_gdr=a.branch_gdr, sdpa=a.sdpa)
143
+ print(f"verdin loaded in {time.time() - t:.0f} s: {json.dumps(v.engine.describe())}", flush=True)
144
+ if v.cfg.render["date_facts"] != bool(a.date_facts):
145
+ sys.exit("checkpoint date_facts setting differs from --date-facts")
146
+ res, encs, keys = {}, [], []
147
+ for r in recs:
148
+ key = f"{r['_suite']}|{rid(r)}"
149
+ try:
150
+ encs.append(v.encode(api_request(r))); keys.append(key)
151
+ except ValueError as e:
152
+ res[key] = {"refused": str(e)[:200]}
153
+ for i, (key, enc) in enumerate(zip(keys, encs)): # one request per pass (single-request path)
154
+ t = time.time()
155
+ rr = v.run([enc])[0]
156
+ v.engine.sync()
157
+ res[key] = {"logits": rr.logits, "unknown": rr.unknown, "tokens": enc.n_tokens, "state_tokens": enc.n_state,
158
+ "seconds": round(time.time() - t, 2)}
159
+ print(f"[{i + 1}/{len(encs)}] {key} tokens={enc.n_tokens} {time.time() - t:.1f}s", flush=True)
160
+ if a.batch > 1: # the same records in batches: batching must not change results
161
+ for s in range(0, len(encs), a.batch):
162
+ for key, rr in zip(keys[s:s + a.batch], v.run(encs[s:s + a.batch])):
163
+ res[key]["logits_batched"] = rr.logits
164
+ tag = a.tag or f"verdin-{a.dtype}-{a.device.split(':')[0]}"
165
+ (out / f"{tag}.json").write_text(json.dumps(res))
166
+
167
+
168
+ def softmax(z, T=1.0):
169
+ m = max(z); e = [math.exp((x - m) / T) for x in z]; s = sum(e)
170
+ return [x / s for x in e]
171
+
172
+
173
+ def cmp_sets(A, B, T, field_b="logits"):
174
+ """A, B: {key: {"logits": [[...] per question]}} -> stats over questions both have."""
175
+ dl, dp, dpT, n, agree, both = [], [], [], 0, 0, 0
176
+ for key, ra in A.items():
177
+ rb = B.get(key)
178
+ if not rb or "logits" not in ra or field_b not in rb:
179
+ continue
180
+ both += 1
181
+ for za, zb in zip(ra["logits"], rb[field_b]):
182
+ n += 1
183
+ dl.append(max(abs(x - y) for x, y in zip(za, zb)))
184
+ pa, pb = softmax(za), softmax(zb)
185
+ dp.append(max(abs(x - y) for x, y in zip(pa, pb)))
186
+ pa, pb = softmax(za, T), softmax(zb, T)
187
+ dpT.append(max(abs(x - y) for x, y in zip(pa, pb)))
188
+ agree += max(range(len(za)), key=lambda i: za[i]) == max(range(len(zb)), key=lambda i: zb[i])
189
+ q = lambda xs, f: sorted(xs)[min(len(xs) - 1, int(f * len(xs)))] if xs else None
190
+ return {"records": both, "questions": n, "argmax_agree": agree, "max_abs_dlogit": max(dl) if dl else None,
191
+ "max_abs_dp_T1": max(dp) if dp else None, "median_abs_dp_T1": q(dp, 0.5), "p99_abs_dp_T1": q(dp, 0.99),
192
+ f"max_abs_dp_T{T:.4g}": max(dpT) if dpT else None}
193
+
194
+
195
+ def cmd_compare(a):
196
+ d = Path(a.dir)
197
+ sets = {p.stem: json.loads(p.read_text()) for p in sorted(d.glob("*.json")) if p.stem != "compare"}
198
+ recs = [json.loads(l) for l in open(d / "records.jsonl", encoding="utf-8")]
199
+ report = {"pairs": {}, "refused": {k: [key for key, r in v.items() if "refused" in r] for k, v in sets.items()}}
200
+ names = sorted(sets)
201
+ for i, x in enumerate(names):
202
+ for y in names[i + 1:]:
203
+ report["pairs"][f"{x} vs {y}"] = cmp_sets(sets[x], sets[y], a.temperature)
204
+ if any("logits_batched" in r for r in sets[x].values()):
205
+ report["pairs"][f"{x} single vs batched"] = cmp_sets(sets[x], sets[x], a.temperature, "logits_batched")
206
+ if a.rows: # stored eval rows (kev on GPU, raw logits): keyed by record id + question
207
+ stored = {}
208
+ for r in recs:
209
+ f = Path(a.rows) / r["_suite"] / "rows.json"
210
+ if not f.exists(): continue
211
+ if r["_suite"] not in stored:
212
+ stored[r["_suite"]] = {(x["id"], x["question"]): x for x in json.loads(f.read_text())}
213
+ gpu = {}
214
+ for r in recs:
215
+ rows = stored.get(r["_suite"], {})
216
+ zs = [rows.get((rid(r), q), {}).get("logits") for q in r["questions"]]
217
+ if all(z is not None for z in zs):
218
+ gpu[f"{r['_suite']}|{rid(r)}"] = {"logits": zs}
219
+ report["stored_gpu_rows"] = {"records_with_rows": len(gpu), "source": a.rows}
220
+ for x in names:
221
+ report["pairs"][f"stored-gpu-rows vs {x}"] = cmp_sets(gpu, sets[x], a.temperature)
222
+ (d / "compare.json").write_text(json.dumps(report, indent=1) + "\n")
223
+ print(json.dumps(report, indent=1))
224
+
225
+
226
+ def main():
227
+ ap = argparse.ArgumentParser()
228
+ sub = ap.add_subparsers(dest="cmd", required=True)
229
+ k = sub.add_parser("kev"); k.add_argument("--run", required=True); k.add_argument("--out", required=True)
230
+ k.add_argument("--date-facts", type=int, default=1); k.add_argument("--seed", type=int, default=0)
231
+ k.add_argument("--records"); k.add_argument("--limit", type=int, default=0)
232
+ k.add_argument("--device", default="cpu"); k.add_argument("--kev-dtype", default="fp32", choices=["fp32", "bf16"])
233
+ k.add_argument("--threads", type=int, default=int(os.environ.get("OMP_NUM_THREADS", "16")))
234
+ v = sub.add_parser("verdin"); v.add_argument("--model", required=True); v.add_argument("--out", required=True)
235
+ v.add_argument("--date-facts", type=int, default=1); v.add_argument("--device", default="cpu")
236
+ v.add_argument("--dtype", default="fp32"); v.add_argument("--batch", type=int, default=8); v.add_argument("--tag")
237
+ v.add_argument("--gdr", default="auto"); v.add_argument("--conv", default="auto"); v.add_argument("--branch-gdr", default="chunk")
238
+ v.add_argument("--sdpa", default="auto")
239
+ v.add_argument("--threads", type=int, default=int(os.environ.get("OMP_NUM_THREADS", "16")))
240
+ c = sub.add_parser("compare"); c.add_argument("--dir", required=True); c.add_argument("--temperature", type=float, default=1.0)
241
+ c.add_argument("--rows")
242
+ a = ap.parse_args()
243
+ {"kev": cmd_kev, "verdin": cmd_verdin, "compare": cmd_compare}[a.cmd](a)
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()
verdin/tests/parity_gpu.sh ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Verdin phase-A GPU acceptance + benchmark. Queue on a free RTX 5090 host: ~1.5 h for s1 on .124 (its CPU reference was
3
+ # made in phase A; steps 1-5 ~40 min, then the fp32 suite pass), ~2.5 h for s0 on .204 (CPU reference rebuilt first,
4
+ # GPU idle meanwhile). Run ON the host from the repo:
5
+ # bash verdin/tests/parity_gpu.sh s1 # .124 (runs/exp-combo-s-di-4b-s1); "s0" on .204
6
+ # It refuses to start if any process is on this host's 5090, starts only its own servers and stops only those.
7
+ # Steps (results under results/verdin/gpu-<tag>/; a finished step is skipped on re-run):
8
+ # 0. checkpoints: bf16 Verdin (runs/verdin-4b-<tag>) + fp32 one (scratch) converted on the CPU if missing
9
+ # 1. tiny-model kernel tests on the GPU (fla chunk / fused-recurrent, causal-conv1d, SDPA) vs transformers' CPU reference
10
+ # 2. numeric parity on 64 records (incl. multi-question and 3-9k-token states): Verdin fp32 and bf16 on the GPU (+ kernel
11
+ # variants) vs kev's fp32 CPU reference (made in phase A) and vs kev's own GPU serving path (bf16 + unmerged LoRA)
12
+ # 3. suite acceptance: Verdin bf16 vs kev's stored eval rows on 18 suites: same argmax >= 99.5 %, |acc delta| <= 0.2 pp
13
+ # 4. server wire-format test on the real checkpoint (JevBench typesafe adapter; DI kit if present)
14
+ # 5. benchmark: kev's predictor_server in the Decision Index serving config vs the Verdin server, same 400 requests,
15
+ # concurrency 1 / 8 / 32, latency p50/p95, throughput, peak GPU memory
16
+ # 5b. the stored-rows comparison again with the fp32 checkpoint (the agreement ceiling against kev's bf16 rows)
17
+ # 6. verdict.json
18
+ set -u
19
+ cd "$(dirname "$0")/../.."
20
+ source env.sh
21
+ TAG=${1:-s1}
22
+ # 10-09: VERDIN_GPU=<nvml index> runs on another card of the host (e.g. .124's shared RTX 4090, index 2). Results, the
23
+ # GPU-made references and the bench ports are then separate (results/verdin/gpu-<tag>-gpu<idx>/, numeric-<tag>-gpu<idx>,
24
+ # ports +10), so the 5090 run neither skips steps nor collides; with VERDIN_ALLOW_SHARED=1 the card may already host other
25
+ # processes as long as >= 30 GB are free.
26
+ SFX=""; PB=8940
27
+ if [ -n "${VERDIN_GPU:-}" ]; then export MINIJEV_NVML_INDEX=$VERDIN_GPU CUDA_VISIBLE_DEVICES=$VERDIN_GPU; SFX=-gpu$VERDIN_GPU; PB=8950; fi
28
+ RUN=runs/exp-combo-s-di-4b-$TAG; LBL=minijev-combo-s-di-4b-$TAG
29
+ SCR=/data/disk1/workspace/verdin-scratch; mkdir -p $SCR
30
+ V=runs/verdin-4b-$TAG; VF=$SCR/verdin-4b-$TAG-fp32; N=$SCR/numeric-$TAG$SFX
31
+ OUT=results/verdin/gpu-$TAG$SFX; mkdir -p $OUT/bench
32
+ if [ -n "$SFX" ] && [ ! -f $N/kev-fp32-cpu.json ] && [ -f $SCR/numeric-$TAG/kev-fp32-cpu.json ]; then # reuse the CPU-made references
33
+ mkdir -p $N; cp $SCR/numeric-$TAG/records.jsonl $SCR/numeric-$TAG/*-cpu.json $N/; fi
34
+ ROWS=results/eval/$LBL; [ -f $ROWS/robust-v1/rows.json ] || ROWS=$SCR/rows/$LBL
35
+ PY=./.venv/bin/python
36
+ CC1D=/data/disk1/workspace/cc1d/site
37
+ KEVENV="KEV_SCHEMA_FIRST=1 KEV_MAX_STATE=65536 KEV_MAX_BRANCH=66560 KEV_MAX_PACKED=131072 KEV_ROW_BUDGET=16384"
38
+ VPP="$PYTHONPATH:$CC1D" # Verdin runs with the causal-conv1d kernel importable; kev as in the DI runs (without)
39
+ log () { echo "$(date '+%F %T') $*" | tee -a $OUT/job.log; }
40
+
41
+ busy=$(nvidia-smi -i "$MINIJEV_NVML_INDEX" --query-compute-apps=pid --format=csv,noheader | grep -c .)
42
+ if [ "${VERDIN_ALLOW_SHARED:-0}" = 1 ]; then
43
+ free=$(nvidia-smi -i "$MINIJEV_NVML_INDEX" --query-gpu=memory.free --format=csv,noheader,nounits)
44
+ [ "$free" -ge 30000 ] || { log "GPU $MINIJEV_NVML_INDEX has only $free MiB free: not starting"; exit 1; }
45
+ log "GPU $MINIJEV_NVML_INDEX shared with $busy other processes, $free MiB free"
46
+ elif [ "$busy" != 0 ]; then log "GPU $MINIJEV_NVML_INDEX is busy ($busy processes): not starting"; exit 1; fi
47
+ [ -f $RUN/head.pt ] || { log "missing $RUN"; exit 1; }
48
+ [ -f $ROWS/robust-v1/rows.json ] || { log "missing stored rows ($ROWS)"; exit 1; }
49
+ log "start: $RUN -> $V; rows $ROWS"
50
+
51
+ # 0. checkpoints (CPU)
52
+ CONV="--run $RUN --schema-first 1 --date-facts 1 --max-state 65536 --max-branch 66560 --max-packed 131072 --name Verdin-4B --threads 16"
53
+ [ -f $V/verdin_config.json ] || CUDA_VISIBLE_DEVICES= $PY -m verdin.convert $CONV --out $V --dtype bf16 --verify 3 >> $OUT/convert.log 2>&1 || { log "convert bf16 failed"; exit 1; }
54
+ [ -f $VF/verdin_config.json ] || CUDA_VISIBLE_DEVICES= $PY -m verdin.convert $CONV --out $VF --dtype fp32 --verify 0 >> $OUT/convert.log 2>&1 || { log "convert fp32 failed"; exit 1; }
55
+ T=$($PY -c "import json; print(json.load(open('$V/verdin_config.json'))['head']['temperature'])")
56
+ log "checkpoints ready (T=$T)"
57
+
58
+ # 1. tiny-model kernel tests
59
+ if [ ! -f $OUT/tiny.done ]; then
60
+ ok=1
61
+ for args in "--dtype fp32" "--dtype bf16" "--dtype bf16 --branch-gdr recurrent"; do
62
+ env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.tests.test_tiny --device cuda $args >> $OUT/tiny.log 2>&1 || ok=0
63
+ done
64
+ [ $ok = 1 ] && touch $OUT/tiny.done; log "tiny kernel tests: $([ $ok = 1 ] && echo OK || echo FAILED, see $OUT/tiny.log)"
65
+ fi
66
+
67
+ # 2. numeric parity (64 records)
68
+ if [ ! -f $N/kev-fp32-cpu.json ]; then
69
+ log "kev fp32 CPU reference missing: building it (CPU, ~40 min)"
70
+ env $KEVENV CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=16 nice -n 10 $PY -m verdin.tests.numeric_parity kev --run $RUN --out $N --threads 16 >> $OUT/numeric.log 2>&1
71
+ fi
72
+ [ -f $N/kev-bf16-cuda.json ] || env $KEVENV $PY -m verdin.tests.numeric_parity kev --run $RUN --out $N --device cuda --kev-dtype bf16 >> $OUT/numeric.log 2>&1
73
+ nv () { local tag=$1; shift; [ -f $N/$tag.json ] || env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.tests.numeric_parity verdin --out $N --device cuda --tag $tag "$@" >> $OUT/numeric.log 2>&1 || log "numeric $tag failed"; }
74
+ nv verdin-fp32-cuda --model $VF --dtype fp32
75
+ nv verdin-fp32-cuda-sdpamath --model $VF --dtype fp32 --sdpa math --batch 1
76
+ nv verdin-bf16-cuda --model $V --dtype bf16
77
+ nv verdin-bf16-cuda-torchgdr --model $V --dtype bf16 --gdr torch --batch 1
78
+ nv verdin-bf16-cuda-torchconv --model $V --dtype bf16 --conv torch --batch 1
79
+ nv verdin-bf16-cuda-recurrent --model $V --dtype bf16 --branch-gdr recurrent --batch 1
80
+ $PY -m verdin.tests.numeric_parity compare --dir $N --temperature $T --rows $ROWS > $OUT/numeric-compare.log 2>&1
81
+ cp $N/compare.json $OUT/numeric-compare.json 2>/dev/null
82
+ log "numeric parity: $OUT/numeric-compare.json"
83
+
84
+ # 3. suite acceptance vs kev's stored rows
85
+ [ -f $OUT/eval/summary.json ] || env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.tests.eval_rows --model $V --rows-root $ROWS --out $OUT/eval --batch 16 >> $OUT/eval.log 2>&1
86
+ log "suite acceptance: $(grep -c PASS $OUT/eval.log) PASS / $(grep -c FAIL $OUT/eval.log) FAIL ($OUT/eval/summary.json)"
87
+
88
+ # 4. server wire-format test on the real checkpoint
89
+ [ -f $OUT/server.done ] || { env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.tests.test_server --model $V >> $OUT/server.log 2>&1 && touch $OUT/server.done; }
90
+ log "server test: $([ -f $OUT/server.done ] && echo OK || echo FAILED, see $OUT/server.log)"
91
+
92
+ # 5. benchmark: kev predictor_server (DI config) vs Verdin
93
+ wait_up () { for i in $(seq 1 180); do curl -s -m 5 http://127.0.0.1:$1/v1/models > /dev/null && return 0; sleep 5; done; return 1; }
94
+ [ -f $OUT/bench/requests.jsonl ] || $PY -m verdin.tests.bench build --out $OUT/bench/requests.jsonl --n 400 >> $OUT/bench.log 2>&1
95
+ if [ ! -f $OUT/bench/kev.json ]; then
96
+ env $KEVENV PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m minijev.predictor_server --host 127.0.0.1 --port $((PB+1)) -- \
97
+ --kev $RUN --dtype bf16 --date-facts > $OUT/bench/kev-server.log 2>&1 &
98
+ KP=$!
99
+ if wait_up $((PB+1)); then $PY -m verdin.tests.bench run --url http://127.0.0.1:$((PB+1)) --requests $OUT/bench/requests.jsonl --pid $KP --label kev --out $OUT/bench/kev.json >> $OUT/bench.log 2>&1
100
+ else log "kev server did not come up"; fi
101
+ kill $KP 2>/dev/null; wait $KP 2>/dev/null
102
+ fi
103
+ if [ ! -f $OUT/bench/verdin.json ]; then
104
+ env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.server --model $V --host 127.0.0.1 --port $((PB+2)) > $OUT/bench/verdin-server.log 2>&1 &
105
+ VP=$!
106
+ if wait_up $((PB+2)); then $PY -m verdin.tests.bench run --url http://127.0.0.1:$((PB+2)) --requests $OUT/bench/requests.jsonl --pid $VP --label verdin --out $OUT/bench/verdin.json >> $OUT/bench.log 2>&1
107
+ else log "verdin server did not come up"; fi
108
+ kill $VP 2>/dev/null; wait $VP 2>/dev/null
109
+ fi
110
+ if [ ! -f $OUT/bench/verdin-nobatch.json ]; then # one request per forward: the single-request path, no cross-request batching
111
+ env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.server --model $V --host 127.0.0.1 --port $((PB+3)) --max-batch 1 > $OUT/bench/verdin-nobatch-server.log 2>&1 &
112
+ VP=$!
113
+ if wait_up $((PB+3)); then $PY -m verdin.tests.bench run --url http://127.0.0.1:$((PB+3)) --requests $OUT/bench/requests.jsonl --pid $VP --label verdin-mb1 --concurrency 1,8 --out $OUT/bench/verdin-nobatch.json >> $OUT/bench.log 2>&1
114
+ fi
115
+ kill $VP 2>/dev/null; wait $VP 2>/dev/null
116
+ fi
117
+ if [ ! -f $OUT/bench/verdin-recurrent.json ]; then # fla fused_recurrent for the (short) branch rows instead of chunk
118
+ env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.server --model $V --host 127.0.0.1 --port $((PB+4)) --branch-gdr recurrent > $OUT/bench/verdin-recurrent-server.log 2>&1 &
119
+ VP=$!
120
+ if wait_up $((PB+4)); then $PY -m verdin.tests.bench run --url http://127.0.0.1:$((PB+4)) --requests $OUT/bench/requests.jsonl --pid $VP --label verdin-rec --concurrency 1,8 --out $OUT/bench/verdin-recurrent.json >> $OUT/bench.log 2>&1
121
+ fi
122
+ kill $VP 2>/dev/null; wait $VP 2>/dev/null
123
+ fi
124
+ $PY -m verdin.tests.bench table $OUT/bench/kev.json $OUT/bench/verdin.json > $OUT/bench/table.txt 2>&1
125
+ $PY -m verdin.tests.bench table $OUT/bench/verdin-nobatch.json $OUT/bench/verdin-recurrent.json >> $OUT/bench/table.txt 2>&1
126
+ cat $OUT/bench/table.txt | tee -a $OUT/job.log
127
+
128
+ # 5b. (after the benchmark: the slowest step) the same with the fp32 checkpoint (exact merged model): how far kev's stored bf16 rows are from the exact model,
129
+ # i.e. the agreement ceiling any bf16 engine can reach against them
130
+ [ -f $OUT/eval-fp32/summary.json ] || env PYTHONPATH=$VPP PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True $PY -m verdin.tests.eval_rows --model $VF --dtype fp32 --rows-root $ROWS --out $OUT/eval-fp32 --batch 8 >> $OUT/eval-fp32.log 2>&1
131
+ log "fp32 reference vs stored rows: $OUT/eval-fp32/summary.json"
132
+
133
+ # 6. verdict
134
+ $PY - <<EOF | tee -a $OUT/job.log
135
+ import json, os
136
+ o = "$OUT"; v = {}
137
+ s = json.load(open(f"{o}/eval/summary.json")) if os.path.exists(f"{o}/eval/summary.json") else {}
138
+ v["suites_all_pass"] = s.get("all_pass")
139
+ v["suites_failing"] = [k for k, x in s.get("suites", {}).items() if not x["pass"]]
140
+ v["core5_acc_kev"], v["core5_acc_verdin"] = s.get("core5_acc_kev"), s.get("core5_acc_verdin")
141
+ v["argmax_agree_by_suite"] = {k: round(x["argmax_agree"], 4) for k, x in s.get("suites", {}).items()}
142
+ f = json.load(open(f"{o}/eval-fp32/summary.json")) if os.path.exists(f"{o}/eval-fp32/summary.json") else {}
143
+ v["fp32_exact_vs_stored_rows_agree_by_suite"] = {k: round(x["argmax_agree"], 4) for k, x in f.get("suites", {}).items()}
144
+ c = json.load(open(f"{o}/numeric-compare.json")) if os.path.exists(f"{o}/numeric-compare.json") else {}
145
+ pairs = c.get("pairs", {})
146
+ for k in ("kev-fp32-cpu vs verdin-fp32-cuda", "kev-fp32-cpu vs verdin-bf16-cuda", "kev-bf16-cuda vs kev-fp32-cpu"):
147
+ if k in pairs: v[k] = {x: pairs[k][x] for x in ("questions", "argmax_agree", "max_abs_dp_T1", "median_abs_dp_T1")}
148
+ b = {n: json.load(open(f"{o}/bench/{n}.json")) for n in ("kev", "verdin") if os.path.exists(f"{o}/bench/{n}.json")}
149
+ if len(b) == 2:
150
+ v["throughput_speedup"] = {c_: round(b["verdin"]["levels"][c_]["req_per_s"] / b["kev"]["levels"][c_]["req_per_s"], 2) for c_ in b["kev"]["levels"]}
151
+ v["p50_ms"] = {n: b[n]["levels"]["1"]["latency_ms"]["p50"] for n in b}
152
+ v["peak_gpu_mem_mib"] = {n: b[n].get("peak_gpu_mem_mib") for n in b}
153
+ v["faster_than_kev"] = all(x > 1 for x in v["throughput_speedup"].values()) and v["p50_ms"]["verdin"] < v["p50_ms"]["kev"]
154
+ v["tiny_kernel_tests"] = os.path.exists(f"{o}/tiny.done"); v["server_test"] = os.path.exists(f"{o}/server.done")
155
+ json.dump(v, open(f"{o}/verdict.json", "w"), indent=1)
156
+ print(json.dumps(v, indent=1))
157
+ EOF
158
+ log "done: $OUT/verdict.json"
verdin/tests/render_parity.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render parity: Verdin's request -> tokens path vs kev's, record by record (needs kev + transformers: run on a host).
2
+
3
+ kev side = exactly what minijev.predictor_server / kev.predictors.LocalPredictor do with a request: date facts on the raw
4
+ state (when on), kev.data.materialize (pydantic validation + kev.api.to_record), kev.model.encode(strict=True) under the
5
+ KEV_* environment, then the MAX_PACKED check; tokenizer = kev.model.load_tokenizer(base, revision).
6
+ Verdin side = verdin.render.Renderer.encode_request on the same wire request (kev.data.api_request), with the
7
+ converted checkpoint's tokenizer.json and the render settings given here.
8
+ Compared: the packed ids / segments / positions / <decide> and </opt> indices, or the refusal (both must refuse, with the
9
+ same message after Verdin's "too many tokens: " prefix).
10
+
11
+ KEV_SCHEMA_FIRST=1 KEV_MAX_STATE=65536 KEV_MAX_BRANCH=66560 KEV_MAX_PACKED=131072 \\
12
+ python -m verdin.tests.render_parity --tokenizer runs/verdin-4b-s1/tokenizer.json --date-facts 1 --per-suite 400 \\
13
+ --out results/verdin/render-parity-serving.json
14
+ The KEV_* variables configure kev; Verdin takes the same values from them, so the two sides always agree on settings.
15
+ """
16
+ import argparse
17
+ import json
18
+ import os
19
+ import random
20
+ import sys
21
+ import time
22
+ from collections import Counter
23
+ from pathlib import Path
24
+
25
+ ROOT = Path(__file__).resolve().parents[2]
26
+ sys.path.insert(0, str(ROOT / "third_party" / "kev"))
27
+ sys.path.insert(0, str(ROOT))
28
+
29
+ SUITES = [
30
+ ("robust-v1", "data/frozen/robust-v1.jsonl"),
31
+ ("jevbench-public", "data/frozen/jevbench-public-v1.jsonl"),
32
+ ("typed-decisions", "data/external/typed-decisions.jsonl"),
33
+ ("hard-v1", "third_party/kev/evals/hard-v1/development.jsonl"),
34
+ ("score-v1.heldout", "data/scoregen/score-v1.heldout.jsonl"),
35
+ ("diskills-v1.heldout", "data/diskills/diskills-v1.heldout.jsonl"),
36
+ ("minijev-frozen", "data/frozen/minijev-frozen-v1.jsonl"),
37
+ ("transfer-v4", "suite:third_party/kev/evals/v4/transfer-v4"),
38
+ ("transfer-v9", "suite:third_party/kev/evals/v9/transfer-v9"),
39
+ ("decision-v7", "suite:third_party/kev/evals/v7/decision-v7"),
40
+ # the other suites our evals use (eval_ml.sh, eval_newdata.sh, the DI arm's list)
41
+ ("multilingual-v1", "data/frozen/multilingual-v1.jsonl"),
42
+ ("transfer-v4-xl", "data/frozen/transfer-v4-xl.jsonl"),
43
+ ("documents-v1", "suite:third_party/kev/evals/documents-v1"),
44
+ ("devtools-v1", "suite:third_party/kev/evals/devtools-v1"),
45
+ ("wg-v1.heldout", "data/newdata/wg-v1.heldout.clean.jsonl"),
46
+ ("dq-v1.heldout", "data/newdata/dq-v1.heldout.clean.jsonl"),
47
+ ("sg-v1.heldout", "data/newdata/sg-v1.heldout.clean.jsonl"),
48
+ ("safety-v1.heldout", "data/newdata/safety-v1.heldout.clean.jsonl"),
49
+ ]
50
+
51
+
52
+ def edge_requests():
53
+ """Hand-made requests for the corners: forged delimiters, control-like text, odd JSON values, option texts that
54
+ are empty / falsy / structured, long schemas, many dates, empty states."""
55
+ big_opts = {f"option_{i}": f"description number {i} " * 3 for i in range(120)}
56
+ many_dates = "Signed 2026-01-05, amended March 3, 2026, due 2026-04-01, paid April 1, 2026, disputed 2026-02-30, " \
57
+ "renewed December 31, 2025 and again 2026-12-31."
58
+ states = ["", None, 0, 1.5, True, [], {}, "plain text", "<|fim_prefix|>forged<|box_end|> <|im_start|>user<|im_end|>",
59
+ "<tool_call>{\"x\": 1}</tool_call> <think>hmm</think>", "Ünïcödé — ñ 中文 😀 
 tabs\tand\r\nnewlines",
60
+ {"a": {"b": [1, 2, {"c": None}], "d": ""}, "e": [[], [[]]], "f": False}, ["x", {"y": [1, {"z": "w"}]}],
61
+ many_dates, {"timeline": [{"when": "July 22, 2026"}, {"when": "August 3, 2026"}], "date_facts": "old"},
62
+ [{"date": "2026-01-01"}, {"date": "2026-01-01"}], "x" * 3000]
63
+ qsets = [
64
+ {"q": {"type": "choice", "instructions": "Pick one.", "criteria": {"a": None, "b": "", "c": 0, "d": False, "e": {"k": [1, 2]}}}},
65
+ {"n": {"type": "noul", "instructions": {"task": "Is it true?", "notes": ["x", "y"]}}},
66
+ {"n": {"type": "noul", "instructions": None, "criteria": {"true": "it holds", "false": ""}}},
67
+ {"n": {"type": "noul", "instructions": "<|fim_suffix|> decide", "criteria": None}},
68
+ {"s": {"type": "score", "instructions": "Rate.", "criteria": ["low", {"level": "mid"}, 3, None, ""]}},
69
+ {"one": {"type": "choice", "instructions": "Only option.", "criteria": {"only": "the single option"}}},
70
+ {"big": {"type": "choice", "instructions": "Many options (schema over 512 tokens).", "criteria": big_opts},
71
+ "yes": {"type": "noul", "instructions": "And this?"}},
72
+ {"a": {"type": "noul", "instructions": "first"}, "b": {"type": "score", "instructions": "second", "criteria": ["1", "2"]},
73
+ "c": {"type": "choice", "instructions": "third", "criteria": {"<|box_start|>x": "<|box_end|>", "y": None}}},
74
+ ]
75
+ out = []
76
+ for i, s in enumerate(states):
77
+ for j, qs in enumerate(qsets):
78
+ if (i + j) % 3 == 0 or j in (6, 7):
79
+ out.append({"state": s, "questions": json.loads(json.dumps(qs))})
80
+ # invalid requests: both sides must reject them
81
+ bad = [
82
+ {"q": {"type": "choice", "instructions": "none", "criteria": {}}},
83
+ {"q": {"type": "choice", "instructions": "too many", "criteria": {f"o{i}": None for i in range(256)}}},
84
+ {"q": {"type": "choice", "instructions": "list criteria", "criteria": ["a", "b"]}},
85
+ {"q": {"type": "score", "instructions": "one level", "criteria": ["only"]}},
86
+ {"q": {"type": "score", "instructions": "object levels", "criteria": {"a": 1, "b": 2}}},
87
+ {"q": {"type": "noul", "instructions": "list criteria", "criteria": ["yes"]}},
88
+ {"q": {"type": "noul"}},
89
+ {"q": {"type": "rank", "instructions": "unknown type", "criteria": ["a", "b"]}},
90
+ {"q": "not an object"},
91
+ {},
92
+ ]
93
+ for qs in bad:
94
+ out.append({"state": "s", "questions": qs})
95
+ return out
96
+
97
+
98
+ def load_suite(path, n, seed):
99
+ from kev.data import load_records
100
+ from kev.suite import load_split
101
+ if path.startswith("suite:"):
102
+ recs = load_split(str(ROOT / path[6:]), "development")
103
+ else:
104
+ recs = load_records(str(ROOT / path))
105
+ rng = random.Random(seed)
106
+ if n and len(recs) > n:
107
+ recs = rng.sample(recs, n)
108
+ return recs
109
+
110
+
111
+ def main():
112
+ ap = argparse.ArgumentParser()
113
+ ap.add_argument("--tokenizer", required=True, help="the converted checkpoint's tokenizer.json")
114
+ ap.add_argument("--date-facts", type=int, choices=[0, 1], required=True)
115
+ ap.add_argument("--per-suite", type=int, default=400, help="records sampled per suite (0 = all)")
116
+ ap.add_argument("--seed", type=int, default=0)
117
+ ap.add_argument("--base", default="Qwen/Qwen3.5-4B-Base")
118
+ ap.add_argument("--revision", default="1001bb4d826a52d1f399e183466143f4da7b741b")
119
+ ap.add_argument("--out", required=True)
120
+ ap.add_argument("--suites", default="all", help="comma-separated suite names (default: all)")
121
+ a = ap.parse_args()
122
+ from kev.api import with_date_facts
123
+ from kev.data import materialize
124
+ from kev.model import MAX_BRANCH, MAX_PACKED, MAX_STATE, SCHEMA_FIRST, SCHEMA_MAX, encode, load_tokenizer
125
+ from verdin.convert import QWEN_SPECIALS
126
+ from verdin.render import RenderConfig, Renderer, RequestError, Tokenizer, Unsupported
127
+ kev_tok = load_tokenizer(a.base, revision=a.revision)
128
+ cfg = RenderConfig(schema_first=SCHEMA_FIRST, date_facts=bool(a.date_facts), max_state=MAX_STATE, max_branch=MAX_BRANCH,
129
+ max_packed=MAX_PACKED, schema_max=SCHEMA_MAX)
130
+ ren = Renderer(Tokenizer(a.tokenizer, QWEN_SPECIALS), cfg)
131
+ print(f"settings: {cfg}", flush=True)
132
+
133
+ def kev_side(record):
134
+ try:
135
+ r = {**record, "state": with_date_facts(record["state"])} if a.date_facts else record
136
+ enc = encode(kev_tok, materialize(r), strict=True)
137
+ except Exception as e: # noqa: BLE001 - pydantic ValidationError (a ValueError) or a crash on malformed input
138
+ m = str(e)
139
+ return ("refused" if m.startswith(("state exceeds", "branch too long")) else "invalid", m)
140
+ if len(enc["ids"]) > MAX_PACKED:
141
+ return ("refused", f"packed request exceeds frozen {MAX_PACKED}-token limit")
142
+ return ("ok", {k: enc[k] for k in ("ids", "seg", "pos", "decide_idx", "opt_idx")})
143
+
144
+ def verdin_side(body):
145
+ try:
146
+ return ("ok", ren.encode_request(body).packed())
147
+ except Unsupported as e:
148
+ return ("refused", str(e)[len("too many tokens: "):])
149
+ except RequestError as e:
150
+ return ("invalid", str(e))
151
+
152
+ report = {"settings": {"schema_first": SCHEMA_FIRST, "date_facts": bool(a.date_facts), "max_state": MAX_STATE,
153
+ "max_branch": MAX_BRANCH, "max_packed": MAX_PACKED, "schema_max": SCHEMA_MAX,
154
+ "tokenizer": a.tokenizer, "base": f"{a.base}@{a.revision}"}, "suites": {}, "mismatches": []}
155
+ total = Counter()
156
+ t0 = time.time()
157
+ pick = None if a.suites == "all" else set(a.suites.split(","))
158
+ sources = [(name, load_suite(path, a.per_suite, a.seed)) for name, path in SUITES
159
+ if (pick is None or name in pick) and (path.startswith("suite:") or (ROOT / path).exists())]
160
+ edge = []
161
+ for i, body in enumerate(edge_requests()):
162
+ rec = {**body, "_meta": {"id": f"edge/{i}"},
163
+ "questions": {k: ({**q, "src": "edge", "label": _label(q)} if isinstance(q, dict) else q) for k, q in body["questions"].items()}}
164
+ edge.append(rec)
165
+ sources.append(("edge-cases", edge))
166
+ for name, recs in sources:
167
+ c = Counter()
168
+ for rec in recs:
169
+ body = {"state": rec["state"], "questions": {k: ({f: v for f, v in q.items() if f in ("type", "instructions", "criteria")}
170
+ if isinstance(q, dict) else q) for k, q in rec["questions"].items()}}
171
+ k, v = kev_side(rec), verdin_side(body)
172
+ if k[0] == "ok" and v[0] == "ok":
173
+ same = k[1] == v[1]
174
+ c["identical" if same else "MISMATCH tokens"] += 1
175
+ if not same:
176
+ diff = next((f for f in ("ids", "seg", "pos", "decide_idx", "opt_idx") if k[1][f] != v[1][f]), "?")
177
+ report["mismatches"].append({"suite": name, "id": rec.get("_meta", {}).get("id"), "field": diff})
178
+ elif k[0] == v[0] == "refused":
179
+ if k[1] == v[1]:
180
+ c["both refused (same cap, same message)"] += 1
181
+ else:
182
+ c["MISMATCH refusal message"] += 1
183
+ report["mismatches"].append({"suite": name, "id": rec.get("_meta", {}).get("id"), "kev": k[1][:200], "verdin": v[1][:200]})
184
+ elif k[0] == v[0] == "invalid":
185
+ c["both rejected (invalid request)"] += 1
186
+ else:
187
+ c[f"MISMATCH kev {k[0]} / verdin {v[0]}"] += 1
188
+ report["mismatches"].append({"suite": name, "id": rec.get("_meta", {}).get("id"), "kev": str(k[1])[:200], "verdin": str(v[1])[:200]})
189
+ report["suites"][name] = dict(c)
190
+ total.update(c)
191
+ print(f"{name:22s} {len(recs):5d} records {dict(c)}", flush=True)
192
+ report["total"] = dict(total)
193
+ report["records"] = sum(total.values())
194
+ report["seconds"] = round(time.time() - t0, 1)
195
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
196
+ Path(a.out).write_text(json.dumps(report, indent=1) + "\n")
197
+ bad = sum(v for k, v in total.items() if k.startswith("MISMATCH"))
198
+ print(f"TOTAL {report['records']} records: {dict(total)} -> {'PARITY OK' if not bad else f'{bad} MISMATCHES'}", flush=True)
199
+ sys.exit(1 if bad else 0)
200
+
201
+
202
+ def _label(q):
203
+ if not isinstance(q, dict): return 0
204
+ if q.get("type") == "choice" and isinstance(q.get("criteria"), dict) and q["criteria"]: return next(iter(q["criteria"]))
205
+ if q.get("type") == "noul": return False
206
+ return 0
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
verdin/tests/test_bidir.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """State-bidirectional attention (kev KEV_STATE_BIDIR / Verdin architecture.state_bidir) on a tiny random Qwen3.5 (CPU,
2
+ fp32, seconds). Three independent implementations must agree:
3
+ ref transformers' Qwen3_5TextModel, one row per question, with a hand-built boolean mask for the full-attention
4
+ layers: causal | (both state tokens and i // B == j // B); the DeltaNet layers get the 2D padding mask
5
+ kev kev.model.DecisionModel's paths with state_bidir=B: forward_rows_batch (padded batch of rows, transformers'
6
+ blockwise overlay), forward_prefix_rows (state prefilled in pieces from the cache), prefix + branch rows (serving)
7
+ verdin the torch backend with arch.state_bidir=B: chunked prefill over several sweeps, prefix cache, query chunking
8
+ plus: B = 0 reproduces the causal model exactly, and B > 0 really changes the logits.
9
+
10
+ PYTHONPATH=.:third_party/kev python -m verdin.tests.test_bidir (or pytest verdin/tests/test_bidir.py)
11
+ """
12
+ import dataclasses
13
+ import random
14
+ import sys
15
+
16
+ import torch
17
+
18
+ sys.modules.setdefault("fla", None) # transformers must take its torch reference kernels (CPU)
19
+ sys.modules.setdefault("causal_conv1d", None)
20
+
21
+ from verdin.render import Encoded # noqa: E402
22
+ from verdin.tests.test_tiny import engine, maxdiff, rand_request, tiny # noqa: E402
23
+
24
+ TOL = 2e-4
25
+ B = 16
26
+
27
+
28
+ def kev_model(model, head, bidir, attn="eager"):
29
+ """A kev DecisionModel around the tiny transformers backbone (no from_pretrained), pointer head loaded."""
30
+ from kev.model import DecisionModel, PointerHead
31
+ m = DecisionModel.__new__(DecisionModel)
32
+ torch.nn.Module.__init__(m)
33
+ model.config._attn_implementation = attn
34
+ m.lm, m.pad_id, m.recurrent, m.hybrid, m.option_isolation = model, 0, True, True, False
35
+ m.return_unknown, m.device, m.state_bidir, m._tied_lm_head = False, "cpu", bidir, False
36
+ m.head = PointerHead(model.config.hidden_size, dp=head["q.weight"].shape[0])
37
+ m.head.load_state_dict(head)
38
+ return m.eval()
39
+
40
+
41
+ def kev_enc(e):
42
+ """verdin Encoded -> kev's packed encoding (state, then each branch with positions continuing from the state)."""
43
+ S = list(e.state_ids)
44
+ ids, seg, pos, dec, opt = list(S), [0] * len(S), list(range(len(S))), [], []
45
+ for k, r in enumerate(e.rows, start=1):
46
+ base = len(ids)
47
+ ids += r.ids; seg += [k] * len(r.ids); pos += list(range(len(S), len(S) + len(r.ids)))
48
+ dec.append(base + r.decide); opt.append([base + o for o in r.opts])
49
+ return {"ids": ids, "seg": seg, "pos": pos, "decide_idx": dec, "opt_idx": opt, "option_isolation": False}
50
+
51
+
52
+ def ref_logits(model, head, e, bidir):
53
+ """Hand-built masks, one row at a time (no padding)."""
54
+ from kev.model import PointerHead
55
+ ph = PointerHead(model.config.hidden_size, dp=head["q.weight"].shape[0]); ph.load_state_dict(head); ph.eval()
56
+ S, out = list(e.state_ids), []
57
+ with torch.no_grad():
58
+ for r in e.rows:
59
+ L, Ls = len(S) + len(r.ids), len(S)
60
+ i, j = torch.arange(L)[:, None], torch.arange(L)[None, :]
61
+ allow = j <= i
62
+ if bidir:
63
+ allow = allow | ((i < Ls) & (j < Ls) & (i // bidir == j // bidir))
64
+ full = allow[None, None] if model.config._attn_implementation == "sdpa" else \
65
+ torch.zeros(1, 1, L, L).masked_fill(~allow[None, None], torch.finfo(torch.float32).min)
66
+ h = model(input_ids=torch.tensor([S + r.ids]), position_ids=torch.arange(L)[None],
67
+ attention_mask={"full_attention": full, "linear_attention": None}).last_hidden_state[0].float()
68
+ out.append(ph(h[Ls + r.decide], h[[Ls + o for o in r.opts]]).tolist())
69
+ return out
70
+
71
+
72
+ def flat(nested):
73
+ return [z.tolist() for per in nested for z in per]
74
+
75
+
76
+ def test_bidir(attn="eager"):
77
+ import kev.model as km
78
+ rng = random.Random(1)
79
+ model, sd, head, arch = tiny(0)
80
+ # states shorter than, equal to, and several times the block (3 blocks + a tail), 1-4 questions each
81
+ reqs = [rand_request(rng, n, q) for n, q in ((1, 1), (5, 2), (B, 3), (B + 1, 1), (40, 4), (3 * B + 7, 2), (70, 3))]
82
+ ref = [ref_logits(model, head, e, B) for e in reqs]
83
+ ref0 = [ref_logits(model, head, e, 0) for e in reqs]
84
+ moved = max(maxdiff(a, b) for a, b in zip(ref, ref0))
85
+ print(f" [{attn}] bidirectional vs causal reference: max |dlogit| = {moved:.3f} (must be clearly > 0)")
86
+ assert moved > 1e-2
87
+
88
+ m = kev_model(model, head, B, attn)
89
+ got = m.forward_rows_batch([kev_enc(e) for e in reqs]) # one padded batch, rows of different states
90
+ w = max(maxdiff(a, [z.tolist() for z in g]) for a, g in zip(ref, got))
91
+ print(f" [{attn}] kev forward_rows_batch (padded batch) vs reference: {w:.2e}")
92
+ assert w < TOL, w
93
+ m0 = kev_model(model, head, 0, attn)
94
+ w0 = max(maxdiff(a, [z.tolist() for z in g]) for a, g in zip(ref0, m0.forward_rows_batch([kev_enc(e) for e in reqs])))
95
+ print(f" [{attn}] kev state_bidir=0 vs causal reference: {w0:.2e}")
96
+ assert w0 < TOL, w0
97
+ assert m0._lm_mask("att", [3], 5) == "att" # off: the 2D mask passes through untouched
98
+
99
+ # forward_prefix_rows: state prefilled in pieces (KEV_PREFILL_CHUNK 5 -> rounded up to one block), rows from the cache
100
+ saved = km.LONG_SDPA, km.PREFILL_CHUNK, km.ROW_BUDGET
101
+ try:
102
+ km.LONG_SDPA, km.PREFILL_CHUNK, km.ROW_BUDGET = 1, 5, 40
103
+ w = max(maxdiff(a, [z.tolist() for z in m.forward_prefix_rows(kev_enc(e))]) for a, e in zip(ref, reqs))
104
+ print(f" [{attn}] kev forward_prefix_rows (chunked prefill, rows in budget chunks) vs reference: {w:.2e}")
105
+ assert w < TOL, w
106
+ finally:
107
+ km.LONG_SDPA, km.PREFILL_CHUNK, km.ROW_BUDGET = saved
108
+ # serving: prefix() + branch rows from the cached state
109
+ w = 0.0
110
+ for a, e in zip(ref, reqs):
111
+ enc = kev_enc(e)
112
+ ps = m._branch_rows_from_prefix(enc, m.prefix(enc)[1])
113
+ lg = [torch.log(p).tolist() for p in ps]
114
+ ra = [[x - torch.logsumexp(torch.tensor(z), 0).item() for x in z] for z in a] # compare log-probabilities
115
+ w = max(w, maxdiff(ra, lg))
116
+ print(f" [{attn}] kev prefix + branch rows (serving) vs reference (log-probs): {w:.2e}")
117
+ assert w < TOL, w
118
+ return model, sd, head, arch, reqs, ref
119
+
120
+
121
+ def test_verdin(model=None, sd=None, head=None, arch=None, reqs=None, ref=None):
122
+ if model is None:
123
+ model, sd, head, arch, reqs, ref = test_bidir()
124
+ ab = dataclasses.replace(arch, state_bidir=B)
125
+ cases = [("one sweep per batch", {}),
126
+ ("prefill_chunk = block, several sweeps", {"prefill_chunk": B, "max_sweep_tokens": 40, "max_sweep_rows": 3}),
127
+ ("prefill_chunk = 3 blocks", {"prefill_chunk": 3 * B, "max_sweep_tokens": 60}),
128
+ ("attention query chunking", {"prefill_chunk": 2 * B, "attn": 4 * 5})]
129
+ for label, kw in cases:
130
+ qchunk = kw.pop("attn", None)
131
+ e = engine(sd, head, ab, **kw)
132
+ if qchunk:
133
+ e.m.attn_elems = qchunk
134
+ assert e.m.prefill_chunk % B == 0, e.m.prefill_chunk
135
+ res = e.run(reqs)
136
+ w = max(maxdiff(a, r.logits) for a, r in zip(ref, res))
137
+ print(f" verdin ({label}; prefill_chunk {e.m.prefill_chunk}) vs reference: {w:.2e}")
138
+ assert w < TOL, (label, w)
139
+ # prefix cache: the second pass hits and still matches
140
+ e = engine(sd, head, ab, prefix_cache=8, prefix_cache_min_tokens=0, prefill_chunk=B, max_sweep_tokens=40)
141
+ e.run(reqs)
142
+ again = e.run(reqs)
143
+ assert all(r.cache_hit for r in again)
144
+ w = max(maxdiff(a, r.logits) for a, r in zip(ref, again))
145
+ print(f" verdin prefix cache (second pass) vs reference: {w:.2e}")
146
+ assert w < TOL, w
147
+ # duplicate states in one batch
148
+ dup = Encoded(reqs[5].state_ids, reqs[4].rows)
149
+ ref_dup = ref_logits(model, head, dup, B)
150
+ res = engine(sd, head, ab, prefill_chunk=B, max_sweep_tokens=30).run([reqs[5], dup, reqs[1]])
151
+ w = max(maxdiff(ref[5], res[0].logits), maxdiff(ref_dup, res[1].logits), maxdiff(ref[1], res[2].logits))
152
+ print(f" verdin duplicate states in a batch vs reference: {w:.2e}")
153
+ assert w < TOL, w
154
+ # a prefill_chunk that splits a block is refused; the default is rounded to a multiple of the block
155
+ try:
156
+ engine(sd, head, ab, prefill_chunk=B + 3)
157
+ raise AssertionError("prefill_chunk not a multiple of the block was accepted")
158
+ except ValueError:
159
+ pass
160
+ assert engine(sd, head, dataclasses.replace(arch, state_bidir=24)).m.prefill_chunk == 2040 # CPU default 2048 -> 85 x 24
161
+ # config round trip: format 2 only with the field
162
+ assert "state_bidir" not in arch.to_dict() and ab.to_dict()["state_bidir"] == B
163
+ print("state-bidirectional tests: OK")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ out = test_bidir("eager")
168
+ test_bidir("sdpa")
169
+ test_verdin(*out)
verdin/tests/test_cache_reuse.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression test (10-09): the same state requested three or more times across batches must keep working from the
2
+ prefix cache and give the same logits as a cache-less engine. Before the fix the second cache hit raised KeyError: 0.
3
+
4
+ python -m verdin.tests.test_cache_reuse [--device cpu|cuda]
5
+ """
6
+ import argparse
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+ from verdin.core import Verdin
13
+ from verdin.tests.make_tiny import make_tiny_checkpoint
14
+
15
+
16
+ def main():
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--device", default="cpu")
19
+ ap.add_argument("--tokenizer", help="tokenizer.json for the random tiny checkpoint")
20
+ a = ap.parse_args()
21
+ model = make_tiny_checkpoint(Path(tempfile.mkdtemp(prefix="verdin-tiny-")), a.tokenizer)
22
+ state = {"dialogue": " ".join(f"turn {i}: the user asks about bus {i % 7} to city {i % 5}." for i in range(80))}
23
+ qs = [{"intent": {"type": "choice", "instructions": f"Which intent is active for service {k}?",
24
+ "criteria": {"FindBus": "FindBus", "BuyBusTicket": "BuyBusTicket", "NONE": "none"}}} for k in range(5)]
25
+ cached = Verdin.from_pretrained(model, backend="cpu" if a.device == "cpu" else "cuda", device=a.device, dtype="fp32",
26
+ prefix_cache=4, prefix_cache_min_tokens=0)
27
+ plain = Verdin.from_pretrained(model, backend="cpu" if a.device == "cpu" else "cuda", device=a.device, dtype="fp32",
28
+ prefix_cache=0)
29
+ worst = 0.0
30
+ # schema-first puts the questions into the state segment, so only an identical request reuses the cached prefix
31
+ # (the DI SGD rows repeat whole requests): 1 miss + 4 hits on the same request, one request per batch
32
+ for k in range(5):
33
+ x = cached.decide(state, qs[0]); y = plain.decide(state, qs[0])
34
+ px = x["intent"]["probabilities"]; py = y["intent"]["probabilities"]
35
+ worst = max(worst, max(abs(px[o] - py[o]) for o in px))
36
+ assert worst < 1e-5, worst
37
+ print(f"cache reuse x5: OK (max |dp| vs no cache {worst:.1e})")
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
verdin/tests/test_server.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server + wire-format test (CPU, random tiny checkpoint around the real tokenizer; seconds):
2
+ - verdin.server in-process: every question type, invalid requests (422), an over-cap state (422 "too many tokens"),
3
+ 24 concurrent clients (dynamic batching) giving the same numbers as one-at-a-time, /v1/models;
4
+ - the Decision Index kit's own http engine + response validator (third_party/decision-index), unchanged;
5
+ - JevBench's own typesafe adapter (third_party/jevbench), unchanged.
6
+
7
+ python -m verdin.tests.test_server --tokenizer runs/verdin-4b-s1/tokenizer.json [--model DIR]
8
+ --model runs the same checks against a real checkpoint instead (e.g. on a GPU host).
9
+ """
10
+ import argparse
11
+ import json
12
+ import socket
13
+ import sys
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ import urllib.error
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parents[2]
22
+
23
+ REQS = [
24
+ {"state": "The parcel arrived on 2026-03-02, two weeks after the order on 2026-02-16; the mug inside was broken.",
25
+ "questions": {"damaged": {"type": "noul", "instructions": "Was anything damaged?"},
26
+ "team": {"type": "choice", "instructions": "Route it.", "criteria": {"billing": "refunds", "shipping": None, "other": ""}},
27
+ "severity": {"type": "score", "instructions": "How severe?", "criteria": ["minor", "moderate", "major"]}}},
28
+ {"state": {"user": "ana", "events": [{"t": "login"}, {"t": "export", "rows": 120000}]},
29
+ "questions": {"risky": {"type": "noul", "instructions": "Is this an unusual data export?", "criteria": {"true": "unusual", "false": "routine"}}}},
30
+ {"state": ["a", "b", {"c": [1, 2.5, True, None]}], "model": "client-name",
31
+ "questions": {"pick": {"type": "choice", "instructions": {"task": "pick", "hint": "first letter"}, "criteria": {"a": None, "b": None}}}},
32
+ {"state": "", "questions": {"only": {"type": "choice", "instructions": "One option.", "criteria": {"x": "the only one"}}}},
33
+ ]
34
+
35
+
36
+ def post(url, body, raw=None):
37
+ data = raw if raw is not None else json.dumps(body).encode()
38
+ req = urllib.request.Request(url + "/v1/systemone", data=data, headers={"Content-Type": "application/json"}, method="POST")
39
+ try:
40
+ with urllib.request.urlopen(req, timeout=600) as r:
41
+ return r.status, json.loads(r.read())
42
+ except urllib.error.HTTPError as e:
43
+ return e.code, json.loads(e.read())
44
+
45
+
46
+ def free_port():
47
+ s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close()
48
+ return p
49
+
50
+
51
+ def start(model, extra=()):
52
+ from verdin.server import main
53
+ port = free_port()
54
+ threading.Thread(target=main, args=(["--model", str(model), "--port", str(port), "--no-warmup", *extra],), daemon=True).start()
55
+ url = f"http://127.0.0.1:{port}"
56
+ for _ in range(600):
57
+ try:
58
+ urllib.request.urlopen(url + "/health", timeout=2); return url
59
+ except Exception: # noqa: BLE001
60
+ time.sleep(0.5)
61
+ raise RuntimeError("server did not start")
62
+
63
+
64
+ def check_answer(q, a):
65
+ assert a["type"] == q["type"], (q, a)
66
+ if q["type"] == "noul":
67
+ assert 0 <= a["noul"] <= 1
68
+ else:
69
+ p = a["probabilities"]
70
+ keys = list(q["criteria"]) if q["type"] == "choice" else [str(i) for i in range(len(q["criteria"]))]
71
+ assert list(p) == keys and abs(sum(p.values()) - 1) < 1e-9, a
72
+ if q["type"] == "choice":
73
+ assert a["choice"] == max(p, key=p.get)
74
+ else:
75
+ assert abs(a["score"] - sum(i * v for i, v in enumerate(p.values()))) < 1e-9 and set(a["legend"]) == set(keys)
76
+
77
+
78
+ def run(url):
79
+ # 1. every question type
80
+ single = []
81
+ for body in REQS:
82
+ code, out = post(url, body)
83
+ assert code == 200, out
84
+ assert set(out["answers"]) == set(body["questions"]) and out["usage"]["input_tokens"] > 0
85
+ assert out["model"] == body.get("model", out["model"])
86
+ for k, q in body["questions"].items():
87
+ check_answer(q, out["answers"][k])
88
+ single.append(out["answers"])
89
+ print(" question types / answers: OK")
90
+ # 2. invalid and over-cap
91
+ bad = [({"state": "x", "questions": {}}, "questions"), ({"questions": {"a": {"type": "noul", "instructions": "x"}}}, "state"),
92
+ ({"state": "x", "questions": {"a": {"type": "rank", "instructions": "x", "criteria": ["a", "b"]}}}, "type"),
93
+ ({"state": "x", "questions": {"a": {"type": "choice", "instructions": "x", "criteria": {}}}}, "criteria"),
94
+ ({"state": "x", "questions": {"a": {"type": "score", "instructions": "x", "criteria": ["one"]}}}, "score")]
95
+ for body, word in bad:
96
+ code, out = post(url, body)
97
+ assert code == 422 and word in out["error"] and "too many tokens" not in out["error"], (code, out)
98
+ code, out = post(url, None, raw=b"{not json")
99
+ assert code == 422 and "JSON" in out["error"]
100
+ big = {"state": "lorem ipsum dolor " * 30000, "questions": {"a": {"type": "noul", "instructions": "x"}}}
101
+ code, out = post(url, big)
102
+ print(f" over-cap: {code} {out.get('error', '')[:80]}")
103
+ return single, code, out
104
+
105
+
106
+ def concurrency(url, single, n_threads=24):
107
+ results, errors = {}, []
108
+
109
+ def worker(t):
110
+ try:
111
+ for j in range(4):
112
+ i = (t + j) % len(REQS)
113
+ code, out = post(url, REQS[i])
114
+ assert code == 200, out
115
+ results[(t, j)] = (i, out["answers"])
116
+ except Exception as e: # noqa: BLE001
117
+ errors.append(repr(e))
118
+ ths = [threading.Thread(target=worker, args=(t,)) for t in range(n_threads)]
119
+ [t.start() for t in ths]; [t.join() for t in ths]
120
+ assert not errors, errors[:3]
121
+ worst = 0.0
122
+ for i, ans in results.values():
123
+ for k, a in ans.items():
124
+ b = single[i][k]
125
+ if a["type"] == "noul":
126
+ worst = max(worst, abs(a["noul"] - b["noul"]))
127
+ else:
128
+ worst = max(worst, max(abs(a["probabilities"][x] - b["probabilities"][x]) for x in a["probabilities"]))
129
+ with urllib.request.urlopen(url + "/v1/models") as r:
130
+ models = json.loads(r.read())
131
+ srv = models["data"][0]["server"]
132
+ print(f" {len(results)} concurrent requests: max |dp| vs one-at-a-time {worst:.1e}; batches {srv['batches']}, "
133
+ f"largest batch {srv['max_batch_seen']}")
134
+ return worst
135
+
136
+
137
+ def di_and_jevbench(url):
138
+ sys.path.insert(0, str(ROOT / "third_party" / "decision-index"))
139
+ sys.path.insert(0, str(ROOT / "third_party" / "jevbench"))
140
+ ok = []
141
+ try:
142
+ from decision_index.engines.base import Unsupported, validate
143
+ from decision_index.engines.http import HttpSystemOne
144
+ except ImportError as e:
145
+ print(f" Decision Index kit not importable here ({e}); skipped")
146
+ else:
147
+ eng = HttpSystemOne(base_url=url, model="verdin-test")
148
+ for body in REQS:
149
+ qs = {k: q for k, q in body["questions"].items() if q["type"] in ("choice", "noul")}
150
+ if not qs: continue
151
+ resp, raw = eng(body["state"], qs)
152
+ validate(qs, resp)
153
+ try:
154
+ eng("lorem ipsum " * 40000, {"a": {"type": "noul", "instructions": "x"}})
155
+ raise AssertionError("over-cap request was not refused")
156
+ except Unsupported:
157
+ pass
158
+ eng.close(); ok.append("decision-index http engine + validate (incl. Unsupported on over-cap)")
159
+ try:
160
+ from jevbench.adapters.typesafe import TypeSafeAdapter
161
+ from jevbench.tasks import Task
162
+ except ImportError as e:
163
+ print(f" JevBench not importable here ({e}); skipped")
164
+ else:
165
+ ad = TypeSafeAdapter(endpoint=url, model="verdin-test", key_env=None)
166
+ tasks = [Task("t1", "x", "The mug was broken.", {"type": "noul", "instructions": "Damaged?"}, ["yes", "no"], "yes", "public"),
167
+ Task("t2", "x", "Refund please.", {"type": "choice", "instructions": "Team?", "criteria": {"billing": None, "tech": None}},
168
+ ["billing", "tech"], "billing", "public"),
169
+ Task("t3", "x", "Severe outage.", {"type": "score", "instructions": "Severity?", "criteria": ["low", "mid", "high"]},
170
+ ["0", "1", "2"], "2", "public")]
171
+ for t in tasks:
172
+ r = ad.run(t)
173
+ assert r.ok, (t.id, r.error)
174
+ assert abs(sum(r.probs.values()) - 1) < 1e-6
175
+ ok.append("jevbench typesafe adapter (noul / choice / score)")
176
+ for x in ok:
177
+ print(f" {x}: OK")
178
+
179
+
180
+ def main():
181
+ ap = argparse.ArgumentParser()
182
+ ap.add_argument("--tokenizer", help="tokenizer.json for the random tiny checkpoint")
183
+ ap.add_argument("--model", help="test this checkpoint instead of a random tiny one")
184
+ ap.add_argument("--server-args", default="", help="extra verdin.server flags")
185
+ ap.add_argument("--url", help="test an already running server instead (e.g. http://host:port)")
186
+ a = ap.parse_args()
187
+ sys.path.insert(0, str(ROOT))
188
+ if a.url:
189
+ url = a.url.rstrip("/")
190
+ else:
191
+ if a.model:
192
+ model = a.model
193
+ else:
194
+ from verdin.tests.make_tiny import make_tiny_checkpoint
195
+ model = make_tiny_checkpoint(Path(tempfile.mkdtemp(prefix="verdin-tiny-")), a.tokenizer)
196
+ url = start(model, a.server_args.split())
197
+ single, code, out = run(url)
198
+ assert code == 422 and "too many tokens" in out["error"], (code, out)
199
+ worst = concurrency(url, single)
200
+ # batched vs one-at-a-time: ~1e-7 in fp32 (CPU tests); on a GPU in bf16 the GEMM shapes change with the batch
201
+ # composition, so the last bits move (4e-3 max |dp| seen on the 4090, 10-09): allow 2e-2 when serving bf16 on CUDA
202
+ info = json.loads(urllib.request.urlopen(url + "/v1/models", timeout=30).read())
203
+ bf16_gpu = "bfloat16" in json.dumps(info) and "cuda" in json.dumps(info)
204
+ assert worst < (2e-2 if bf16_gpu else 1e-4), worst
205
+ di_and_jevbench(url)
206
+ print("server tests: OK")
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
verdin/tests/test_tiny.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend unit tests on a tiny random Qwen3.5 (CPU, fp32, seconds): Verdin's forward pass against transformers'
2
+ Qwen3_5TextModel run the way kev runs a hybrid backbone (one causal row per question = state + branch, positions
3
+ continuing; kev.model.DecisionModel.forward_rows_batch). Covers batching across requests, chunked prefill and multi-sweep
4
+ plans, the prefix cache, duplicate states in one batch, attention query chunking, the unknown head, and unmerged-LoRA
5
+ vs merged weights. Test-only dependency: transformers (>= 5.17; its torch reference kernels on CPU).
6
+
7
+ python -m verdin.tests.test_tiny (CPU fp32; or pytest verdin/tests/test_tiny.py)
8
+ python -m verdin.tests.test_tiny --device cuda --dtype bf16 (GPU kernels: fla, causal-conv1d, SDPA; looser tolerance)
9
+ """
10
+ import argparse
11
+ import math
12
+ import random
13
+ import sys
14
+
15
+ import torch
16
+
17
+ sys.modules.setdefault("fla", None) # transformers must take its torch reference kernels (CPU)
18
+ sys.modules.setdefault("causal_conv1d", None)
19
+
20
+ from verdin.config import Arch # noqa: E402
21
+ from verdin.render import Encoded, Row # noqa: E402
22
+ from verdin.torch_backend import TorchEngine, TorchModel, TorchOptions # noqa: E402
23
+
24
+ # logits reach ~20 on this random model; transformers' own bf16 path drifts 0.64 from fp32 on it (Verdin's bf16: 0.40), and
25
+ # fla's Triton kernels may use TF32 dots even for fp32 inputs
26
+ TOL = {"cpu-fp32": 2e-4, "cuda-fp32": 0.05, "cuda-bf16": 1.0, "cpu-bf16": 1.0}
27
+ DEVICE, DTYPE = "cpu", "fp32"
28
+
29
+
30
+ def tiny(seed=0, unknown=False):
31
+ from transformers import Qwen3_5TextConfig, Qwen3_5TextModel
32
+ torch.manual_seed(seed)
33
+ lt = ["linear_attention"] * 3 + ["full_attention"] + ["linear_attention"] * 3 + ["full_attention"]
34
+ cfg = Qwen3_5TextConfig(vocab_size=300, hidden_size=128, intermediate_size=192, num_hidden_layers=8, num_attention_heads=4,
35
+ num_key_value_heads=2, head_dim=64, linear_conv_kernel_dim=4, linear_key_head_dim=64,
36
+ linear_value_head_dim=64, linear_num_key_heads=2, linear_num_value_heads=4, rms_norm_eps=1e-6,
37
+ layer_types=lt, rope_parameters={"rope_type": "default", "rope_theta": 10000000.0,
38
+ "partial_rotary_factor": 0.25, "mrope_section": [3, 3, 2],
39
+ "mrope_interleaved": True})
40
+ cfg._attn_implementation = "eager"
41
+ model = Qwen3_5TextModel(cfg).eval()
42
+ with torch.no_grad():
43
+ for name, p in model.named_parameters():
44
+ if "norm" in name:
45
+ p.normal_(0.0, 0.2)
46
+ elif name.endswith("A_log"):
47
+ p.uniform_(-1.0, 1.0)
48
+ elif name.endswith("dt_bias"):
49
+ p.normal_(0.0, 0.5)
50
+ else:
51
+ p.normal_(0.0, 0.08)
52
+ head = {"q.weight": torch.randn(16, 128) * 0.2, "q.bias": torch.randn(16) * 0.1,
53
+ "k.weight": torch.randn(16, 128) * 0.2, "k.bias": torch.randn(16) * 0.1}
54
+ if unknown:
55
+ head["unk_key"] = torch.randn(16) * 0.5
56
+ head["unk_bias"] = torch.tensor(0.3)
57
+ arch = Arch.from_hf_text_config(cfg.to_dict())
58
+ return model, {k: v.detach().clone() for k, v in model.state_dict().items()}, head, arch
59
+
60
+
61
+ def ref_logits(model, head, enc, temperature=1.0):
62
+ """kev's row form: one causal row per question through transformers, pointer head on <decide> / </opt>."""
63
+ out, unk = [], []
64
+ S = enc.state_ids
65
+ with torch.no_grad():
66
+ for r in enc.rows:
67
+ ids = torch.tensor([S + r.ids]); pos = torch.arange(len(S) + len(r.ids))[None]
68
+ h = model(input_ids=ids, position_ids=pos).last_hidden_state[0].float()
69
+ qd = h[len(S) + r.decide] @ head["q.weight"].T + head["q.bias"]
70
+ ko = h[[len(S) + o for o in r.opts]] @ head["k.weight"].T + head["k.bias"]
71
+ scale = 1 / math.sqrt(head["q.weight"].shape[0])
72
+ out.append(((ko @ qd) * scale).tolist())
73
+ if "unk_key" in head:
74
+ unk.append(float((qd @ head["unk_key"]) * scale + head["unk_bias"]))
75
+ return out, unk
76
+
77
+
78
+ def rand_request(rng, n_state, n_q):
79
+ S = [rng.randrange(1, 300) for _ in range(n_state)]
80
+ rows = []
81
+ for _ in range(n_q):
82
+ K = rng.randint(1, 5)
83
+ ids, opts = [rng.randrange(1, 300) for _ in range(rng.randint(1, 6))], []
84
+ for _ in range(K):
85
+ ids += [rng.randrange(1, 300) for _ in range(rng.randint(1, 7))]
86
+ opts.append(len(ids) - 1)
87
+ ids.append(rng.randrange(1, 300))
88
+ rows.append(Row(ids, len(ids) - 1, opts))
89
+ return Encoded(S, rows)
90
+
91
+
92
+ def engine(sd, head, arch, lora=None, fuse=True, **kw):
93
+ opts = TorchOptions(device=DEVICE, dtype=DTYPE, **kw)
94
+ return TorchEngine(TorchModel(arch, lambda n: sd[n], head, 1.0, opts, "fp32", lora=lora, fuse=fuse))
95
+
96
+
97
+ def maxdiff(a, b):
98
+ return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
99
+
100
+
101
+ def check(eng, model, head, encs, label):
102
+ res = eng.run(encs)
103
+ worst = 0.0
104
+ for e, r in zip(encs, res):
105
+ ref, unk = ref_logits(model, head, e)
106
+ worst = max(worst, maxdiff(ref, r.logits))
107
+ if unk:
108
+ worst = max(worst, max(abs(a - b) for a, b in zip(unk, r.unknown)))
109
+ assert all(len(x) == len(y) for x, y in zip(ref, r.logits))
110
+ tol = TOL[f"{DEVICE.split(':')[0]}-{DTYPE}"]
111
+ print(f" {label}: max |dlogit| = {worst:.2e} ({DEVICE} {DTYPE}, tol {tol:g})")
112
+ assert worst < tol, f"{label}: {worst}"
113
+ return res
114
+
115
+
116
+ def test_all():
117
+ rng = random.Random(0)
118
+ model, sd, head, arch = tiny(0)
119
+ reqs = [rand_request(rng, n, q) for n, q in ((1, 1), (5, 2), (70, 3), (130, 1), (64, 4), (200, 2))]
120
+ e = engine(sd, head, arch)
121
+ check(e, model, head, reqs[:1], "single request, 1-token state")
122
+ check(e, model, head, [reqs[2]], "single request, 3 questions")
123
+ check(e, model, head, reqs, "batch of 6 requests")
124
+ # chunked prefill + split rows across sweeps
125
+ e2 = engine(sd, head, arch, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3)
126
+ check(e2, model, head, reqs, "multi-sweep (prefill_chunk 48, 80 tokens / sweep, 3 rows / sweep)")
127
+ # attention query chunking (force tiny score blocks)
128
+ e3 = engine(sd, head, arch, prefill_chunk=100)
129
+ e3.m.attn_elems = 4 * 40
130
+ if DEVICE.startswith("cuda"):
131
+ print(f" kernels: {e3.m.describe()}")
132
+ check(e3, model, head, reqs, "attention query chunking")
133
+ # prefix cache: second run hits
134
+ e4 = engine(sd, head, arch, prefix_cache=8, prefix_cache_min_tokens=0)
135
+ first = e4.run(reqs)
136
+ again = check(e4, model, head, reqs, "prefix cache (second pass)")
137
+ assert all(r.cache_hit for r in again) and not any(r.cache_hit for r in first)
138
+ e6 = engine(sd, head, arch, prefix_cache=8, prefix_cache_min_tokens=0, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3)
139
+ e6.run(reqs)
140
+ again = check(e6, model, head, reqs, "prefix cache + multi-sweep (second pass)")
141
+ assert all(r.cache_hit for r in again)
142
+ # the same state twice in one batch (and different questions)
143
+ dup = Encoded(reqs[4].state_ids, reqs[2].rows)
144
+ check(engine(sd, head, arch, prefill_chunk=40, max_sweep_tokens=60), model, head, [reqs[4], dup, reqs[1], dup], "duplicate states in a batch")
145
+ # unknown head
146
+ model_u, sd_u, head_u, arch_u = tiny(1, unknown=True)
147
+ check(engine(sd_u, head_u, arch_u), model_u, head_u, reqs[:4], "unknown head")
148
+ # unmerged LoRA vs merged weights (convert's verification path)
149
+ targets = [k for k in sd if k.endswith("_proj.weight") or ".in_proj_" in k or k.endswith("out_proj.weight")]
150
+ lora, merged = {}, dict(sd)
151
+ for k in targets:
152
+ out_f, in_f = sd[k].shape
153
+ a, b = torch.randn(4, in_f) * 0.05, torch.randn(out_f, 4) * 0.05
154
+ lora[k] = (a, b, 2.0)
155
+ merged[k] = sd[k] + 2.0 * b @ a
156
+ with torch.no_grad():
157
+ model.load_state_dict(merged)
158
+ check(engine(sd, head, arch, lora=lora, fuse=False), model, head, reqs, "unmerged LoRA (base + s*B@A) vs merged reference")
159
+ check(engine(merged, head, arch), model, head, reqs, "merged weights")
160
+ # out-of-memory handling (simulated): only the request that does not fit alone is refused
161
+ e5 = engine(sd, head, arch)
162
+ real = e5._run
163
+
164
+ def fake(reqs, keep=frozenset()):
165
+ if any(r.enc.n_state > 150 for r in reqs):
166
+ raise torch.OutOfMemoryError("simulated")
167
+ return real(reqs, keep)
168
+ e5._run = fake
169
+ res = e5.run(reqs)
170
+ assert [r.error is not None for r in res] == [e.n_state > 150 for e in reqs], [r.error for r in res]
171
+ assert all(r.logits is not None for r, e in zip(res, reqs) if e.n_state <= 150)
172
+ assert "too many tokens" in str(next(r.error for r in res if r.error is not None))
173
+ print(" simulated OOM: only the oversized request refused")
174
+ print("tiny backend tests: OK")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ ap = argparse.ArgumentParser()
179
+ ap.add_argument("--device", default="cpu")
180
+ ap.add_argument("--dtype", default="fp32")
181
+ ap.add_argument("--branch-gdr", default="chunk")
182
+ a = ap.parse_args()
183
+ DEVICE, DTYPE = a.device, a.dtype
184
+ if a.branch_gdr != "chunk":
185
+ _engine = engine
186
+ engine = lambda *x, **k: _engine(*x, branch_gdr=a.branch_gdr, **k) # noqa: E731
187
+ if DEVICE.startswith("cuda"):
188
+ import transformers.models.qwen3_5.modeling_qwen3_5 # noqa: F401 - binds transformers' torch reference kernels now
189
+ del sys.modules["fla"], sys.modules["causal_conv1d"] # ... so that only Verdin picks up the GPU kernels
190
+ test_all()
verdin/torch_backend.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verdin torch backend: our own forward pass of the Qwen3.5 hybrid backbone for prefill-only decisions.
2
+
3
+ No transformers / kev / peft at runtime. CUDA first (fla Gated-DeltaNet kernels, causal-conv1d when importable, SDPA),
4
+ and the same code on CPU with torch reference kernels (used by the parity tests).
5
+
6
+ How a batch of requests runs (planning is backend-independent: engine.py; this module executes one sweep)
7
+ ---------------------------------------------------------------------------------------------------------
8
+ A request is a state prefix (shared by all its questions) plus one branch row per question (render.Encoded). Work is
9
+ cut into *sweeps*: one pass over the 32 layers for a flat, unpadded list of tokens that mixes
10
+ - prefill segments: a request's state tokens [a, b) (long states are split into prefill_chunk pieces, one per sweep),
11
+ - branch rows: question branches of requests whose state is complete (earlier sweep, the same sweep, or the cache).
12
+ Inside a layer, prefill segments run first and update the request's PrefixState for that layer (attention K/V,
13
+ DeltaNet recurrent state, conv tail); branch rows then start from it:
14
+ - DeltaNet: one varlen kernel call for all segments (initial = carried state, final state kept) and one for all rows
15
+ (initial = the request's state replicated per row by index_select, no final state),
16
+ - causal conv: one gather over [carried tails ; tokens] (each row sees its request's last 3 pre-conv state tokens),
17
+ - full attention: per request, all of its rows' tokens attend [prefix K/V ; own row] under a block-diagonal mask, so
18
+ the prefix K/V is read once per request and never copied per question,
19
+ - projections / MLP: one GEMM each over every token of the sweep (fused q/k/v/z/b/a, gate/up), no LoRA (merged).
20
+ The last layer runs its MLP / final norm / pointer head only on the readout tokens (<decide> and </opt>).
21
+ Residual stream and every norm / gate / softmax are fp32; matmul weights and activations in the compute dtype (bf16 on
22
+ GPU, fp32 for exact parity); the pointer head is fp32.
23
+
24
+ Exactness: a branch row computed from the prefix states is the same computation as kev's causal row (state + branch,
25
+ positions continuing), so results match kev's row form up to floating-point reassociation (verdin/tests).
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import math
30
+ from dataclasses import dataclass
31
+
32
+ import torch
33
+ import torch.nn.functional as F
34
+
35
+ from .config import Arch, VerdinConfig
36
+ from .engine import BaseEngine, RunResult # noqa: F401 - RunResult re-exported for callers of this module
37
+
38
+
39
+ # ---------------------------------------------------------------------------------------------------------------------
40
+ # optional kernels
41
+
42
+ def _fla():
43
+ try:
44
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
45
+ return chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
46
+ except Exception: # noqa: BLE001 - any import failure means: use the torch reference
47
+ return None
48
+
49
+
50
+ def _cc1d():
51
+ try:
52
+ from causal_conv1d import causal_conv1d_fn
53
+ return causal_conv1d_fn
54
+ except Exception: # noqa: BLE001
55
+ return None
56
+
57
+
58
+ # ---------------------------------------------------------------------------------------------------------------------
59
+ # torch reference kernels (CPU, and the fallback on GPU)
60
+
61
+ def _l2norm(x, eps=1e-6):
62
+ return x * torch.rsqrt((x * x).sum(dim=-1, keepdim=True) + eps)
63
+
64
+
65
+ def gdr_chunk_padded(q, k, v, g, beta, initial_state=None, output_final_state=False, chunk_size=64):
66
+ """Gated delta rule over [B, L, H, D] inputs with q/k L2-normalised inside (fp32 throughout). Port of transformers'
67
+ torch_chunk_gated_delta_rule (Apache-2.0, the reference kev runs on CPU). Returns (out [B, L, H, Dv] fp32,
68
+ final state [B, H, Dk, Dv] or None)."""
69
+ B, L, H, Dk = k.shape
70
+ Dv = v.shape[-1]
71
+ q, k, v, beta, g = [x.transpose(1, 2).to(torch.float32).contiguous() for x in (q, k, v, beta, g)]
72
+ q, k = _l2norm(q), _l2norm(k)
73
+ q = q * Dk ** -0.5
74
+ pad = (chunk_size - L % chunk_size) % chunk_size
75
+ q, k, v = (F.pad(x, (0, 0, 0, pad)) for x in (q, k, v))
76
+ beta, g = (F.pad(x, (0, pad)) for x in (beta, g))
77
+ n = (L + pad) // chunk_size
78
+ v_beta, k_beta = v * beta.unsqueeze(-1), k * beta.unsqueeze(-1)
79
+ q, k, k_beta, v_beta = [x.reshape(B, H, n, chunk_size, x.shape[-1]) for x in (q, k, k_beta, v_beta)]
80
+ g = g.reshape(B, H, n, chunk_size)
81
+ upper = torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device).triu(1)
82
+ cum = g.cumsum(dim=3)
83
+ pair = (cum.unsqueeze(4) - cum.unsqueeze(3)).masked_fill(upper, float("-inf")).exp()
84
+ ut = (k_beta @ k.transpose(-1, -2)) * pair
85
+ intra = (q @ k.transpose(-1, -2)) * pair
86
+ dkb = k_beta * cum.exp().unsqueeze(-1)
87
+ new_v = torch.linalg.solve_triangular(ut, v_beta, upper=False, unitriangular=True)
88
+ k_cum = torch.linalg.solve_triangular(ut, dkb, upper=False, unitriangular=True)
89
+ S = torch.zeros(B, H, Dk, Dv, dtype=torch.float32, device=q.device) if initial_state is None else initial_state.to(torch.float32)
90
+ out = torch.zeros_like(new_v)
91
+ q = q * cum.exp().unsqueeze(-1)
92
+ k = k * (cum[..., -1:] - cum).exp().unsqueeze(-1)
93
+ cdec = cum[..., -1].exp()[..., None, None]
94
+ for i in range(n):
95
+ vn = new_v[:, :, i] - k_cum[:, :, i] @ S
96
+ out[:, :, i] = q[:, :, i] @ S + intra[:, :, i] @ vn
97
+ S = S * cdec[:, :, i] + k[:, :, i].transpose(-1, -2) @ vn
98
+ out = out.reshape(B, H, -1, Dv)[:, :, :L].transpose(1, 2)
99
+ return out, (S if output_final_state else None)
100
+
101
+
102
+ def gdr_varlen_torch(q, k, v, g, beta, cu, initial_state, output_final_state):
103
+ """Flat varlen [T, H, D] sequences (boundaries `cu`, python ints) through gdr_chunk_padded, padded at the end
104
+ (pads have beta = 0 and g = 0: they neither write nor decay the state)."""
105
+ lens = [cu[i + 1] - cu[i] for i in range(len(cu) - 1)]
106
+ if len(lens) == 1:
107
+ o, f = gdr_chunk_padded(q[None], k[None], v[None], g[None], beta[None], initial_state, output_final_state)
108
+ return o[0], f
109
+ Lm = max(lens)
110
+
111
+ def pad(x):
112
+ y = x.new_zeros((len(lens), Lm) + tuple(x.shape[1:]))
113
+ for b, (s, n) in enumerate(zip(cu[:-1], lens)):
114
+ y[b, :n] = x[s:s + n]
115
+ return y
116
+ o, f = gdr_chunk_padded(pad(q), pad(k), pad(v), pad(g), pad(beta), initial_state, output_final_state)
117
+ return torch.cat([o[b, :n] for b, n in enumerate(lens)]), f
118
+
119
+
120
+ # ---------------------------------------------------------------------------------------------------------------------
121
+ # options and weights
122
+
123
+ @dataclass
124
+ class TorchOptions:
125
+ device: str = "auto" # cuda | cpu | auto
126
+ dtype: str = "auto" # bf16 | fp32 | auto (= the checkpoint's stored dtype)
127
+ prefill_chunk: int = 0 # state tokens per prefill segment (0 = 8192 on CUDA, 2048 on CPU)
128
+ max_sweep_tokens: int = 0 # tokens per layer pass (0 = 16384 on CUDA, 4096 on CPU)
129
+ max_sweep_rows: int = 256 # branch rows per layer pass (each carries a replicated DeltaNet state, 2 MB/layer)
130
+ attn_chunk_mb: int = 0 # queries per SDPA call are bounded so that a materialised fp32 score block would stay
131
+ # under this (0 = 4096 on CUDA, 512 on CPU): long states never need an L x L matrix,
132
+ # even if SDPA falls back to its math kernel
133
+ gdr: str = "auto" # fla | torch
134
+ branch_gdr: str = "recurrent" # recurrent (default since 10-10: suite parity = chunk, c1 +19 %) | chunk
135
+ conv: str = "auto" # kernel (causal-conv1d) | torch
136
+ sdpa: str = "auto" # auto | math (force the math SDPA kernel: kev's fp32 eval setting)
137
+ prefix_cache: int = 4 # states kept across requests (LRU); 0 disables
138
+ prefix_cache_min_tokens: int = 384
139
+ prefix_cache_max_tokens: int = 262144
140
+ threads: int = 0 # CPU threads (0 = torch default)
141
+ cuda_graphs: bool = False # reserved: CUDA Graphs for the branch phase (not implemented in phase A)
142
+
143
+
144
+ class Lin:
145
+ """y = x W^T for one weight or several stacked ones (fused GEMM). With `lora` (convert-time verification only), the
146
+ parts stay separate and each adds its unmerged low-rank term s * B(A x)."""
147
+
148
+ def __init__(self, ws, lora=None, fuse=True):
149
+ if lora is None or all(x is None for x in lora):
150
+ self.w = (torch.cat(ws, 0) if len(ws) > 1 else ws[0]) if fuse else None
151
+ self.parts = None if fuse else [(w, None) for w in ws]
152
+ else:
153
+ self.w, self.parts = None, list(zip(ws, lora))
154
+ if self.w is not None and len(ws) > 1:
155
+ del ws[:]
156
+
157
+ def __call__(self, x):
158
+ if self.w is not None:
159
+ return F.linear(x, self.w)
160
+ out = []
161
+ for w, l in self.parts:
162
+ y = F.linear(x, w)
163
+ if l is not None:
164
+ a, b, s = l
165
+ y = y + (s * F.linear(F.linear(x.to(a.dtype), a), b)).to(y.dtype)
166
+ out.append(y)
167
+ return torch.cat(out, -1) if len(out) > 1 else out[0]
168
+
169
+
170
+ class _Layer:
171
+ pass
172
+
173
+
174
+ def resolve_device(device):
175
+ if device in (None, "", "auto"):
176
+ return "cuda" if torch.cuda.is_available() else "cpu"
177
+ return device
178
+
179
+
180
+ class TorchModel:
181
+ """The backbone + pointer head as plain tensors. Build with TorchModel.load(dir) for serving, or directly from a
182
+ tensor dict (convert-time verification)."""
183
+
184
+ def __init__(self, arch: Arch, get, head: dict, temperature: float, opts: TorchOptions, stored_dtype: str,
185
+ lora: dict | None = None, fuse: bool = True):
186
+ self.arch, self.opts = arch, opts
187
+ self.device = torch.device(resolve_device(opts.device))
188
+ want = opts.dtype if opts.dtype not in ("", "auto", None) else stored_dtype
189
+ self.dt = {"bf16": torch.bfloat16, "bfloat16": torch.bfloat16, "fp32": torch.float32, "float32": torch.float32}[want]
190
+ self.temperature = float(temperature)
191
+ A = arch
192
+ self.d, self.eps = A.hidden_size, A.rms_norm_eps
193
+ self.H, self.KV, self.D = A.num_attention_heads, A.num_key_value_heads, A.head_dim
194
+ self.nk, self.nv, self.dk, self.dv = A.linear_num_key_heads, A.linear_num_value_heads, A.linear_key_head_dim, A.linear_value_head_dim
195
+ self.key_dim, self.value_dim = self.nk * self.dk, self.nv * self.dv
196
+ self.conv_dim = 2 * self.key_dim + self.value_dim
197
+ self.kconv = A.linear_conv_kernel_dim
198
+ if self.kconv != 4:
199
+ raise ValueError("the conv plan assumes a width-4 causal conv (Qwen3.5)")
200
+ dev, dt = self.device, self.dt
201
+
202
+ def W(name): # a matmul weight in the compute dtype
203
+ return get(name).to(device=dev, dtype=dt)
204
+
205
+ def P(name): # a small parameter, fp32
206
+ return get(name).to(device=dev, dtype=torch.float32)
207
+
208
+ def lo(name):
209
+ if not lora or name not in lora: return None
210
+ a, b, s = lora[name]
211
+ return (a.to(dev, torch.float32), b.to(dev, torch.float32), float(s))
212
+
213
+ self.embed = W("embed_tokens.weight")
214
+ self.layers = []
215
+ for i, kind in enumerate(A.layer_types):
216
+ L = _Layer(); L.linear = kind == "linear_attention"
217
+ p = f"layers.{i}."
218
+ L.ln1 = 1.0 + P(p + "input_layernorm.weight")
219
+ L.ln2 = 1.0 + P(p + "post_attention_layernorm.weight")
220
+ if L.linear:
221
+ m = p + "linear_attn."
222
+ names = [m + "in_proj_qkv.weight", m + "in_proj_z.weight", m + "in_proj_b.weight", m + "in_proj_a.weight"]
223
+ L.in_proj = Lin([W(n) for n in names], [lo(n) for n in names], fuse)
224
+ L.out_proj = Lin([W(m + "out_proj.weight")], [lo(m + "out_proj.weight")], fuse)
225
+ cw = get(m + "conv1d.weight").to(dev, torch.float32).reshape(self.conv_dim, self.kconv)
226
+ L.conv_w = cw.contiguous() # fp32 [C, 4] (torch path)
227
+ L.conv_w_dt = cw.to(dt).contiguous() # compute dtype (causal-conv1d kernel)
228
+ L.negA = -P(m + "A_log").exp()
229
+ L.dt_bias = P(m + "dt_bias")
230
+ L.norm = P(m + "norm.weight") # plain RMSNormGated weight (not zero-centred)
231
+ else:
232
+ m = p + "self_attn."
233
+ names = [m + "q_proj.weight", m + "k_proj.weight", m + "v_proj.weight"]
234
+ L.qkv = Lin([W(n) for n in names], [lo(n) for n in names], fuse)
235
+ L.o_proj = Lin([W(m + "o_proj.weight")], [lo(m + "o_proj.weight")], fuse)
236
+ L.q_norm = 1.0 + P(m + "q_norm.weight")
237
+ L.k_norm = 1.0 + P(m + "k_norm.weight")
238
+ names = [p + "mlp.gate_proj.weight", p + "mlp.up_proj.weight"]
239
+ L.gate_up = Lin([W(n) for n in names], [lo(n) for n in names], fuse)
240
+ L.down = Lin([W(p + "mlp.down_proj.weight")], [lo(p + "mlp.down_proj.weight")], fuse)
241
+ self.layers.append(L)
242
+ self.final_norm = 1.0 + P("norm.weight")
243
+ # RoPE exactly as transformers computes inv_freq (on the CPU, fp32), partial rotary dims, positions in fp32
244
+ rd = int(A.head_dim * A.partial_rotary_factor)
245
+ self.rot = rd
246
+ self.inv_freq = (1.0 / (A.rope_theta ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd))).to(dev)
247
+ # pointer head (fp32)
248
+ self.hq_w = head["q.weight"].to(dev, torch.float32); self.hq_b = head["q.bias"].to(dev, torch.float32)
249
+ self.hk_w = head["k.weight"].to(dev, torch.float32); self.hk_b = head["k.bias"].to(dev, torch.float32)
250
+ self.unknown = "unk_key" in head
251
+ if self.unknown:
252
+ self.unk_key = head["unk_key"].to(dev, torch.float32); self.unk_bias = head["unk_bias"].to(dev, torch.float32)
253
+ self.head_scale = 1.0 / math.sqrt(self.hq_w.shape[0])
254
+ cuda = self.device.type == "cuda"
255
+ self.fla = _fla() if (cuda and opts.gdr in ("auto", "fla")) else None
256
+ if opts.gdr == "fla" and self.fla is None:
257
+ raise RuntimeError("gdr=fla requested but flash-linear-attention is not importable on this device")
258
+ self.cc1d = _cc1d() if (cuda and opts.conv in ("auto", "kernel")) else None
259
+ if opts.conv == "kernel" and self.cc1d is None:
260
+ raise RuntimeError("conv=kernel requested but causal_conv1d is not importable on this device")
261
+ self.prefill_chunk = opts.prefill_chunk or (8192 if cuda else 2048)
262
+ # state-bidirectional checkpoints (kev KEV_STATE_BIDIR): plan_sweeps starts prefill segments at multiples of
263
+ # prefill_chunk, so a multiple of the block size keeps every block whole inside one segment
264
+ self.bidir = int(A.state_bidir)
265
+ if self.bidir:
266
+ if opts.prefill_chunk and opts.prefill_chunk % self.bidir:
267
+ raise ValueError(f"prefill_chunk {opts.prefill_chunk} must be a multiple of the checkpoint's state_bidir block ({self.bidir})")
268
+ if not opts.prefill_chunk:
269
+ self.prefill_chunk = max(1, self.prefill_chunk // self.bidir) * self.bidir
270
+ self.max_tokens = opts.max_sweep_tokens or (16384 if cuda else 4096)
271
+ self.max_rows = opts.max_sweep_rows
272
+ self.attn_elems = (opts.attn_chunk_mb or (4096 if cuda else 512)) * (1 << 20) // 4
273
+ if opts.cuda_graphs:
274
+ raise NotImplementedError("CUDA Graphs for the branch phase are a reserved hook (phase B); run without --cuda-graphs")
275
+ self._zero_tail = torch.zeros(self.kconv - 1, self.conv_dim, device=dev, dtype=dt)
276
+
277
+ # -- loading ----------------------------------------------------------------------------------------------------
278
+
279
+ @classmethod
280
+ def load(cls, cfg: VerdinConfig, opts: TorchOptions):
281
+ from safetensors import safe_open
282
+ d = torch.device(resolve_device(opts.device))
283
+ where = "cpu" if d.type == "cpu" else f"{d.type}:{d.index or 0}"
284
+ with safe_open(str(cfg.file(cfg.weights["file"])), framework="pt", device=where) as f:
285
+ def get(name):
286
+ return f.get_tensor(name)
287
+ with safe_open(str(cfg.file(cfg.head["file"])), framework="pt", device="cpu") as h:
288
+ head = {k: h.get_tensor(k) for k in h.keys()}
289
+ return cls(cfg.arch, get, head, cfg.temperature, opts, cfg.weights["dtype"])
290
+
291
+ def describe(self):
292
+ return {"device": str(self.device), "dtype": str(self.dt).replace("torch.", ""), "gdr": "fla" if self.fla else "torch",
293
+ "branch_gdr": self.opts.branch_gdr if self.fla else "torch-chunk", "conv": "causal-conv1d" if self.cc1d else "torch",
294
+ "prefill_chunk": self.prefill_chunk, "max_sweep_tokens": self.max_tokens, "max_sweep_rows": self.max_rows,
295
+ "sdpa": self.opts.sdpa, "unknown_head": self.unknown, "temperature": self.temperature,
296
+ **({"state_bidir": self.bidir} if self.bidir else {})}
297
+
298
+ # -- primitives -------------------------------------------------------------------------------------------------
299
+
300
+ def _norm(self, x, w):
301
+ return F.rms_norm(x, (x.shape[-1],), w, self.eps)
302
+
303
+ def _rope(self, x, cos, sin):
304
+ """x [N, h, D] fp32, rotated in place on its first `rot` dims (rotate_half convention); returns x."""
305
+ r = self.rot
306
+ xr = x[..., :r]
307
+ rot = torch.cat((-xr[..., r // 2:], xr[..., : r // 2]), dim=-1)
308
+ x[..., :r] = xr * cos + rot * sin
309
+ return x
310
+
311
+ def _heads(self, k):
312
+ """[Lk, KV, D] -> [1, H, Lk, D]: GQA keys/values expanded once per (layer, request), shared by its query chunks."""
313
+ kh = k.transpose(0, 1).unsqueeze(0)
314
+ rep = self.H // self.KV
315
+ return kh.repeat_interleave(rep, dim=1) if rep > 1 else kh
316
+
317
+ def _sdpa(self, q, kh, vh, mask=None, causal=False):
318
+ """q [Lq, H, D], kh/vh [1, H, Lk, D] (compute dtype) -> [Lq, H, D]."""
319
+ qh = q.transpose(0, 1).unsqueeze(0)
320
+ if self.opts.sdpa == "math":
321
+ from torch.nn.attention import SDPBackend, sdpa_kernel
322
+ with sdpa_kernel([SDPBackend.MATH]):
323
+ o = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask, is_causal=causal, scale=self.D ** -0.5)
324
+ else:
325
+ o = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask, is_causal=causal, scale=self.D ** -0.5)
326
+ return o[0].transpose(0, 1)
327
+
328
+ def _q_chunk(self, n_keys):
329
+ return max(1, self.attn_elems // (self.H * max(1, n_keys)))
330
+
331
+ def _attend_prefill(self, q, K, V, a):
332
+ """Queries at prefix positions a..a+L-1 over keys 0..a+L-1 (bottom-right causal), in query chunks. State-
333
+ bidirectional checkpoints: a query also sees the later keys of its own block (all of them are in K: segments end
334
+ on a block boundary or at the state's end)."""
335
+ L, Tk = q.shape[0], K.shape[0]
336
+ step = self._q_chunk(Tk)
337
+ kh, vh = self._heads(K), self._heads(V)
338
+ B = self.bidir
339
+ if B and a // B == (a + L - 1) // B: # one block: every query sees every key 0..a+L-1
340
+ out = [self._sdpa(q[i0:i0 + step], kh, vh) for i0 in range(0, L, step)]
341
+ return torch.cat(out) if len(out) > 1 else out[0]
342
+ if a == 0 and L <= step and not B:
343
+ return self._sdpa(q, kh, vh, causal=True)
344
+ out = []
345
+ for i0 in range(0, L, step):
346
+ i1 = min(L, i0 + step)
347
+ qp = a + torch.arange(i0, i1, device=q.device)[:, None]
348
+ kp = torch.arange(Tk if B else a + i1, device=q.device)[None, :]
349
+ mask = kp <= qp
350
+ if B:
351
+ mask = mask | (kp // B == qp // B)
352
+ kn = kp.shape[1]
353
+ out.append(self._sdpa(q[i0:i1], kh[:, :, :kn], vh[:, :, :kn], mask=mask))
354
+ return torch.cat(out) if len(out) > 1 else out[0]
355
+
356
+ def _attend_rows(self, q, K, V, n_prefix, bmask):
357
+ """Branch tokens (all rows of one request) over [prefix ; rows]: every prefix key, plus causal keys of their own
358
+ row (bmask [T, T])."""
359
+ T, Tk = q.shape[0], K.shape[0]
360
+ step = self._q_chunk(Tk)
361
+ kh, vh = self._heads(K), self._heads(V)
362
+ out = []
363
+ for i0 in range(0, T, step):
364
+ i1 = min(T, i0 + step)
365
+ mask = torch.cat([torch.ones(i1 - i0, n_prefix, dtype=torch.bool, device=q.device), bmask[i0:i1]], 1)
366
+ out.append(self._sdpa(q[i0:i1], kh, vh, mask=mask))
367
+ return torch.cat(out) if len(out) > 1 else out[0]
368
+
369
+ def _gdr(self, q, k, v, g, beta, cu, cu_t, cu_cpu, initial, final, branch):
370
+ if self.fla is not None:
371
+ chunk, recurrent = self.fla
372
+ if branch and self.opts.branch_gdr == "recurrent":
373
+ o, f = recurrent(q[None], k[None], v[None], g=g[None], beta=beta[None], initial_state=initial,
374
+ output_final_state=final, use_qk_l2norm_in_kernel=True, cu_seqlens=cu_t)
375
+ else:
376
+ o, f = chunk(q[None], k[None], v[None], g[None], beta[None], initial_state=initial, output_final_state=final,
377
+ use_qk_l2norm_in_kernel=True, cu_seqlens=cu_t, cu_seqlens_cpu=cu_cpu)
378
+ return o[0], f
379
+ o, f = gdr_varlen_torch(q, k, v, g, beta, cu, initial, final)
380
+ return o.to(q.dtype), f
381
+
382
+ # -- layers -----------------------------------------------------------------------------------------------------
383
+
384
+ def _deltanet(self, i, L, h, P):
385
+ N, C = h.shape[0], self.conv_dim
386
+ proj = L.in_proj(h)
387
+ qkv, z, b, a = proj.split([C, self.value_dim, self.nv, self.nv], dim=-1)
388
+ # causal conv over [carried tails ; tokens]
389
+ if P.all_fresh: # every state starts in this sweep: zero history
390
+ tails = torch.zeros(len(P.involved) * (self.kconv - 1), C, dtype=qkv.dtype, device=qkv.device)
391
+ else:
392
+ tails = torch.stack([st.tail.get(i, self._zero_tail) for st in P.involved]).reshape(-1, C)
393
+ src = torch.cat([tails, qkv], 0)
394
+ if self.cc1d is not None and P.use_kernel_conv:
395
+ E = src.index_select(0, P.ext_idx)
396
+ y = self.cc1d(E.t().unsqueeze(0), L.conv_w_dt, None, activation="silu")
397
+ x = y[0].t().index_select(0, P.ext_out)
398
+ else:
399
+ w = L.conv_w
400
+ acc = src.index_select(0, P.conv_idx[3]).float() * w[:, 3]
401
+ for j in (2, 1, 0):
402
+ acc.addcmul_(src.index_select(0, P.conv_idx[j]), w[:, j])
403
+ x = F.silu(acc).to(self.dt)
404
+ del acc
405
+ if P.pre_states:
406
+ new_tails = src.index_select(0, P.tail_idx).reshape(len(P.pre_states), self.kconv - 1, C)
407
+ for j, st in enumerate(P.pre_states):
408
+ st.tail[i] = new_tails[j].clone() if P.persist[id(st)] else new_tails[j]
409
+ q, k, v = x.split([self.key_dim, self.key_dim, self.value_dim], dim=-1)
410
+ q = q.reshape(N, self.nk, self.dk); k = k.reshape(N, self.nk, self.dk); v = v.reshape(N, self.nv, self.dv)
411
+ if self.nv != self.nk:
412
+ q = q.repeat_interleave(self.nv // self.nk, dim=1); k = k.repeat_interleave(self.nv // self.nk, dim=1)
413
+ beta = b.float().sigmoid().to(self.dt)
414
+ g = L.negA * F.softplus(a.float() + L.dt_bias)
415
+ outs, Np, fin = [], P.n_pre, None
416
+ if Np:
417
+ init = None
418
+ if not all(P.pre_fresh):
419
+ init = torch.stack([torch.zeros(self.nv, self.dk, self.dv, device=h.device) if fresh else st.rec[i]
420
+ for st, fresh in zip(P.pre_states, P.pre_fresh)])
421
+ o, fin = self._gdr(q[:Np], k[:Np], v[:Np], g[:Np], beta[:Np], P.cu_pre, P.cu_pre_t, P.cu_pre_cpu, init, True, False)
422
+ for j, st in enumerate(P.pre_states): # a state used later gets its own memory (must not pin the batch's tensor)
423
+ st.rec[i] = fin[j].clone() if P.persist[id(st)] else fin[j]
424
+ outs.append(o)
425
+ if P.n_rows_tok:
426
+ cur = fin if P.involved_is_pre else torch.stack([st.rec[i] for st in P.involved])
427
+ init = cur.index_select(0, P.row_inv)
428
+ o, _ = self._gdr(q[Np:], k[Np:], v[Np:], g[Np:], beta[Np:], P.cu_rows, P.cu_rows_t, P.cu_rows_cpu, init, False, True)
429
+ del init
430
+ outs.append(o)
431
+ o = (torch.cat(outs) if len(outs) > 1 else outs[0]).float()
432
+ del outs
433
+ o.mul_(torch.rsqrt(o.pow(2).mean(-1, keepdim=True) + self.eps)).mul_(L.norm)
434
+ zf = z.reshape(N, self.nv, self.dv).float()
435
+ o.mul_(F.silu(zf, inplace=True))
436
+ del zf
437
+ return L.out_proj(o.reshape(N, self.value_dim).to(self.dt))
438
+
439
+ def _attention(self, i, L, h, P, last):
440
+ N, H, KV, D = h.shape[0], self.H, self.KV, self.D
441
+ proj = L.qkv(h)
442
+ qg, k, v = proj.split([H * 2 * D, KV * D, KV * D], dim=-1)
443
+ qg = qg.reshape(N, H, 2 * D)
444
+ gate = qg[..., D:].reshape(N, H * D)
445
+ q = self._rope(self._norm(qg[..., :D].float(), L.q_norm), P.cos, P.sin).to(self.dt)
446
+ k = self._rope(self._norm(k.reshape(N, KV, D).float(), L.k_norm), P.cos, P.sin).to(self.dt)
447
+ v = v.reshape(N, KV, D)
448
+ out = torch.zeros(N, H, D, dtype=self.dt, device=h.device)
449
+ for st, a, b_, f0 in P.pre_segs:
450
+ if self.bidir and (a % self.bidir or (b_ != st.n and b_ % self.bidir)):
451
+ raise RuntimeError(f"prefill segment [{a}, {b_}) of a {st.n}-token state splits a {self.bidir}-token block")
452
+ if i not in st.kv:
453
+ st.kv[i] = (torch.empty(st.n, KV, D, dtype=self.dt, device=h.device), torch.empty(st.n, KV, D, dtype=self.dt, device=h.device))
454
+ Kb, Vb = st.kv[i]
455
+ n = b_ - a
456
+ Kb[a:b_] = k[f0:f0 + n]; Vb[a:b_] = v[f0:f0 + n]
457
+ if not last: # the last layer's prefix outputs are never read (only its K/V)
458
+ out[f0:f0 + n] = self._attend_prefill(q[f0:f0 + n], Kb[:b_], Vb[:b_], a)
459
+ for st, f0, T, bmask in P.row_blocks:
460
+ Kp, Vp = st.kv[i]
461
+ Kc = torch.cat([Kp, k[f0:f0 + T]]); Vc = torch.cat([Vp, v[f0:f0 + T]])
462
+ out[f0:f0 + T] = self._attend_rows(q[f0:f0 + T], Kc, Vc, st.n, bmask)
463
+ del Kc, Vc
464
+ o = out.reshape(N, H * D).float()
465
+ del out
466
+ o.mul_(torch.sigmoid_(gate.float()))
467
+ return L.o_proj(o.to(self.dt))
468
+
469
+ def _mlp(self, L, h):
470
+ gu = L.gate_up(h)
471
+ g, u = gu.chunk(2, dim=-1)
472
+ a = F.silu(g.float(), inplace=True).mul_(u)
473
+ del gu, g, u
474
+ return L.down(a.to(self.dt))
475
+
476
+ def sweep(self, P):
477
+ """One pass over every layer for a plan. Returns final-normed fp32 hidden states at the readout tokens
478
+ ([decide of each row ; </opt> of each option]) or None for a prefill-only sweep."""
479
+ x = F.embedding(P.ids, self.embed).float()
480
+ n = len(self.layers)
481
+ for i, L in enumerate(self.layers):
482
+ last = i == n - 1
483
+ h = self._norm(x, L.ln1).to(self.dt)
484
+ mix = self._deltanet(i, L, h, P) if L.linear else self._attention(i, L, h, P, last)
485
+ del h
486
+ if last:
487
+ if P.readout is None:
488
+ return None
489
+ x = x.index_select(0, P.readout).add_(mix.index_select(0, P.readout))
490
+ else:
491
+ x.add_(mix)
492
+ del mix
493
+ h = self._norm(x, L.ln2).to(self.dt)
494
+ x.add_(self._mlp(L, h))
495
+ return self._norm(x, self.final_norm)
496
+
497
+ def head(self, hs, n_rows, opt_row):
498
+ """Pointer head on the readouts: option logits (one per option, rows concatenated) and the unknown logit per
499
+ row (or None). Raw logits (temperature 1)."""
500
+ hd, ho = hs[:n_rows], hs[n_rows:]
501
+ qd = F.linear(hd, self.hq_w, self.hq_b)
502
+ ko = F.linear(ho, self.hk_w, self.hk_b)
503
+ z = (ko * qd.index_select(0, opt_row)).sum(-1) * self.head_scale
504
+ zu = (qd @ self.unk_key) * self.head_scale + self.unk_bias if self.unknown else None
505
+ return z, zu
506
+
507
+
508
+ # ---------------------------------------------------------------------------------------------------------------------
509
+ # the engine: shared planning / caching / batching (engine.BaseEngine) + this backend's execute()
510
+
511
+ class _Plan:
512
+ pass
513
+
514
+
515
+ class TorchEngine(BaseEngine):
516
+ """Batches of Encoded requests -> raw logits on torch (CUDA or CPU)."""
517
+
518
+ backend = "torch"
519
+ oom_errors = (torch.OutOfMemoryError,)
520
+
521
+ def __init__(self, model: TorchModel):
522
+ o = model.opts
523
+ super().__init__(o.prefix_cache, o.prefix_cache_min_tokens, o.prefix_cache_max_tokens)
524
+ self.m = model
525
+ self.prefill_chunk, self.max_tokens, self.max_rows = model.prefill_chunk, model.max_tokens, model.max_rows
526
+ self.kconv, self.unknown = model.kconv, model.unknown
527
+ if model.device.type == "cuda":
528
+ torch.backends.cuda.matmul.allow_tf32 = False # the fp32 head / norms must stay fp32
529
+ torch.backends.cudnn.allow_tf32 = False
530
+ elif o.threads:
531
+ torch.set_num_threads(o.threads)
532
+
533
+ @classmethod
534
+ def load(cls, cfg: VerdinConfig, opts: TorchOptions):
535
+ return cls(TorchModel.load(cfg, opts))
536
+
537
+ def describe_backend(self):
538
+ return self.m.describe()
539
+
540
+ def sync(self):
541
+ if self.m.device.type == "cuda":
542
+ torch.cuda.synchronize(self.m.device)
543
+
544
+ def on_oom(self):
545
+ if self.m.device.type == "cuda":
546
+ torch.cuda.empty_cache()
547
+
548
+ def _tensors(self, L):
549
+ """Layout lists -> device tensors (one host-to-device copy each), RoPE tables, per-request row masks."""
550
+ m, dev = self.m, self.m.device
551
+ P = _Plan()
552
+ P.involved, P.all_fresh, P.persist = L.involved, L.all_fresh, L.persist
553
+ P.pre_segs, P.pre_states, P.pre_fresh, P.involved_is_pre, P.n_pre = L.pre_segs, L.pre_states, L.pre_fresh, L.involved_is_pre, L.n_pre
554
+ P.cu_pre, P.cu_pre_cpu = L.cu_pre, torch.tensor(L.cu_pre, dtype=torch.long)
555
+ P.cu_pre_t = P.cu_pre_cpu.to(dev)
556
+ P.tail_idx = torch.tensor(L.tail_idx, dtype=torch.long, device=dev)
557
+ P.cu_rows, P.cu_rows_cpu = L.cu_rows, torch.tensor(L.cu_rows, dtype=torch.long)
558
+ P.cu_rows_t = P.cu_rows_cpu.to(dev)
559
+ P.row_inv = torch.tensor(L.row_inv, dtype=torch.long, device=dev)
560
+ P.n_rows_tok = len(L.ids) - L.n_pre
561
+ P.row_blocks = []
562
+ for st, f0, lens in L.row_blocks:
563
+ T = sum(lens)
564
+ rid = torch.repeat_interleave(torch.arange(len(lens), device=dev), torch.tensor(lens, device=dev))
565
+ ar = torch.arange(T, device=dev)
566
+ P.row_blocks.append((st, f0, T, (rid[:, None] == rid[None, :]) & (ar[None, :] <= ar[:, None])))
567
+ P.ids = torch.tensor(L.ids, dtype=torch.long, device=dev)
568
+ freqs = torch.tensor(L.pos, dtype=torch.float32, device=dev)[:, None] * m.inv_freq[None, :]
569
+ emb = torch.cat((freqs, freqs), dim=-1)
570
+ P.cos, P.sin = emb.cos()[:, None, :], emb.sin()[:, None, :]
571
+ P.conv_idx = [torch.tensor(c, dtype=torch.long, device=dev) for c in L.conv]
572
+ P.use_kernel_conv = m.cc1d is not None
573
+ if P.use_kernel_conv:
574
+ P.ext_idx = torch.tensor(L.ext, dtype=torch.long, device=dev)
575
+ P.ext_out = torch.tensor(L.ext_out, dtype=torch.long, device=dev)
576
+ P.n_rows = len(L.row_refs)
577
+ P.readout = torch.tensor(L.dec + L.opt, dtype=torch.long, device=dev) if P.n_rows else None
578
+ P.opt_row = torch.tensor(L.opt_row, dtype=torch.long, device=dev) if P.n_rows else None
579
+ return P
580
+
581
+ @torch.inference_mode()
582
+ def execute(self, layout):
583
+ P = self._tensors(layout)
584
+ hs = self.m.sweep(P)
585
+ if hs is None:
586
+ return None, None
587
+ z, zu = self.m.head(hs, P.n_rows, P.opt_row)
588
+ return z.float().cpu().tolist(), (zu.float().cpu().tolist() if zu is not None else None)