nathaninline commited on
Commit
b9a04fd
·
verified ·
1 Parent(s): 592c89d

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/banner.png filter=lfs diff=lfs merge=lfs -text
37
+ Inkling-2-Mini-NVFP4.basalt filter=lfs diff=lfs merge=lfs -text
Inkling-2-Mini-NVFP4.basalt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45ca652a59141c7a3651bf3b91eba7f99870ac316fe995cc3cfee579efea4c8b
3
+ size 17696702353
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - thinkingmachines/Inkling-2-Mini
5
+ base_model_relation: quantized
6
+ tags:
7
+ - basalt
8
+ - nvfp4
9
+ - moe
10
+ - quantized
11
+ - dspark
12
+ - inkling2
13
+ ---
14
+
15
+ # Inkling 2 Mini NVFP4 for Basalt
16
+
17
+ ![Inkling 2 Mini NVFP4 for Basalt](assets/banner.png)
18
+
19
+ A [Basalt](https://github.com/jesdga95/basalt) pack of Thinking Machines Lab's [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) (**26B parameters**, mixture of experts) that fits a **single 16 GB GPU**, plus a small engine patch that keeps it there. All credit for the model goes to Thinking Machines Lab, and for the engine and the original pack ([jesdga/Inkling-2-Mini-Basalt](https://huggingface.co/jesdga/Inkling-2-Mini-Basalt)) to Jesús Gulfo.
20
+
21
+ ## vs the Unsloth GGUFs: 1.8 to 2.1x faster, closer to BF16
22
+
23
+ | | Unsloth [UD-Q3_K_XL](https://huggingface.co/unsloth/Inkling-2-Mini-GGUF) (llama.cpp) | Unsloth [UD-Q4_K_M](https://huggingface.co/unsloth/Inkling-2-Mini-GGUF) (llama.cpp) | **This pack (Basalt)** |
24
+ |---|---|---|---|
25
+ | **KL divergence vs BF16, mean** | 0.0159 | 0.0073 | **0.0059** |
26
+ | KL divergence vs BF16, median | 0.0074 | 0.0035 | **0.0026** |
27
+ | KL divergence vs BF16, 99th percentile | 0.155 | 0.061 | **0.053** |
28
+ | Same top token as BF16 | 94.4 % | 96.2 % | **96.6 %** |
29
+ | Perplexity vs BF16 | +1.43 % | +0.39 % | **+0.26 %** |
30
+ | **Decode speed** (same machine) | 49.1 tok/s | 42.0 tok/s | **90.1 tok/s** |
31
+ | GPUs used | RTX 5060 Ti | RTX 5060 Ti + RTX 3070 | **RTX 5060 Ti alone** |
32
+ | Context | 32K | 32K | **131K** |
33
+ | File size | 13.6 GB | 16.6 GB | 17.7 GB |
34
+
35
+ This pack's figures are with the 8-bit KV cache (`--kv fp8`), the setting used for speed. With the 16-bit cache (`--kv fp16`) it reads **0.0044** mean KLD, 97.2 % same top token and +0.19 % perplexity, for twice the cache memory.
36
+
37
+ For reference, the official Basalt pack scores 0.0026 mean KLD and 97.8 % same top token (Basalt's own 20-chunk figure), but it does not fit a 16 GB card: on the same RTX 5060 Ti, Basalt keeps about 1,080 of its 3,072 experts in RAM and decodes at **29 tok/s**.
38
+
39
+ ### How quality was measured
40
+
41
+ - Reference: the official checkpoint with its experts dequantized to BF16 (`convert_hf_to_gguf --outtype bf16`, llama.cpp `29b52d398`, the commit that added Inkling 2), run through `llama-perplexity --kl-divergence-base`.
42
+ - Text: WikiText-2 raw test, 20 chunks of 512 tokens, scored on the second half of each chunk. The base perplexity is **7.6535**, the same as the 20-chunk base on Basalt's [precision page](https://github.com/jesdga95/basalt/blob/main/docs/precision/inkling2.md) (7.6534), so this is the same reference.
43
+ - This pack: `basalt-bench --quality 20 --kld-base <base>` (Basalt's own gate: the first half of each chunk is read as a prompt, the second half goes through the decode path).
44
+ - GGUFs: `llama-perplexity --kl-divergence-base <base> --kl-divergence` with Unsloth's llama.cpp build (b12588; these GGUFs use the layout from before upstream support), against the same base file, so the same tokens.
45
+ - 20 chunks is Basalt's quick gate. The differences between the three quants are several times the standard errors (KLD ± 0.0003 to 0.0004).
46
+
47
+ ### How speed was measured
48
+
49
+ RTX 5060 Ti 16 GB (PCIe 4.0 x8) + RTX 3070 8 GB, Ryzen 9 3900X, 46 GB RAM, Linux, CUDA 13.2. Same script for all three: 3 prompts (a story, a Python class with tests, a technical explanation), 400 tokens each, temperature 0.7, reasoning effort `none`, run twice, decode speed after the first token.
50
+
51
+ | | Runs (story, code, explanation, twice) |
52
+ |---|---|
53
+ | UD-Q3_K_XL, llama.cpp | 49.4, 49.0, 49.1, 49.0, 49.0, 48.8 |
54
+ | UD-Q4_K_M, llama.cpp | 41.9, 41.8, 42.0, 41.9, 42.2, 42.2 |
55
+ | This pack, Basalt | 70.8, 117.2, 76.0, 75.3, 117.4, 84.1 |
56
+
57
+ - Basalt: `--kv fp8 --max-context 131072`, its DSpark drafter on (the default). Drafting pays most on code (117 tok/s) and least on free prose (71 to 84). At temperature 0 the same script averages 95 to 110 tok/s.
58
+ - llama.cpp: `-fa on -ctk q8_0 -ctv q8_0 -c 32768 -ngl 99`, Q4_K_M split 0.72 / 0.28 across the two cards. No drafting: the DSpark GGUF made llama.cpp slower on this machine.
59
+ - Repeated runs of the Basalt row vary by about 5 to 10 % (the drafts depend on the text).
60
+
61
+ ## Prompts and long context
62
+
63
+ Prompt reading on the RTX 5060 Ti, same server as above:
64
+
65
+ | Prompt | 481 | 2,326 | 7,663 | 18,495 | 45,761 tokens |
66
+ |---|---:|---:|---:|---:|---:|
67
+ | Read at | 1,731 | 2,514 | 2,707 | 2,337 | 1,995 tok/s |
68
+
69
+ A 103,019-token prompt is read in about 70 s, a fact hidden in the middle of it is found, and decoding still runs at 52 to 54 tok/s at that depth.
70
+
71
+ The KV cache is elastic: a short chat leaves its room to the experts, so a larger `--max-context` costs little on short chats (temperature 0.7, same script):
72
+
73
+ | `--max-context` | 64K | **131K** | 262K | 524K |
74
+ |---|---:|---:|---:|---:|
75
+ | Short-chat decode | 98.0 | **90.1** | 85.8 | 82.9 tok/s |
76
+
77
+ A long conversation does take the room it needs (about 16 KiB a token with `--kv fp8`), and the experts it pushes out are then read from RAM.
78
+
79
+ ## Files
80
+
81
+ | File | Size | What |
82
+ |---|---:|---|
83
+ | `Inkling-2-Mini-NVFP4.basalt` | 17.7 GB | the pack (`.basalt` format version 2) |
84
+ | `basalt-ajean-inkling.patch` | 56 KB | the engine patch, for Basalt `a11e19f6f` (`git am`) |
85
+ | `tools/inkling2_requant.py` | 6 KB | the script that made the pack from the official one |
86
+
87
+ ## What changed vs the official pack
88
+
89
+ The official pack keeps the release's NVFP4 experts in layers 0 to 19 and stores the MXFP8 experts of layers 20 to 23 as Q8_0. Its experts take 14.71 GiB, plus 1.10 GiB of dense weights and 0.48 GiB for the drafter: more than a 16 GB card holds.
90
+
91
+ This pack rounds the experts of **layers 20 to 23 to NVFP4** (tensor scale amax / (6 x 448), one UE4M3 scale per 16 values picked at least squared error, gate and up sharing their tensor scale as in the other NVFP4 layers; mean relative squared error 0.0066). **Every other section is copied byte for byte**: layers 0 to 19, attention, head, embedding, DSpark drafter, vision encoder. The experts drop to 12.81 GiB.
92
+
93
+ Basalt's precision page had measured this exact choice for layers 20 to 23 (NVFP4 0.00431 KLD vs Q8_0 0.00256, 20 chunks), which matches the 0.0044 measured here with the 16-bit cache.
94
+
95
+ ## Engine patch for 16 GB cards
96
+
97
+ The pack also runs on upstream Basalt, but on a 16 GB card upstream still keeps hundreds of experts in RAM, and each one read over PCIe costs speed. Same machine, same script, `--kv fp8`:
98
+
99
+ | | Experts left in RAM | Decode | First token |
100
+ |---|---:|---:|---:|
101
+ | Official pack, upstream Basalt (32K context) | 1,077 | 29.4 tok/s | 0.8 s |
102
+ | This pack, upstream Basalt `a11e19f6f` (131K) | 870 | 43.6 tok/s | 0.75 s |
103
+ | **This pack, patched Basalt (131K)** | **about 60** | **90.1 tok/s** | **0.18 s** |
104
+
105
+ The patch (5 commits, MIT like Basalt) gives that memory back to the experts:
106
+
107
+ - prompt chunks of 1,024 rows instead of 4,096 (about 0.7 GiB of buffers less; `AJEAN_PROMPT_CHUNK` restores 4,096)
108
+ - the memory estimate's margins as settings (`AJEAN_CARD_SPARE_MIB`, `AJEAN_SHARED_FIXED_MIB`): upstream's were about 0.9 GiB above what this card uses
109
+ - an elastic KV cache that starts at 8,192 positions instead of 32,768 and keeps 128 MiB free instead of 512 (`AJEAN_KV_BASE`, `AJEAN_ELASTIC_KEEP_MIB`)
110
+ - experts copied back to the card in slabs of 15: alone, each one was rounded up to the driver's 2 MiB pages and **40 % of that memory was lost**
111
+ - a prompt chunk takes each RAM expert from its card copy when it has one (first token at 131K: 0.43 s down to 0.17 s)
112
+ - the drafter's full-attention layer keeps its last 16,384 positions as a ring (`AJEAN_DRAFT_CTX`): 0.5 GiB back at 131K; only the drafts see less, the output is unchanged
113
+ - when the card is full, a new CUDA graph or MMQ buffer gives expert copies back to RAM and retries, instead of stopping the engine
114
+ - the server accepts any model name, as llama-server does
115
+
116
+ Build and run:
117
+
118
+ ```sh
119
+ git clone https://github.com/jesdga95/basalt && cd basalt
120
+ git checkout a11e19f6f && git am /path/to/basalt-ajean-inkling.patch
121
+ # build as in docs/building.md, for this model only: -DBASALT_MODELS=inkling2
122
+
123
+ AJEAN_CARD_SPARE_MIB=128 AJEAN_SHARED_FIXED_MIB=0 CUDA_MODULE_LOADING=EAGER \
124
+ ./bin/basalt serve --model Inkling-2-Mini-NVFP4.basalt --kv fp8 --max-context 131072
125
+ ```
126
+
127
+ On a card of 24 GB or more, upstream Basalt and the official pack are the better choice: everything fits there.
128
+
129
+ ## Limits
130
+
131
+ - Tested on one RTX 5060 Ti 16 GB, Linux, CUDA 13.2. Other cards are not tested.
132
+ - The vision encoder is in the pack (copied unchanged) but was not tested with this setup.
133
+ - Quality is measured on 20 chunks, speed on one machine with one script.
134
+
135
+ ## License
136
+
137
+ The model: Apache 2.0, as the base model (`LICENSE`). The patch and the script: MIT, as Basalt.
assets/banner.png ADDED

Git LFS Details

  • SHA256: d30a486642b76d5e2bbd73f78d77d6cebe25f758590372013ad7b01d363d97d9
  • Pointer size: 131 Bytes
  • Size of remote file: 384 kB
basalt-ajean-inkling.patch ADDED
@@ -0,0 +1,1140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ From 2ef97d2bf4ea697b9e0e1a8aacc025693a326896 Mon Sep 17 00:00:00 2001
2
+ From: nathaninline <mail@nathaninline.com>
3
+ Date: Sun, 22 Nov 2026 17:11:37 +0000
4
+ Subject: [PATCH 1/5] AJEAN: Inkling 2 Mini sur une carte de 16 Go
5
+
6
+ - tools/convert/inkling2_requant.py : experts Q8_0 des couches 20 a 23 du pack officiel en NVFP4 (-1,9 Gio)
7
+ - tranches de prompt de 1024 lignes (AJEAN_PROMPT_CHUNK, 4096 en amont) : ~0,7 Gio de tampons en moins
8
+ - xq prend la plus grande des deux tailles (les plans FP4 debordaient sous 4096 lignes)
9
+ - AJEAN_CARD_SPARE_MIB et AJEAN_SHARED_FIXED_MIB : marges de l estimation reglables (surestimees de ~0,9 Gio sur une 5060 Ti)
10
+ - ligne de journal AJEAN budget
11
+ ---
12
+ src/models/inkling2/model.cpp | 20 ++++-
13
+ src/models/inkling2/prompt.cpp | 14 +--
14
+ src/models/inkling2/prompt.hpp | 7 +-
15
+ tools/convert/inkling2_requant.py | 140 ++++++++++++++++++++++++++++++
16
+ 4 files changed, 172 insertions(+), 9 deletions(-)
17
+ create mode 100644 tools/convert/inkling2_requant.py
18
+
19
+ diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
20
+ index cd1c3a67d..ae273f19c 100644
21
+ --- a/src/models/inkling2/model.cpp
22
+ +++ b/src/models/inkling2/model.cpp
23
+ @@ -32,9 +32,21 @@ constexpr uint64_t kQ8Row = (uint64_t) kWidth / 32 * 34; // bytes of a Q8_0 ro
24
+ // what the sessions share once (the forward's row buffers and expert scratch, the batch windows' logits), what each one
25
+ // needs beside its caches (its logits, its windows' graphs) and what the card keeps free for the kernels' modules and the
26
+ // driver
27
+ -constexpr uint64_t kSharedFixed = 768 * kMiB;
28
+ +// AJEAN: AJEAN_SHARED_FIXED_MIB overrides the shared estimate (768 MiB upstream; about 0.9 GiB above what an RTX 5060 Ti uses)
29
+ +uint64_t ajean_shared_fixed() {
30
+ + const char* v = std::getenv("AJEAN_SHARED_FIXED_MIB");
31
+ + const long long m = v && *v ? std::atoll(v) : 768;
32
+ + return (uint64_t) (m < 0 ? 0 : m) * kMiB;
33
+ +}
34
+ +const uint64_t kSharedFixed = ajean_shared_fixed();
35
+ constexpr uint64_t kSessionFixed = 96 * kMiB;
36
+ -constexpr uint64_t kCardSpare = 1024 * kMiB;
37
+ +// AJEAN: AJEAN_CARD_SPARE_MIB overrides the card spare (1024 MiB upstream); measured unused on an RTX 5060 Ti.
38
+ +uint64_t ajean_card_spare() {
39
+ + const char* v = std::getenv("AJEAN_CARD_SPARE_MIB");
40
+ + const long long m = v && *v ? std::atoll(v) : 1024;
41
+ + return (uint64_t) (m < 64 ? 64 : m) * kMiB;
42
+ +}
43
+ +const uint64_t kCardSpare = ajean_card_spare();
44
+
45
+ // The fused projection rows of a layer: tensor suffix, first row, rows, needed on a full layer only.
46
+ struct ProjPart {
47
+ @@ -334,6 +346,10 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
48
+ uint64_t full = 0;
49
+ for (uint64_t st : stride) full += st * (uint64_t) g.n_expert;
50
+ const uint64_t want_b = full + bytes_at(want) * n_sess + shared + spare;
51
+ + basalt::log::info("basalt inkling2", "AJEAN budget: free %.0f MiB, experts %.0f, session %.0f x %llu, shared %.0f (prompt %.0f), spare %.0f",
52
+ + (double) free_b / (double) kMiB, (double) full / (double) kMiB, (double) bytes_at(want) / (double) kMiB,
53
+ + (unsigned long long) n_sess, (double) shared / (double) kMiB, (double) prompt_bytes(g) / (double) kMiB,
54
+ + (double) spare / (double) kMiB);
55
+ // when some must go: a margin for the tables and maps allocated after the plan and the driver's own rounding
56
+ const uint64_t short_b = want_b > free_b ? want_b - free_b + 128 * kMiB : 0;
57
+ const int64_t keep = req.expert_cache > 0 ? req.expert_cache : -1;
58
+ diff --git a/src/models/inkling2/prompt.cpp b/src/models/inkling2/prompt.cpp
59
+ index 049b66a78..2f1889e32 100644
60
+ --- a/src/models/inkling2/prompt.cpp
61
+ +++ b/src/models/inkling2/prompt.cpp
62
+ @@ -93,17 +93,19 @@ void carve(Carve& c, Bufs& b, const Geometry& g) {
63
+ // the experts' buffers, from the arena's base: the MLP's input (mix, its controller, nrm) is read before any is written
64
+ Carve x = c;
65
+ x.at = arena;
66
+ - b.xq = x.take<uint8_t>(mmq::q8_bytes((int64_t) P, (int64_t) E));
67
+ + // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows); AJEAN: with chunks under 4096 rows
68
+ + // the planes' per-expert padding outgrows the q8_1 rows, so xq takes the larger of the two
69
+ + const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
70
+ + const size_t a4h_al = (a4h + 255) / 256 * 256;
71
+ + const size_t xq_bytes = std::max<size_t>(mmq::q8_bytes((int64_t) P, (int64_t) E), a4h_al + a4x);
72
+ + b.xq = x.take<uint8_t>(xq_bytes);
73
+ b.gu = x.take<float>(P * 2 * (size_t) g.n_ff_exp);
74
+ b.h = x.take<float>(P * (size_t) g.n_ff_exp);
75
+ b.moe = b.h;
76
+ - // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows)
77
+ - const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
78
+ - if (a4h + 256 + a4x > mmq::q8_bytes((int64_t) P, (int64_t) E)) throw std::logic_error("inkling2 prompt: the FP4 planes outgrow xq");
79
+ b.a4h = b.xq;
80
+ - b.a4x = b.xq ? (uint8_t*) b.xq + ((a4h + 255) & ~(size_t) 255) : nullptr;
81
+ + b.a4x = b.xq ? (uint8_t*) b.xq + a4h_al : nullptr;
82
+ // the experts' input rows are rounded from nrm while it is read, so they end before it
83
+ - if (c.base && (uint8_t*) b.xq + mmq::q8_bytes((int64_t) P, (int64_t) E) > (uint8_t*) b.nrm)
84
+ + if (c.base && (uint8_t*) b.xq + xq_bytes > (uint8_t*) b.nrm)
85
+ throw std::logic_error("inkling2 prompt: the experts' input rows overlap the MLP's normed rows");
86
+ c.at = std::max(end_a, x.at);
87
+ b.xqd = c.take<uint8_t>(mmq::q8_bytes((int64_t) R, std::max<int64_t>((int64_t) E, kOut)));
88
+ diff --git a/src/models/inkling2/prompt.hpp b/src/models/inkling2/prompt.hpp
89
+ index 03de6ca86..bda6b5e8c 100644
90
+ --- a/src/models/inkling2/prompt.hpp
91
+ +++ b/src/models/inkling2/prompt.hpp
92
+ @@ -16,7 +16,12 @@ namespace basalt::models::inkling2 {
93
+ class DsparkHook;
94
+
95
+ /// The most rows one prompt chunk runs (the drafter's tap holds as many).
96
+ -constexpr int kPromptChunk = 4096;
97
+ +// AJEAN: 1024 rows by default (4096 upstream): the chunk scratch drops from ~1 GiB to ~0.25 GiB, so a 16 GB card keeps
98
+ +// every expert; -DAJEAN_PROMPT_CHUNK=4096 restores upstream.
99
+ +#ifndef AJEAN_PROMPT_CHUNK
100
+ +#define AJEAN_PROMPT_CHUNK 1024
101
+ +#endif
102
+ +constexpr int kPromptChunk = AJEAN_PROMPT_CHUNK;
103
+
104
+ class PromptRunner {
105
+ public:
106
+ diff --git a/tools/convert/inkling2_requant.py b/tools/convert/inkling2_requant.py
107
+ new file mode 100644
108
+ index 000000000..4e63584bc
109
+ --- /dev/null
110
+ +++ b/tools/convert/inkling2_requant.py
111
+ @@ -0,0 +1,140 @@
112
+ +"""AJEAN : réécrit un pack inkling2 en passant les experts Q8_0 (couches 20 à 23 du pack officiel) en NVFP4.
113
+ +
114
+ + python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
115
+ +
116
+ +Chaque matrice (gate, up, down) d'un expert Q8_0 est déquantifiée puis arrondie en NVFP4 comme le fait
117
+ +hy4flash_bf16.py (échelle de tenseur amax / (6 x 448), échelle UE4M3 par 16 valeurs choisie au moindre carré).
118
+ +gate et up partagent leur échelle de tenseur, comme dans les couches NVFP4 du pack officiel ({s_gu, s_gu, s_d, 0}).
119
+ +Les autres sections sont copiées telles quelles. Gain : ~1,9 Gio d'experts en moins sur la carte.
120
+ +"""
121
+ +from __future__ import annotations
122
+ +
123
+ +import argparse
124
+ +import json
125
+ +import multiprocessing
126
+ +import os
127
+ +import pathlib
128
+ +import sys
129
+ +import time
130
+ +
131
+ +import numpy as np
132
+ +
133
+ +HERE = pathlib.Path(__file__).resolve().parent
134
+ +sys.path.insert(0, str(HERE))
135
+ +sys.path.insert(0, str(HERE.parent))
136
+ +import checkpoint as C # noqa: E402
137
+ +import checkpoint_qwen35 as Q # noqa: E402
138
+ +import model_sections as S # noqa: E402
139
+ +from model_file import ModelFile, ModelWriter # noqa: E402
140
+ +
141
+ +H, FF, NE = 2304, 1152, 128
142
+ +Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
143
+ +Q8_ROW_FF = FF // 32 * 34
144
+ +Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
145
+ +F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
146
+ +
147
+ +
148
+ +def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
149
+ + b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
150
+ + d = b[:, :2].copy().view(np.float16).astype(np.float32)
151
+ + q = b[:, 2:].view(np.int8).astype(np.float32)
152
+ + return (q * d).reshape(rows, cols)
153
+ +
154
+ +
155
+ +def _job(args):
156
+ + path, off, e0, n = args
157
+ + with open(path, "rb") as f:
158
+ + f.seek(off + e0 * Q8_BLOB)
159
+ + raw = f.read(n * Q8_BLOB)
160
+ + out = []
161
+ + for e in range(n):
162
+ + b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
163
+ + g = q8_values(b[:FF * Q8_ROW_H], FF, H)
164
+ + u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
165
+ + d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
166
+ + gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
167
+ + gs_d = Q.fp4q_global(float(np.abs(d).max()))
168
+ + err = 0.0
169
+ + for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
170
+ + codes, sc = Q.fp4q_rows(x, gs)
171
+ + out.append(C.nvfp4_rows(codes, sc).tobytes())
172
+ + v = np.empty(x.shape, np.float32)
173
+ + v[:, 0::2] = C.E2M1[codes & 15]
174
+ + v[:, 1::2] = C.E2M1[codes >> 4]
175
+ + v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
176
+ + err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
177
+ + out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
178
+ + return b"".join(out), err / 3
179
+ +
180
+ +
181
+ +def main() -> None:
182
+ + ap = argparse.ArgumentParser()
183
+ + ap.add_argument("--pack", required=True)
184
+ + ap.add_argument("--out", required=True)
185
+ + ap.add_argument("--layers", default="20,21,22,23")
186
+ + ap.add_argument("--workers", type=int, default=12)
187
+ + a = ap.parse_args()
188
+ + if os.path.exists(a.out):
189
+ + sys.exit(f"{a.out} existe déjà")
190
+ + want = {int(x) for x in a.layers.split(",")}
191
+ + m = ModelFile(a.pack)
192
+ + lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
193
+ + rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
194
+ + eoff, _ = m.section("experts")
195
+ + new, off = [], 0
196
+ + for l, gu, dt, o, blob in rows:
197
+ + if l in want:
198
+ + if gu != 8 or blob != Q8_BLOB:
199
+ + sys.exit(f"couche {l} : type {gu} blob {blob}, attendu Q8_0 {Q8_BLOB}")
200
+ + new.append((l, 40, 40, off, F4_BLOB))
201
+ + off += F4_BLOB * NE
202
+ + else:
203
+ + new.append((l, gu, dt, off, blob))
204
+ + off += blob * NE
205
+ + total = off
206
+ + t0 = time.time()
207
+ + errs = []
208
+ +
209
+ + def experts_chunks(pool):
210
+ + for (l, gu, dt, o, blob), nl in zip(rows, new):
211
+ + if l not in want:
212
+ + left, at = blob * NE, eoff + o
213
+ + with open(a.pack, "rb") as f:
214
+ + f.seek(at)
215
+ + while left:
216
+ + b = f.read(min(64 << 20, left))
217
+ + left -= len(b)
218
+ + yield b
219
+ + continue
220
+ + jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
221
+ + for b, err in pool.imap(_job, jobs):
222
+ + errs.append(err)
223
+ + yield b
224
+ + print(f"couche {l} : NVFP4, erreur relative moyenne {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
225
+ +
226
+ + w = ModelWriter(a.out)
227
+ + with multiprocessing.Pool(a.workers) as pool:
228
+ + for name in m.names():
229
+ + so, sz = m.section(name)
230
+ + if name == "experts":
231
+ + n = w.add_chunks(name, experts_chunks(pool))
232
+ + if n != total:
233
+ + sys.exit(f"experts : {n} octets, attendu {total}")
234
+ + elif name == "experts.layout":
235
+ + w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
236
+ + elif name == "meta":
237
+ + j = json.loads(m.read("meta"))
238
+ + j["name"] = j.get("name", "Inkling 2 Mini")
239
+ + j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
240
+ + "layers_nvfp4": sorted(want),
241
+ + "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
242
+ + "UE4M3 per 16 at least squared error)"}
243
+ + w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
244
+ + else:
245
+ + w.add_file(name, a.pack, so, sz)
246
+ + w.close()
247
+ + print(f"écrit {a.out} : experts {total / 2**30:.2f} Gio (avant {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
248
+ +
249
+ +
250
+ +if __name__ == "__main__":
251
+ + main()
252
+ --
253
+ 2.43.0
254
+
255
+
256
+ From 83d4832b1adc302868fea4d2d82118b8c0496eb1 Mon Sep 17 00:00:00 2001
257
+ From: nathaninline <mail@nathaninline.com>
258
+ Date: Sun, 22 Nov 2026 17:32:07 +0000
259
+ Subject: [PATCH 2/5] AJEAN: plus d experts sur la carte (KV elastique, copies
260
+ en blocs, cache du drafter plafonne)
261
+
262
+ - base du KV elastique a 8192 positions (AJEAN_KV_BASE, 32768 en amont) et marge de 128 Mio (AJEAN_ELASTIC_KEEP_MIB, 512)
263
+ - copies des experts recuperes en blocs de 15 : un expert seul s arrondissait aux pages de 2 Mio (40 % perdus)
264
+ - tranche de prompt : chaque expert en RAM depuis sa copie carte quand elle existe, les autres en suites contigues
265
+ - couche pleine du drafter en anneau de 16384 positions (AJEAN_DRAFT_CTX) : 0,5 Gio rendus aux experts a 131k
266
+ - journal : VRAM au debut du plan, cout reel des copies
267
+ ---
268
+ src/models/inkling2/dspark.cpp | 26 +++++-
269
+ src/models/inkling2/dspark.hpp | 1 +
270
+ src/models/inkling2/model.cpp | 135 +++++++++++++++++++++++++++-----
271
+ src/models/inkling2/model.hpp | 19 +++++
272
+ src/models/inkling2/session.cpp | 12 +--
273
+ 5 files changed, 164 insertions(+), 29 deletions(-)
274
+
275
+ diff --git a/src/models/inkling2/dspark.cpp b/src/models/inkling2/dspark.cpp
276
+ index 5ee0646f9..57d1ccde7 100644
277
+ --- a/src/models/inkling2/dspark.cpp
278
+ +++ b/src/models/inkling2/dspark.cpp
279
+ @@ -50,6 +50,18 @@ uint64_t q8_bytes(uint64_t rows, uint64_t n_in) { return rows * (n_in / 32) * 34
280
+
281
+ int64_t ring_cells(const DsparkGeometry& d) { return (int64_t) d.window + kRingExtra; }
282
+ int64_t full_cells(int64_t context) { return context + kDsBlock; }
283
+ +// AJEAN: the full layer's cache keeps at most AJEAN_DRAFT_CTX positions (default 16384) as a ring over the last ones: at
284
+ +// 131K its fp16 cells took 0.5 GiB of the card from the experts. Only the drafts see less; the output does not change.
285
+ +int64_t draft_ctx() {
286
+ + static const int64_t v = [] {
287
+ + const char* e = std::getenv("AJEAN_DRAFT_CTX");
288
+ + const long long n = e && *e ? std::atoll(e) : 16384;
289
+ + return (int64_t) std::max<long long>(n, 2048);
290
+ + }();
291
+ + return v;
292
+ +}
293
+ +bool full_capped(int64_t context) { return context > draft_ctx(); }
294
+ +int64_t full_layer_cells(int64_t context) { return full_capped(context) ? draft_ctx() + kRingExtra : full_cells(context); }
295
+
296
+ bk::RopeSpec rope_of(const DsparkGeometry& d) {
297
+ bk::RopeSpec r;
298
+ @@ -302,10 +314,10 @@ uint64_t dspark_session_bytes(const Pack& pack, int64_t context) {
299
+ uint64_t n = 3 * kSlice * E * 4 + kFrRing * E * 4 + 2 * kSlice * kKV * 4 + 64; // a commit step's rows
300
+ n += bk::native_q8_1_bytes(kE, kSlice);
301
+ for (int l = 0; l < d.n_layers; ++l) // the caches, fp16 K and V
302
+ - n += 2ull * (uint64_t) (d.swa[(size_t) l] ? ring_cells(d) : full_cells(context)) * kKV * 2;
303
+ + n += 2ull * (uint64_t) (d.swa[(size_t) l] ? ring_cells(d) : full_layer_cells(context)) * kKV * 2;
304
+ n += (2 * R * E + 3 * R * kQ) * 4; // the block's rows
305
+ n += 2 * bk::wgemm::act_bytes((int64_t) std::max<uint64_t>(ff, kQ)) + dspark_ws_bytes(d) + 1024; // the window gemm's
306
+ - n += bk::gqa_decode_scratch_floats(std::max(ring_cells(d), full_cells(context)), kDsBlock, kHeads, kHeadDim) * 4;
307
+ + n += bk::gqa_decode_scratch_floats(std::max(ring_cells(d), full_layer_cells(context)), kDsBlock, kHeads, kHeadDim) * 4;
308
+ n += ((uint64_t) kDsDrafts * dspark_screen_rows((int64_t) V) + (uint64_t) kDsDrafts * kDsRnn + kDsRnn + 3 * kDsRank) * 4; // the head's
309
+ n += bk::native_q8_1_bytes(kE, kDsDrafts) + bk::native_q8_1_bytes(kDsRank, kDsDrafts) + dspark_head_scratch_bytes((int64_t) V) + 1024;
310
+ return n;
311
+ @@ -361,6 +373,12 @@ bool DsparkHook::init(const DsparkWeights* w, const Geometry& g, int64_t context
312
+ Cache& c = cache_[(size_t) l];
313
+ c.ring = d.swa[(size_t) l];
314
+ c.cap = c.ring ? ring_cells(d) : full_cells(context);
315
+ + c.win = c.ring ? (int64_t) d.window + 1 : 0;
316
+ + if (!c.ring && full_capped(context)) { // AJEAN: the full layer as a ring of its last draft_ctx() positions
317
+ + c.ring = true;
318
+ + c.cap = draft_ctx() + kRingExtra;
319
+ + c.win = draft_ctx() + 1;
320
+ + }
321
+ c.k = (uint16_t*) dev((size_t) c.cap * kKV * 2, ok);
322
+ c.v = (uint16_t*) dev((size_t) c.cap * kKV * 2, ok);
323
+ }
324
+ @@ -380,7 +398,7 @@ bool DsparkHook::init(const DsparkWeights* w, const Geometry& g, int64_t context
325
+ ws_.tickets_n = tk;
326
+ }
327
+ pos3b_ = (int32_t*) dev(R * 3 * 4, ok);
328
+ - att_cells_ = std::max(ring_cells(d), full_cells(context));
329
+ + att_cells_ = std::max(ring_cells(d), full_layer_cells(context));
330
+ att_scr_ = f(bk::gqa_decode_scratch_floats(att_cells_, kDsBlock, kHeads, kHeadDim));
331
+ approx_ = f((size_t) kDsDrafts * dspark_screen_rows((int64_t) V));
332
+ hq_ = dev(bk::native_q8_1_bytes(kE, kDsDrafts), ok);
333
+ @@ -588,7 +606,7 @@ model::Result DsparkHook::draft_begin(int32_t anchor, int64_t pos, int n, void*
334
+ if (k > 0) {
335
+ const Cache& c = cache_[(size_t) k - 1];
336
+ // a sliding-window layer sees its window before the block, the full one every position, and both the block
337
+ - const int64_t window = c.ring ? (int64_t) d.window + 1 : pos + kDsBlock;
338
+ + const int64_t window = c.win > 0 ? c.win : pos + kDsBlock;
339
+ // the splits from the cells the block reads, not from the scratch's capacity (this call is not captured): a
340
+ // short context runs few splits; the drafts only shape the speed
341
+ const int64_t cells = pos + kDsBlock - std::max<int64_t>(0, pos - window + 1) + 64;
342
+ diff --git a/src/models/inkling2/dspark.hpp b/src/models/inkling2/dspark.hpp
343
+ index 689cd7b65..f334fdd13 100644
344
+ --- a/src/models/inkling2/dspark.hpp
345
+ +++ b/src/models/inkling2/dspark.hpp
346
+ @@ -146,6 +146,7 @@ private:
347
+ uint16_t *k = nullptr, *v = nullptr; ///< fp16 [cap][kv heads][head width], position p at cell p % cap
348
+ int64_t cap = 0;
349
+ bool ring = false;
350
+ + int64_t win = 0; ///< AJEAN: the attention window of a ring (0: every position)
351
+ };
352
+ void* dev(size_t bytes, bool& ok);
353
+ void stage(int k, int n, void* stream);
354
+ diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
355
+ index ae273f19c..632134736 100644
356
+ --- a/src/models/inkling2/model.cpp
357
+ +++ b/src/models/inkling2/model.cpp
358
+ @@ -89,12 +89,30 @@ uint64_t shared_bytes(const Geometry& g, bool drafter) {
359
+ return kSharedFixed + prompt_bytes(g) + (drafter ? dspark_tap_bytes(std::max(kDecodeRows, kPromptChunk)) : 0); // PROMPT, DSPARK HOOKS
360
+ }
361
+
362
+ +int64_t ajean_kv_base() {
363
+ + static const int64_t v = [] {
364
+ + const char* e = std::getenv("AJEAN_KV_BASE");
365
+ + const long long n = e && *e ? std::atoll(e) : 8192;
366
+ + return (int64_t) std::clamp<long long>(n, 1024, core::kElasticKvBase);
367
+ + }();
368
+ + return v;
369
+ +}
370
+ +
371
+ +uint64_t ajean_elastic_keep() {
372
+ + static const uint64_t v = [] {
373
+ + const char* e = std::getenv("AJEAN_ELASTIC_KEEP_MIB");
374
+ + const long long n = e && *e ? std::atoll(e) : 128;
375
+ + return (uint64_t) std::max<long long>(n, 32) << 20;
376
+ + }();
377
+ + return v;
378
+ +}
379
+ +
380
+ InklingModel::InklingModel() = default;
381
+
382
+ InklingModel::~InklingModel() {
383
+ for (void* p : dev_) cudaFree(p);
384
+ - for (void* p : copy_)
385
+ - if (p) cudaFree(p);
386
+ + for (CopySlab& sl : slabs_)
387
+ + if (sl.base) cudaFree(sl.base);
388
+ for (const Range& r : ranges_) {
389
+ if (r.handle) core::vmm::unmap(r.va, r.own, r.handle);
390
+ core::vmm::unmap_only(r.va + r.own, r.bytes - r.own);
391
+ @@ -164,6 +182,11 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
392
+ if (!open_pack(path, pack_, err)) return {model::Status::Error, "inkling2: " + err};
393
+ flags_ = req;
394
+ cudaGetDevice(&device_);
395
+ + {
396
+ + size_t f0 = 0, t0 = 0;
397
+ + cudaMemGetInfo(&f0, &t0);
398
+ + basalt::log::info("basalt inkling2", "AJEAN vram at plan start: free %.0f MiB of %.0f", (double) f0 / (double) kMiB, (double) t0 / (double) kMiB);
399
+ + }
400
+ const Geometry& g = pack_.geo;
401
+ desc_.arch = "inkling2";
402
+ desc_.n_layers = g.n_layers;
403
+ @@ -373,7 +396,7 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
404
+ for (int l = 0; l < g.n_layers; ++l)
405
+ for (int e = 0; e < g.n_expert; ++e)
406
+ if (!on_card(l, e)) spill_order_.emplace_back(l, e);
407
+ - elastic_ = keep < 0 && want > core::kElasticKvBase;
408
+ + elastic_ = keep < 0 && want > ajean_kv_base();
409
+ uint64_t ram = 0;
410
+ for (int l = 0; l < g.n_layers; ++l) ram += (uint64_t) spill_.n_spill[(size_t) l] * stride[(size_t) l];
411
+ basalt::log::info("basalt inkling2",
412
+ @@ -423,6 +446,7 @@ model::Result InklingModel::load_experts(core::LoadPlan& reads, int file, uint64
413
+ const uint64_t gran = spill_.any() ? core::vmm::granularity() : 0;
414
+ if (spill_.any()) {
415
+ copy_.assign((size_t) g.n_layers * g.n_expert, nullptr);
416
+ + copy_slab_.assign((size_t) g.n_layers * g.n_expert, -1);
417
+ layer_copies_.assign((size_t) g.n_layers, 0);
418
+ host_addr_.assign((size_t) g.n_layers * g.n_expert, 0);
419
+ }
420
+ @@ -554,7 +578,12 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
421
+ for (auto& s : sessions)
422
+ if (model::Result r = s->prepare(); !r.ok()) return r;
423
+ if (elastic_) { // the caches back only their base yet: the RAM experts come back while the card has room
424
+ + size_t fa = 0, fb = 0, tt = 0;
425
+ + cudaMemGetInfo(&fa, &tt);
426
+ const uint64_t moved = promote(held_free(kCardSpare));
427
+ + cudaMemGetInfo(&fb, &tt);
428
+ + basalt::log::info("basalt inkling2", "AJEAN promote: %.0f MiB of copies took %.0f MiB of the card", (double) moved / (double) kMiB,
429
+ + (double) (fa - fb) / (double) kMiB);
430
+ basalt::log::info("basalt inkling2", "elastic spill: %lld of %lld RAM experts copied back to the card (%.2f GiB); they go back "
431
+ "to RAM, the least routed first, as a conversation's caches grow",
432
+ (long long) n_copy_, (long long) spill_.spilled, (double) moved / (double) kGiB);
433
+ @@ -562,6 +591,56 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
434
+ return {};
435
+ }
436
+
437
+ +void* InklingModel::slab_take(uint64_t stride, uint64_t keep_free, int& slab) {
438
+ + constexpr int kSlabExperts = 15; // 15 x 4,478,992 bytes = 32.04 pages of 2 MiB: 3 % lost
439
+ + for (size_t k = slabs_.size(); k-- > 0;) {
440
+ + CopySlab& sl = slabs_[k];
441
+ + if (!sl.base || sl.stride != stride || sl.used == sl.n) continue;
442
+ + for (int j = 0; j < sl.n; ++j)
443
+ + if (!sl.busy[(size_t) j]) {
444
+ + sl.busy[(size_t) j] = 1;
445
+ + ++sl.used;
446
+ + slab = (int) k;
447
+ + return sl.base + (uint64_t) j * stride;
448
+ + }
449
+ + }
450
+ + size_t free_b = 0, total_b = 0;
451
+ + cudaMemGetInfo(&free_b, &total_b);
452
+ + if (free_b < keep_free + stride) return nullptr;
453
+ + const int n = (int) std::min<uint64_t>(kSlabExperts, (free_b - keep_free) / stride);
454
+ + void* p = nullptr;
455
+ + if (n < 1 || cudaMalloc(&p, (uint64_t) n * stride) != cudaSuccess) {
456
+ + cudaGetLastError();
457
+ + return nullptr;
458
+ + }
459
+ + CopySlab sl;
460
+ + sl.base = static_cast<uint8_t*>(p);
461
+ + sl.stride = stride;
462
+ + sl.n = n;
463
+ + sl.used = 1;
464
+ + sl.busy.assign((size_t) n, 0);
465
+ + sl.busy[0] = 1;
466
+ + size_t k = 0;
467
+ + while (k < slabs_.size() && slabs_[k].base) ++k;
468
+ + if (k == slabs_.size()) slabs_.push_back(std::move(sl));
469
+ + else slabs_[k] = std::move(sl);
470
+ + slab = (int) k;
471
+ + return p;
472
+ +}
473
+ +
474
+ +uint64_t InklingModel::slab_give(int slab, const void* p) {
475
+ + if (slab < 0 || (size_t) slab >= slabs_.size()) return 0;
476
+ + CopySlab& sl = slabs_[(size_t) slab];
477
+ + const size_t j = (size_t) ((const uint8_t*) p - sl.base) / sl.stride;
478
+ + if (j >= sl.busy.size() || !sl.busy[j]) return 0;
479
+ + sl.busy[j] = 0;
480
+ + if (--sl.used > 0) return 0;
481
+ + const uint64_t bytes = (uint64_t) sl.n * sl.stride;
482
+ + cudaFree(sl.base);
483
+ + sl = CopySlab{};
484
+ + return bytes;
485
+ +}
486
+ +
487
+ uint64_t InklingModel::promote(uint64_t keep_free) {
488
+ const int ne = geo().n_expert;
489
+ uint64_t moved = 0;
490
+ @@ -569,23 +648,19 @@ uint64_t InklingModel::promote(uint64_t keep_free) {
491
+ const size_t i = (size_t) l * ne + e;
492
+ if (copy_[i]) continue;
493
+ const LayerWeights& w = layers_[(size_t) l];
494
+ - size_t free_b = 0, total_b = 0;
495
+ - cudaMemGetInfo(&free_b, &total_b);
496
+ - if (free_b < keep_free + w.expert_stride) break;
497
+ - void* p = nullptr;
498
+ - if (cudaMalloc(&p, w.expert_stride) != cudaSuccess) {
499
+ - cudaGetLastError();
500
+ - break;
501
+ - }
502
+ + int slab = -1;
503
+ + void* p = slab_take(w.expert_stride, keep_free, slab);
504
+ + if (!p) break;
505
+ const int keep = ne - w.n_spill;
506
+ const uint8_t* src = w.spill_host + (uint64_t) (spill_.slot[(size_t) l][(size_t) e] - keep) * w.expert_stride;
507
+ const unsigned long long at = (unsigned long long) p;
508
+ if (cudaMemcpy(p, src, w.expert_stride, cudaMemcpyHostToDevice) != cudaSuccess ||
509
+ cudaMemcpy(w.blob_table + e, &at, 8, cudaMemcpyHostToDevice) != cudaSuccess) {
510
+ - cudaFree(p);
511
+ + slab_give(slab, p);
512
+ break;
513
+ }
514
+ copy_[i] = p;
515
+ + copy_slab_[i] = slab;
516
+ ++n_copy_;
517
+ ++layer_copies_[(size_t) l];
518
+ moved += w.expert_stride;
519
+ @@ -616,13 +691,30 @@ void InklingModel::lend(bool low, void* stream) {
520
+ }
521
+
522
+ bool InklingModel::stage_from_card(int l, void* stream) const {
523
+ + // AJEAN: every RAM expert of the layer from its card copy when it has one, the others from RAM in runs of adjacent
524
+ + // slots (upstream read the whole layer's RAM experts over the bus unless every one had a copy: at 131K a 38-token
525
+ + // prompt waited about 0.2 s on it)
526
+ const LayerWeights& w = layers_[(size_t) l];
527
+ - if (copy_.empty() || w.n_spill == 0 || layer_copies_[(size_t) l] < w.n_spill) return false;
528
+ - const int ne = geo().n_expert;
529
+ - for (int e = 0; e < ne; ++e)
530
+ + if (copy_.empty() || w.n_spill == 0) return false;
531
+ + const int ne = geo().n_expert, keep = ne - w.n_spill;
532
+ + std::vector<int> host;
533
+ + for (int e = 0; e < ne; ++e) {
534
+ + const int slot = spill_.slot[(size_t) l][(size_t) e];
535
+ + if (slot < keep) continue;
536
+ if (const void* c = copy_[(size_t) l * ne + e])
537
+ - cudaMemcpyAsync(w.experts + (uint64_t) spill_.slot[(size_t) l][(size_t) e] * w.expert_stride, c, w.expert_stride,
538
+ - cudaMemcpyDeviceToDevice, (cudaStream_t) stream);
539
+ + cudaMemcpyAsync(w.experts + (uint64_t) slot * w.expert_stride, c, w.expert_stride, cudaMemcpyDeviceToDevice,
540
+ + (cudaStream_t) stream);
541
+ + else
542
+ + host.push_back(slot);
543
+ + }
544
+ + std::sort(host.begin(), host.end());
545
+ + for (size_t i = 0; i < host.size();) {
546
+ + size_t j = i + 1;
547
+ + while (j < host.size() && host[j] == host[j - 1] + 1) ++j;
548
+ + cudaMemcpyAsync(w.experts + (uint64_t) host[i] * w.expert_stride, w.spill_host + (uint64_t) (host[i] - keep) * w.expert_stride,
549
+ + (size_t) (j - i) * w.expert_stride, cudaMemcpyHostToDevice, (cudaStream_t) stream);
550
+ + i = j;
551
+ + }
552
+ return true;
553
+ }
554
+
555
+ @@ -630,17 +722,22 @@ uint64_t InklingModel::demote(uint64_t bytes, void* stream) {
556
+ const int ne = geo().n_expert;
557
+ std::vector<size_t> out;
558
+ uint64_t freed = 0;
559
+ + // AJEAN: a slab frees its memory once all its copies leave: count what each slab would give back
560
+ + std::vector<int> left(slabs_.size());
561
+ + for (size_t k = 0; k < slabs_.size(); ++k) left[k] = slabs_[k].used;
562
+ for (auto it = spill_order_.rbegin(); it != spill_order_.rend() && freed < bytes; ++it) {
563
+ const size_t i = (size_t) it->first * ne + it->second;
564
+ if (!copy_[i]) continue;
565
+ cudaMemcpyAsync(layers_[(size_t) it->first].blob_table + it->second, &host_addr_[i], 8, cudaMemcpyHostToDevice, (cudaStream_t) stream);
566
+ out.push_back(i);
567
+ - freed += layers_[(size_t) it->first].expert_stride;
568
+ + const int k = copy_slab_[i];
569
+ + if (k >= 0 && --left[(size_t) k] == 0) freed += (uint64_t) slabs_[(size_t) k].n * slabs_[(size_t) k].stride;
570
+ }
571
+ if (out.empty()) return 0;
572
+ cudaStreamSynchronize((cudaStream_t) stream);
573
+ for (size_t i : out) {
574
+ - cudaFree(copy_[i]);
575
+ + slab_give(copy_slab_[i], copy_[i]);
576
+ + copy_slab_[i] = -1;
577
+ copy_[i] = nullptr;
578
+ --n_copy_;
579
+ --layer_copies_[i / (size_t) ne];
580
+ diff --git a/src/models/inkling2/model.hpp b/src/models/inkling2/model.hpp
581
+ index d38166f35..8b62000e6 100644
582
+ --- a/src/models/inkling2/model.hpp
583
+ +++ b/src/models/inkling2/model.hpp
584
+ @@ -17,6 +17,12 @@
585
+
586
+ namespace basalt::models::inkling2 {
587
+
588
+ +/// AJEAN: the cells a session's full caches back at start with an elastic context (core::kElasticKvBase, 32768, upstream);
589
+ +/// AJEAN_KV_BASE overrides it (default 8192: a short chat leaves about 0.4 GiB more to the experts on a 16 GB card).
590
+ +int64_t ajean_kv_base();
591
+ +/// AJEAN: the free bytes a cache growth or a return of experts leaves on the card (512 MiB upstream); AJEAN_ELASTIC_KEEP_MIB.
592
+ +uint64_t ajean_elastic_keep();
593
+ +
594
+ constexpr int64_t kDefaultContext = 8192;
595
+
596
+ /// The four loop controllers of a core layer: the query, key, value and MLP inputs' messages.
597
+ @@ -162,6 +168,19 @@ private:
598
+ std::vector<unsigned long long> host_addr_;
599
+ int64_t n_copy_ = 0;
600
+ std::vector<int> layer_copies_; ///< [layer] RAM experts with a card copy
601
+ + // AJEAN: the card copies sit in slabs of kSlabExperts slots (one cudaMalloc each); an expert alone rounds up to the
602
+ + // driver's 2 MiB pages (4.27 MiB -> 6 MiB, 40 % lost). A slab is freed when its last copy leaves; promote fills in
603
+ + // spill order and demote empties in reverse, so the least routed slabs go first.
604
+ + struct CopySlab {
605
+ + uint8_t* base = nullptr;
606
+ + uint64_t stride = 0;
607
+ + int n = 0, used = 0;
608
+ + std::vector<char> busy;
609
+ + };
610
+ + std::vector<CopySlab> slabs_;
611
+ + std::vector<int> copy_slab_; ///< [layer * n_expert + expert] the slab of its copy (-1: none)
612
+ + void* slab_take(uint64_t stride, uint64_t keep_free, int& slab);
613
+ + uint64_t slab_give(int slab, const void* p); ///< bytes the card got back (the slab's when it emptied)
614
+ // [vision] the experts' memory lent to the image encoder: each lent range's bytes, in RAM until refill
615
+ struct LentRange {
616
+ size_t range = 0;
617
+ diff --git a/src/models/inkling2/session.cpp b/src/models/inkling2/session.cpp
618
+ index d2208b3e2..97e8ea6cf 100644
619
+ --- a/src/models/inkling2/session.cpp
620
+ +++ b/src/models/inkling2/session.cpp
621
+ @@ -204,11 +204,11 @@ public:
622
+ if (!c.ring && m_.elastic()) { // the elastic KV: the range reserved, its first kElasticKvBase cells backed
623
+ for (int j = 0; j < 2; ++j) {
624
+ auto a = std::make_unique<core::ElasticArray>();
625
+ - if (ok && (!a->open(bytes, err) || !a->ensure(cell_bytes() * (uint64_t) core::kElasticKvBase, 0, err))) ok = false;
626
+ + if (ok && (!a->open(bytes, err) || !a->ensure(cell_bytes() * (uint64_t) ajean_kv_base(), 0, err))) ok = false;
627
+ (j ? c.v : c.k) = a->data();
628
+ elastic_.push_back(std::move(a));
629
+ }
630
+ - backed_ = core::kElasticKvBase;
631
+ + backed_ = ajean_kv_base();
632
+ } else {
633
+ c.k = alloc(bytes, ok);
634
+ c.v = alloc(bytes, ok);
635
+ @@ -460,7 +460,7 @@ public:
636
+ // and when the card has no room the RAM experts' card copies go back to RAM first, the least routed first. False when
637
+ // even without any copy there is no room.
638
+ static constexpr int64_t kElasticKvStep = 8192;
639
+ - static constexpr uint64_t kElasticKeep = 512ull << 20; // free bytes a grow leaves (the driver, the graphs)
640
+ + static uint64_t kElasticKeep_() { return ajean_elastic_keep(); } // AJEAN: free bytes a grow leaves (512 MiB upstream)
641
+ bool ensure_positions(int64_t positions, std::string& err) {
642
+ if (elastic_.empty() || positions <= backed_) return true;
643
+ const int64_t target = std::min<int64_t>(m_.context(), (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
644
+ @@ -468,7 +468,7 @@ public:
645
+ const uint64_t grow = (uint64_t) elastic_.size() * (bytes - std::min<uint64_t>(bytes, elastic_[0]->backed())) + (64ull << 20);
646
+ size_t free_b = 0, total_b = 0;
647
+ cudaMemGetInfo(&free_b, &total_b);
648
+ - const uint64_t keep_free = m_.held_free(kElasticKeep);
649
+ + const uint64_t keep_free = m_.held_free(kElasticKeep_());
650
+ if (free_b < grow + keep_free) {
651
+ const uint64_t freed = m_.demote(grow + keep_free - free_b, stream_);
652
+ basalt::log::info("basalt inkling2", "elastic spill: the caches grow to %lld positions; %.2f GiB of expert copies go back to RAM "
653
+ @@ -486,7 +486,7 @@ public:
654
+ // the base), and the RAM experts come back to the card while it has room.
655
+ void restart_positions(int64_t positions) {
656
+ if (elastic_.empty()) return;
657
+ - const int64_t keep = std::max<int64_t>(core::kElasticKvBase, (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
658
+ + const int64_t keep = std::max<int64_t>(ajean_kv_base(), (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
659
+ if (keep < backed_) {
660
+ cudaStreamSynchronize(stream_);
661
+ for (auto& a : elastic_) a->trim(cell_bytes() * (uint64_t) keep);
662
+ @@ -494,7 +494,7 @@ public:
663
+ }
664
+ if (m_.promoted() < m_.spill().spilled && !m_.lent()) {
665
+ cudaStreamSynchronize(stream_);
666
+ - m_.promote(m_.held_free(kElasticKeep) + (uint64_t) elastic_.size() * cell_bytes() * (uint64_t) std::max<int64_t>(0, keep - backed_));
667
+ + m_.promote(m_.held_free(kElasticKeep_()) + (uint64_t) elastic_.size() * cell_bytes() * (uint64_t) std::max<int64_t>(0, keep - backed_));
668
+ }
669
+ }
670
+ size_t kv_bytes_of(const VisitCache& c) const { return (size_t) kKvHeads * (size_t) c.cap * kHeadDim * elem(); }
671
+ --
672
+ 2.43.0
673
+
674
+
675
+ From e2837d78b39f5e4db910d89b04e1c8b5bec7bf0c Mon Sep 17 00:00:00 2001
676
+ From: nathaninline <mail@nathaninline.com>
677
+ Date: Sun, 22 Nov 2026 17:45:29 +0000
678
+ Subject: [PATCH 3/5] AJEAN: le serveur accepte tout nom de modele (comme
679
+ llama-server)
680
+
681
+ ---
682
+ serve/handler.py | 2 ++
683
+ 1 file changed, 2 insertions(+)
684
+
685
+ diff --git a/serve/handler.py b/serve/handler.py
686
+ index e5b162e14..98af20c2c 100644
687
+ --- a/serve/handler.py
688
+ +++ b/serve/handler.py
689
+ @@ -518,6 +518,8 @@ def make_handler(target: Service | Router):
690
+ # llama.cpp's tokenizer routes name no model: the shown one's tokenizer, as /props describes it
691
+ self.svc = router.shown() if requested is None and path in ("/tokenize", "/detokenize") else \
692
+ router.service_for(requested)
693
+ + if self.svc is None: # AJEAN: any model name reaches the model shown, as with llama-server
694
+ + self.svc = router.shown()
695
+ if self.svc is None:
696
+ self._unknown_model(path, requested)
697
+ return
698
+ --
699
+ 2.43.0
700
+
701
+
702
+ From a3f06956b3e64320f48af1273a2579d2c01f94b6 Mon Sep 17 00:00:00 2001
703
+ From: nathaninline <mail@nathaninline.com>
704
+ Date: Sun, 22 Nov 2026 17:59:26 +0000
705
+ Subject: [PATCH 4/5] AJEAN: carte pleine sans arret du moteur
706
+
707
+ - graphe de fenetre qui ne s instancie pas faute de memoire : 256 Mio de copies d experts rendus a la RAM et nouvelle capture, sinon cette forme tourne sans graphe (le moteur sortait sur cudaGraphInstantiate: out of memory)
708
+ - reservoir MMQ : en cas d echec de cudaMalloc, copies d experts rendues puis nouvel essai (le moteur sortait sur mmq: out of memory)
709
+ ---
710
+ src/models/inkling2/model.cpp | 11 +++++++++++
711
+ src/models/inkling2/session.cpp | 30 +++++++++++++++++++++++++++---
712
+ src/prefill/mmq/mmq_host.cu | 15 ++++++++++++++-
713
+ 3 files changed, 52 insertions(+), 4 deletions(-)
714
+
715
+ diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
716
+ index 632134736..f17302ff0 100644
717
+ --- a/src/models/inkling2/model.cpp
718
+ +++ b/src/models/inkling2/model.cpp
719
+ @@ -15,11 +15,16 @@
720
+ #include <cuda_runtime.h>
721
+
722
+ #include <algorithm>
723
+ +#include <functional>
724
+ #include <chrono>
725
+ #include <cstdlib>
726
+ #include <cstring>
727
+ #include <new>
728
+
729
+ +namespace basalt {
730
+ +extern std::function<uint64_t(uint64_t)> g_ajean_oom_hook; // src/prefill/mmq/mmq_host.cu
731
+ +}
732
+ +
733
+ namespace basalt::models::inkling2 {
734
+ namespace {
735
+ constexpr uint64_t kGiB = 1ull << 30;
736
+ @@ -577,6 +582,12 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
737
+ if (model::Result r = dspark_->finish(head_, embd_dev_, embed_norm_, nullptr); !r.ok()) return r;
738
+ for (auto& s : sessions)
739
+ if (model::Result r = s->prepare(); !r.ok()) return r;
740
+ + if (spill_.any()) // AJEAN: a full card gives expert copies back when MMQ's pool needs room
741
+ + ::basalt::g_ajean_oom_hook = [this](uint64_t bytes) {
742
+ + const uint64_t freed = demote(bytes, nullptr);
743
+ + basalt::log::warn("basalt inkling2", "card full: %.0f MiB of expert copies back to RAM", (double) freed / (double) kMiB);
744
+ + return freed;
745
+ + };
746
+ if (elastic_) { // the caches back only their base yet: the RAM experts come back while the card has room
747
+ size_t fa = 0, fb = 0, tt = 0;
748
+ cudaMemGetInfo(&fa, &tt);
749
+ diff --git a/src/models/inkling2/session.cpp b/src/models/inkling2/session.cpp
750
+ index 97e8ea6cf..47c8d11cb 100644
751
+ --- a/src/models/inkling2/session.cpp
752
+ +++ b/src/models/inkling2/session.cpp
753
+ @@ -922,15 +922,38 @@ private:
754
+ const uint64_t key = ((uint64_t) full_keys << 16) | ((uint64_t) head << 8) | (uint64_t) rows;
755
+ auto it = graphs_.find(key);
756
+ if (it != graphs_.end()) return it->second.launch(stream_, err);
757
+ - if (direct_.insert(key).second) {
758
+ + if (direct_.insert(key).second || nograph_.count(key)) {
759
+ body(rows, head, full_keys);
760
+ return true;
761
+ }
762
+ core::CapturedGraph g;
763
+ if (!g.begin(stream_, err)) return false;
764
+ body(rows, head, full_keys);
765
+ - if (!g.end(stream_, err)) return false;
766
+ - return graphs_.emplace(key, std::move(g)).first->second.launch(stream_, err);
767
+ + if (g.end(stream_, err)) return graphs_.emplace(key, std::move(g)).first->second.launch(stream_, err);
768
+ + // AJEAN: a card kept nearly full of experts can lack the memory to instantiate a new shape's graph (the engine
769
+ + // exited on it): give 256 MiB of expert copies back to RAM and capture again; failing that, run this shape direct
770
+ + for (int attempt = 0; attempt < 2; ++attempt) {
771
+ + cudaGetLastError();
772
+ + const uint64_t freed = m_.demote(256ull << 20, stream_);
773
+ + basalt::log::warn("basalt inkling2", "graph of %d rows: %s; %.0f MiB of expert copies back to RAM, capturing again", rows,
774
+ + err.c_str(), (double) freed / (double) (1 << 20));
775
+ + core::CapturedGraph h;
776
+ + std::string e2;
777
+ + if (!h.begin(stream_, e2)) break;
778
+ + body(rows, head, full_keys);
779
+ + if (h.end(stream_, e2)) {
780
+ + err.clear();
781
+ + return graphs_.emplace(key, std::move(h)).first->second.launch(stream_, err);
782
+ + }
783
+ + err = e2;
784
+ + if (freed == 0) break;
785
+ + }
786
+ + cudaGetLastError();
787
+ + basalt::log::warn("basalt inkling2", "graph of %d rows: %s; this shape runs without a graph", rows, err.c_str());
788
+ + err.clear();
789
+ + nograph_.insert(key);
790
+ + body(rows, head, full_keys);
791
+ + return true;
792
+ }
793
+
794
+ // Launches only: the visits, then the head. Each kernel may start while the one before it finishes (it waits for it
795
+ @@ -1090,6 +1113,7 @@ private:
796
+ DsparkHook dspark_; // DSPARK HOOK
797
+ Walk walk_;
798
+ std::map<uint64_t, core::CapturedGraph> graphs_; // by window shape: rows, head rows, the full visits' launch bound
799
+ + std::set<uint64_t> nograph_; // AJEAN: shapes whose graph could not be instantiated
800
+ std::set<uint64_t> direct_; // the shapes whose first window has run
801
+ const model::BatchView* view_ = nullptr; // the batch window in flight, while batch_forward runs it
802
+ float* logits_ = nullptr; // the last window's head rows (row_logprobs, copy_logits, resample_row)
803
+ diff --git a/src/prefill/mmq/mmq_host.cu b/src/prefill/mmq/mmq_host.cu
804
+ index be8cd273f..444c751eb 100644
805
+ --- a/src/prefill/mmq/mmq_host.cu
806
+ +++ b/src/prefill/mmq/mmq_host.cu
807
+ @@ -1,3 +1,4 @@
808
+ +#include <functional>
809
+ // The host side of the MMQ kernels: error reporting, the properties of each device and the cache of scratch buffers
810
+ // that the stream-k fixup of a launch takes from, and the explicit load of a kernel.
811
+ #include "mmq_common.cuh"
812
+ @@ -63,6 +64,12 @@ const ggml_cuda_device_info & ggml_cuda_info() {
813
+ return info;
814
+ }
815
+
816
+ +namespace basalt {
817
+ +// AJEAN: called when a pool allocation finds the card full (a model that keeps the card full of expert copies frees
818
+ +// some); returns the bytes it gave back. Empty: no retry.
819
+ +std::function<uint64_t(uint64_t)> g_ajean_oom_hook;
820
+ +} // namespace basalt
821
+ +
822
+ namespace {
823
+ // Buffers are kept and reused: MMQ asks for the same few sizes every launch (its stream-k fixup tiles).
824
+ struct CachingPool : ggml_cuda_pool {
825
+ @@ -74,7 +81,13 @@ struct CachingPool : ggml_cuda_pool {
826
+ for (auto & b : bufs)
827
+ if (!b.used && b.size >= size) { b.used = true; *actual_size = b.size; return b.p; }
828
+ void * p = nullptr;
829
+ - CUDA_CHECK(cudaMalloc(&p, size));
830
+ + cudaError_t e = cudaMalloc(&p, size);
831
+ + if (e != cudaSuccess && basalt::g_ajean_oom_hook) { // AJEAN
832
+ + cudaGetLastError();
833
+ + basalt::g_ajean_oom_hook((uint64_t) size + (64ull << 20));
834
+ + e = cudaMalloc(&p, size);
835
+ + }
836
+ + if (e != cudaSuccess) CUDA_CHECK(e);
837
+ bufs.push_back({p, size, true});
838
+ *actual_size = size;
839
+ return p;
840
+ --
841
+ 2.43.0
842
+
843
+
844
+ From 7fe1b04d802bbfdb7866e4fd653dc557304f090a Mon Sep 17 00:00:00 2001
845
+ From: nathaninline <mail@nathaninline.com>
846
+ Date: Sun, 22 Nov 2026 19:34:37 +0000
847
+ Subject: [PATCH 5/5] AJEAN: inkling2_requant.py in English
848
+
849
+ ---
850
+ tools/convert/inkling2_requant.py | 280 +++++++++++++++---------------
851
+ 1 file changed, 140 insertions(+), 140 deletions(-)
852
+
853
+ diff --git a/tools/convert/inkling2_requant.py b/tools/convert/inkling2_requant.py
854
+ index 4e63584bc..df6e42d5b 100644
855
+ --- a/tools/convert/inkling2_requant.py
856
+ +++ b/tools/convert/inkling2_requant.py
857
+ @@ -1,140 +1,140 @@
858
+ -"""AJEAN : réécrit un pack inkling2 en passant les experts Q8_0 (couches 20 à 23 du pack officiel) en NVFP4.
859
+ -
860
+ - python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
861
+ -
862
+ -Chaque matrice (gate, up, down) d'un expert Q8_0 est déquantifiée puis arrondie en NVFP4 comme le fait
863
+ -hy4flash_bf16.py (échelle de tenseur amax / (6 x 448), échelle UE4M3 par 16 valeurs choisie au moindre carré).
864
+ -gate et up partagent leur échelle de tenseur, comme dans les couches NVFP4 du pack officiel ({s_gu, s_gu, s_d, 0}).
865
+ -Les autres sections sont copiées telles quelles. Gain : ~1,9 Gio d'experts en moins sur la carte.
866
+ -"""
867
+ -from __future__ import annotations
868
+ -
869
+ -import argparse
870
+ -import json
871
+ -import multiprocessing
872
+ -import os
873
+ -import pathlib
874
+ -import sys
875
+ -import time
876
+ -
877
+ -import numpy as np
878
+ -
879
+ -HERE = pathlib.Path(__file__).resolve().parent
880
+ -sys.path.insert(0, str(HERE))
881
+ -sys.path.insert(0, str(HERE.parent))
882
+ -import checkpoint as C # noqa: E402
883
+ -import checkpoint_qwen35 as Q # noqa: E402
884
+ -import model_sections as S # noqa: E402
885
+ -from model_file import ModelFile, ModelWriter # noqa: E402
886
+ -
887
+ -H, FF, NE = 2304, 1152, 128
888
+ -Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
889
+ -Q8_ROW_FF = FF // 32 * 34
890
+ -Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
891
+ -F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
892
+ -
893
+ -
894
+ -def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
895
+ - b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
896
+ - d = b[:, :2].copy().view(np.float16).astype(np.float32)
897
+ - q = b[:, 2:].view(np.int8).astype(np.float32)
898
+ - return (q * d).reshape(rows, cols)
899
+ -
900
+ -
901
+ -def _job(args):
902
+ - path, off, e0, n = args
903
+ - with open(path, "rb") as f:
904
+ - f.seek(off + e0 * Q8_BLOB)
905
+ - raw = f.read(n * Q8_BLOB)
906
+ - out = []
907
+ - for e in range(n):
908
+ - b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
909
+ - g = q8_values(b[:FF * Q8_ROW_H], FF, H)
910
+ - u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
911
+ - d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
912
+ - gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
913
+ - gs_d = Q.fp4q_global(float(np.abs(d).max()))
914
+ - err = 0.0
915
+ - for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
916
+ - codes, sc = Q.fp4q_rows(x, gs)
917
+ - out.append(C.nvfp4_rows(codes, sc).tobytes())
918
+ - v = np.empty(x.shape, np.float32)
919
+ - v[:, 0::2] = C.E2M1[codes & 15]
920
+ - v[:, 1::2] = C.E2M1[codes >> 4]
921
+ - v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
922
+ - err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
923
+ - out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
924
+ - return b"".join(out), err / 3
925
+ -
926
+ -
927
+ -def main() -> None:
928
+ - ap = argparse.ArgumentParser()
929
+ - ap.add_argument("--pack", required=True)
930
+ - ap.add_argument("--out", required=True)
931
+ - ap.add_argument("--layers", default="20,21,22,23")
932
+ - ap.add_argument("--workers", type=int, default=12)
933
+ - a = ap.parse_args()
934
+ - if os.path.exists(a.out):
935
+ - sys.exit(f"{a.out} existe déjà")
936
+ - want = {int(x) for x in a.layers.split(",")}
937
+ - m = ModelFile(a.pack)
938
+ - lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
939
+ - rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
940
+ - eoff, _ = m.section("experts")
941
+ - new, off = [], 0
942
+ - for l, gu, dt, o, blob in rows:
943
+ - if l in want:
944
+ - if gu != 8 or blob != Q8_BLOB:
945
+ - sys.exit(f"couche {l} : type {gu} blob {blob}, attendu Q8_0 {Q8_BLOB}")
946
+ - new.append((l, 40, 40, off, F4_BLOB))
947
+ - off += F4_BLOB * NE
948
+ - else:
949
+ - new.append((l, gu, dt, off, blob))
950
+ - off += blob * NE
951
+ - total = off
952
+ - t0 = time.time()
953
+ - errs = []
954
+ -
955
+ - def experts_chunks(pool):
956
+ - for (l, gu, dt, o, blob), nl in zip(rows, new):
957
+ - if l not in want:
958
+ - left, at = blob * NE, eoff + o
959
+ - with open(a.pack, "rb") as f:
960
+ - f.seek(at)
961
+ - while left:
962
+ - b = f.read(min(64 << 20, left))
963
+ - left -= len(b)
964
+ - yield b
965
+ - continue
966
+ - jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
967
+ - for b, err in pool.imap(_job, jobs):
968
+ - errs.append(err)
969
+ - yield b
970
+ - print(f"couche {l} : NVFP4, erreur relative moyenne {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
971
+ -
972
+ - w = ModelWriter(a.out)
973
+ - with multiprocessing.Pool(a.workers) as pool:
974
+ - for name in m.names():
975
+ - so, sz = m.section(name)
976
+ - if name == "experts":
977
+ - n = w.add_chunks(name, experts_chunks(pool))
978
+ - if n != total:
979
+ - sys.exit(f"experts : {n} octets, attendu {total}")
980
+ - elif name == "experts.layout":
981
+ - w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
982
+ - elif name == "meta":
983
+ - j = json.loads(m.read("meta"))
984
+ - j["name"] = j.get("name", "Inkling 2 Mini")
985
+ - j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
986
+ - "layers_nvfp4": sorted(want),
987
+ - "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
988
+ - "UE4M3 per 16 at least squared error)"}
989
+ - w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
990
+ - else:
991
+ - w.add_file(name, a.pack, so, sz)
992
+ - w.close()
993
+ - print(f"écrit {a.out} : experts {total / 2**30:.2f} Gio (avant {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
994
+ -
995
+ -
996
+ -if __name__ == "__main__":
997
+ - main()
998
+ +"""Rewrite an inkling2 pack with its Q8_0 routed experts (layers 20 to 23 of the official pack) as NVFP4.
999
+ +
1000
+ + python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
1001
+ +
1002
+ +Each matrix (gate, up, down) of a Q8_0 expert is dequantized, then rounded to NVFP4 the way hy4flash_bf16.py does it
1003
+ +(tensor scale amax / (6 x 448), one UE4M3 scale per 16 values picked at least squared error). gate and up share their
1004
+ +tensor scale, as in the official pack's NVFP4 layers ({s_gu, s_gu, s_d, 0}). Every other section is copied as is.
1005
+ +Gain: about 1.9 GiB less of experts on the card.
1006
+ +"""
1007
+ +from __future__ import annotations
1008
+ +
1009
+ +import argparse
1010
+ +import json
1011
+ +import multiprocessing
1012
+ +import os
1013
+ +import pathlib
1014
+ +import sys
1015
+ +import time
1016
+ +
1017
+ +import numpy as np
1018
+ +
1019
+ +HERE = pathlib.Path(__file__).resolve().parent
1020
+ +sys.path.insert(0, str(HERE))
1021
+ +sys.path.insert(0, str(HERE.parent))
1022
+ +import checkpoint as C # noqa: E402
1023
+ +import checkpoint_qwen35 as Q # noqa: E402
1024
+ +import model_sections as S # noqa: E402
1025
+ +from model_file import ModelFile, ModelWriter # noqa: E402
1026
+ +
1027
+ +H, FF, NE = 2304, 1152, 128
1028
+ +Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
1029
+ +Q8_ROW_FF = FF // 32 * 34
1030
+ +Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
1031
+ +F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
1032
+ +
1033
+ +
1034
+ +def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
1035
+ + b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
1036
+ + d = b[:, :2].copy().view(np.float16).astype(np.float32)
1037
+ + q = b[:, 2:].view(np.int8).astype(np.float32)
1038
+ + return (q * d).reshape(rows, cols)
1039
+ +
1040
+ +
1041
+ +def _job(args):
1042
+ + path, off, e0, n = args
1043
+ + with open(path, "rb") as f:
1044
+ + f.seek(off + e0 * Q8_BLOB)
1045
+ + raw = f.read(n * Q8_BLOB)
1046
+ + out = []
1047
+ + for e in range(n):
1048
+ + b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
1049
+ + g = q8_values(b[:FF * Q8_ROW_H], FF, H)
1050
+ + u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
1051
+ + d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
1052
+ + gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
1053
+ + gs_d = Q.fp4q_global(float(np.abs(d).max()))
1054
+ + err = 0.0
1055
+ + for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
1056
+ + codes, sc = Q.fp4q_rows(x, gs)
1057
+ + out.append(C.nvfp4_rows(codes, sc).tobytes())
1058
+ + v = np.empty(x.shape, np.float32)
1059
+ + v[:, 0::2] = C.E2M1[codes & 15]
1060
+ + v[:, 1::2] = C.E2M1[codes >> 4]
1061
+ + v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
1062
+ + err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
1063
+ + out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
1064
+ + return b"".join(out), err / 3
1065
+ +
1066
+ +
1067
+ +def main() -> None:
1068
+ + ap = argparse.ArgumentParser()
1069
+ + ap.add_argument("--pack", required=True)
1070
+ + ap.add_argument("--out", required=True)
1071
+ + ap.add_argument("--layers", default="20,21,22,23")
1072
+ + ap.add_argument("--workers", type=int, default=12)
1073
+ + a = ap.parse_args()
1074
+ + if os.path.exists(a.out):
1075
+ + sys.exit(f"{a.out} already exists")
1076
+ + want = {int(x) for x in a.layers.split(",")}
1077
+ + m = ModelFile(a.pack)
1078
+ + lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
1079
+ + rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
1080
+ + eoff, _ = m.section("experts")
1081
+ + new, off = [], 0
1082
+ + for l, gu, dt, o, blob in rows:
1083
+ + if l in want:
1084
+ + if gu != 8 or blob != Q8_BLOB:
1085
+ + sys.exit(f"layer {l}: type {gu} blob {blob}, expected Q8_0 {Q8_BLOB}")
1086
+ + new.append((l, 40, 40, off, F4_BLOB))
1087
+ + off += F4_BLOB * NE
1088
+ + else:
1089
+ + new.append((l, gu, dt, off, blob))
1090
+ + off += blob * NE
1091
+ + total = off
1092
+ + t0 = time.time()
1093
+ + errs = []
1094
+ +
1095
+ + def experts_chunks(pool):
1096
+ + for (l, gu, dt, o, blob), nl in zip(rows, new):
1097
+ + if l not in want:
1098
+ + left, at = blob * NE, eoff + o
1099
+ + with open(a.pack, "rb") as f:
1100
+ + f.seek(at)
1101
+ + while left:
1102
+ + b = f.read(min(64 << 20, left))
1103
+ + left -= len(b)
1104
+ + yield b
1105
+ + continue
1106
+ + jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
1107
+ + for b, err in pool.imap(_job, jobs):
1108
+ + errs.append(err)
1109
+ + yield b
1110
+ + print(f"layer {l}: NVFP4, mean relative squared error {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
1111
+ +
1112
+ + w = ModelWriter(a.out)
1113
+ + with multiprocessing.Pool(a.workers) as pool:
1114
+ + for name in m.names():
1115
+ + so, sz = m.section(name)
1116
+ + if name == "experts":
1117
+ + n = w.add_chunks(name, experts_chunks(pool))
1118
+ + if n != total:
1119
+ + sys.exit(f"experts: {n} bytes, expected {total}")
1120
+ + elif name == "experts.layout":
1121
+ + w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
1122
+ + elif name == "meta":
1123
+ + j = json.loads(m.read("meta"))
1124
+ + j["name"] = j.get("name", "Inkling 2 Mini")
1125
+ + j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
1126
+ + "layers_nvfp4": sorted(want),
1127
+ + "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
1128
+ + "UE4M3 per 16 at least squared error)"}
1129
+ + w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
1130
+ + else:
1131
+ + w.add_file(name, a.pack, so, sz)
1132
+ + w.close()
1133
+ + print(f"wrote {a.out}: experts {total / 2**30:.2f} GiB (was {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
1134
+ +
1135
+ +
1136
+ +if __name__ == "__main__":
1137
+ + main()
1138
+ --
1139
+ 2.43.0
1140
+
tools/inkling2_requant.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rewrite an inkling2 pack with its Q8_0 routed experts (layers 20 to 23 of the official pack) as NVFP4.
2
+
3
+ python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
4
+
5
+ Each matrix (gate, up, down) of a Q8_0 expert is dequantized, then rounded to NVFP4 the way hy4flash_bf16.py does it
6
+ (tensor scale amax / (6 x 448), one UE4M3 scale per 16 values picked at least squared error). gate and up share their
7
+ tensor scale, as in the official pack's NVFP4 layers ({s_gu, s_gu, s_d, 0}). Every other section is copied as is.
8
+ Gain: about 1.9 GiB less of experts on the card.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import multiprocessing
15
+ import os
16
+ import pathlib
17
+ import sys
18
+ import time
19
+
20
+ import numpy as np
21
+
22
+ HERE = pathlib.Path(__file__).resolve().parent
23
+ sys.path.insert(0, str(HERE))
24
+ sys.path.insert(0, str(HERE.parent))
25
+ import checkpoint as C # noqa: E402
26
+ import checkpoint_qwen35 as Q # noqa: E402
27
+ import model_sections as S # noqa: E402
28
+ from model_file import ModelFile, ModelWriter # noqa: E402
29
+
30
+ H, FF, NE = 2304, 1152, 128
31
+ Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
32
+ Q8_ROW_FF = FF // 32 * 34
33
+ Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
34
+ F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
35
+
36
+
37
+ def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
38
+ b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
39
+ d = b[:, :2].copy().view(np.float16).astype(np.float32)
40
+ q = b[:, 2:].view(np.int8).astype(np.float32)
41
+ return (q * d).reshape(rows, cols)
42
+
43
+
44
+ def _job(args):
45
+ path, off, e0, n = args
46
+ with open(path, "rb") as f:
47
+ f.seek(off + e0 * Q8_BLOB)
48
+ raw = f.read(n * Q8_BLOB)
49
+ out = []
50
+ for e in range(n):
51
+ b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
52
+ g = q8_values(b[:FF * Q8_ROW_H], FF, H)
53
+ u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
54
+ d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
55
+ gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
56
+ gs_d = Q.fp4q_global(float(np.abs(d).max()))
57
+ err = 0.0
58
+ for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
59
+ codes, sc = Q.fp4q_rows(x, gs)
60
+ out.append(C.nvfp4_rows(codes, sc).tobytes())
61
+ v = np.empty(x.shape, np.float32)
62
+ v[:, 0::2] = C.E2M1[codes & 15]
63
+ v[:, 1::2] = C.E2M1[codes >> 4]
64
+ v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
65
+ err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
66
+ out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
67
+ return b"".join(out), err / 3
68
+
69
+
70
+ def main() -> None:
71
+ ap = argparse.ArgumentParser()
72
+ ap.add_argument("--pack", required=True)
73
+ ap.add_argument("--out", required=True)
74
+ ap.add_argument("--layers", default="20,21,22,23")
75
+ ap.add_argument("--workers", type=int, default=12)
76
+ a = ap.parse_args()
77
+ if os.path.exists(a.out):
78
+ sys.exit(f"{a.out} already exists")
79
+ want = {int(x) for x in a.layers.split(",")}
80
+ m = ModelFile(a.pack)
81
+ lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
82
+ rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
83
+ eoff, _ = m.section("experts")
84
+ new, off = [], 0
85
+ for l, gu, dt, o, blob in rows:
86
+ if l in want:
87
+ if gu != 8 or blob != Q8_BLOB:
88
+ sys.exit(f"layer {l}: type {gu} blob {blob}, expected Q8_0 {Q8_BLOB}")
89
+ new.append((l, 40, 40, off, F4_BLOB))
90
+ off += F4_BLOB * NE
91
+ else:
92
+ new.append((l, gu, dt, off, blob))
93
+ off += blob * NE
94
+ total = off
95
+ t0 = time.time()
96
+ errs = []
97
+
98
+ def experts_chunks(pool):
99
+ for (l, gu, dt, o, blob), nl in zip(rows, new):
100
+ if l not in want:
101
+ left, at = blob * NE, eoff + o
102
+ with open(a.pack, "rb") as f:
103
+ f.seek(at)
104
+ while left:
105
+ b = f.read(min(64 << 20, left))
106
+ left -= len(b)
107
+ yield b
108
+ continue
109
+ jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
110
+ for b, err in pool.imap(_job, jobs):
111
+ errs.append(err)
112
+ yield b
113
+ print(f"layer {l}: NVFP4, mean relative squared error {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
114
+
115
+ w = ModelWriter(a.out)
116
+ with multiprocessing.Pool(a.workers) as pool:
117
+ for name in m.names():
118
+ so, sz = m.section(name)
119
+ if name == "experts":
120
+ n = w.add_chunks(name, experts_chunks(pool))
121
+ if n != total:
122
+ sys.exit(f"experts: {n} bytes, expected {total}")
123
+ elif name == "experts.layout":
124
+ w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
125
+ elif name == "meta":
126
+ j = json.loads(m.read("meta"))
127
+ j["name"] = j.get("name", "Inkling 2 Mini")
128
+ j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
129
+ "layers_nvfp4": sorted(want),
130
+ "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
131
+ "UE4M3 per 16 at least squared error)"}
132
+ w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
133
+ else:
134
+ w.add_file(name, a.pack, so, sz)
135
+ w.close()
136
+ print(f"wrote {a.out}: experts {total / 2**30:.2f} GiB (was {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()