Add Inkling-2-Mini model card, tokenizer, scripts, and quality logs
Browse filesFiles changed (19)
- .gitattributes+1
- LICENSEAdded+202
- NOTICEAdded+11
- README.mdAdded+133
- checksums.sha256Added+3
- inkling2_tokenizer.binAdded+3
- quality/check_q8.logAdded+28
- quality/logits_oracle.binAdded+3
- quality/logits_q4.binAdded+3
- quality/logits_q8.binAdded+3
- scripts/compare_inkling_logits.pyAdded+53
- scripts/export_hf_q8.pyAdded+539
- scripts/export_inkling.pyAdded+267
- source/chat_template.jinjaAdded+137
- source/config.jsonAdded+122
- source/generation_config.jsonAdded+6
- source/special_tokens_map.jsonAdded+21
- source/tokenizer.jsonAdded+3
- source/tokenizer_config.jsonAdded+548
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsource/tokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011Inkling-2-MiniCopyright Thinking MachinesLicensed under the Apache License, Version 2.0.
This repository contains text-only quantized derivative weights (INK2JSON Q4 and Q8), anumallama-format tokenizer, exporter scripts and validation logits produced fromthinkingmachines/Inkling-2-Mini at revision c9d028302cd0f035fdf8e7e91f089a4ce94d2195.
The numallama engine and export tooling are by the numallama project(https://github.com/miloserdev/numallama). See LICENSE for the Apache-2.0 text.The upstream IQ4_NL GGUF used as a runtime oracle is not included or redistributed here.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133---license: apache-2.0base_model: thinkingmachines/Inkling-2-Minilibrary_name: numallamapipeline_tag: text-generationtags: - inkling - inkling2 - moe - q4 - q8 - numallama - custom-format---
# Inkling-2-Mini for numallama
Text-only quantized weights of[`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini)(source revision `c9d028302cd0f035fdf8e7e91f089a4ce94d2195`, Apache-2.0), packaged for theCPU inference engine [numallama](https://github.com/miloserdev/numallama).
This is **not** a GGUF and cannot be loaded by llama.cpp. The files use numallama's `INK2JSON`container: a JSON manifest plus memory-mappable tensor blobs. Vision, audio and MTP are notincluded.
## Files
| File | Experts | Size | Description ||---|---|---|---|| `inkling_mini_q4.ink2` | Q4 | 17.00 GB | default; source NVFP4/MXFP8 dequantized, then Q4 || `inkling_mini_q8.ink2` | Q8 | 27.71 GB | source dequantized, 8-bit experts || `inkling2_tokenizer.bin` | — | 2.8 MB | 201024-entry BPE tokenizer for numallama || `source/` | — | — | upstream config, tokenizer JSON, chat template, generation config || `scripts/` | — | — | exporter, tokenizer converter helper, logits comparison || `quality/` | — | — | oracle/Q4/Q8 logits and the validation log || `checksums.sha256` | — | — | SHA-256 of the containers and tokenizer |
Matrices outside MoE are Q8 in both containers. Expert quantization differs: layers 0-19 in thesource are NVFP4 and 20-23 MXFP8; the exporter dequantizes them and writes Q4 or Q8 blocks.
## Model
Inkling-2-Mini is a 26.4B-parameter model with 3.4B active parameters (5.4B effective with thethree loop passes), 24 physical layers, hidden size 2304, 24/8 attention heads, head_dim 128,128 experts with top-8 routing, a 1024-token sliding window on 20 layers and full attention onlayers 5/11/17/23. The loop core is layers 6..17, run three times with separate KV/conv slots(48 slots). Vocabulary: 201024 padded / 200058 unpadded.
## Usage
Build numallama (the engine has no external Python/CUDA dependencies at runtime):
```bashgit clone https://github.com/miloserdev/numallamacd numallamamake```
Download the container and tokenizer, then generate:
```bashhf download miloserdev/Inkling-2-Mini-numallama inkling_mini_q4.ink2 --local-dir .hf download miloserdev/Inkling-2-Mini-numallama inkling2_tokenizer.bin --local-dir .
./runq inkling_mini_q4.ink2 -z inkling2_tokenizer.bin \ -m generate -i "The capital of France is" -n 24 -c 128 -t 0```
Chat and the OpenAI-compatible server:
```bash./runq inkling_mini_q4.ink2 -z inkling2_tokenizer.bin \ -m chat -i "What is the capital of France?" -n 128 -t 0
./runq inkling_mini_q4.ink2 -z inkling2_tokenizer.bin \ -m server -P 8080 -c 8192```
The server supports `/v1/chat/completions` (streaming and non-streaming), `reasoning_content`,stop strings, `min_p`, presence/frequency penalties, seeds and `include_usage`. It keeps onemulti-turn session cache. It handles one request at a time; run replicas behind`scripts/replica_router.py` for concurrency. The forward is currently single-threaded andtoken-by-token (~0.79 s/token on the reference machine); `-T` and `-J` do not apply. Promptsabove `INKLING_MAX_PROMPT` (default 4096 tokens) are rejected with a clear 400.
## Quality
Oracle: official IQ4_NL GGUF run by upstream llama.cpp (`inkling2_loop`) on"The capital of France is". Candidate logits come from `tests/check_inkling`; reproduce with`python3 scripts/compare_inkling_logits.py quality/logits_oracle.bin quality/logits_q4.bin`.
| Variant | Top-1 | Logit | KL(oracle) | Top-10 overlap | Correlation | Max logit diff ||---|---|---|---|---|---|---|| Q4 experts | 152717 (` Paris`) | 27.3686 | 0.0594 | 10/10 | 0.97889 | 5.37 || Q8 experts | 152717 (` Paris`) | 27.4252 | 0.0535 | 10/10 | 0.98145 | 5.08 |
Q4 vs Q8: KL 0.0083, correlation 0.99683, top-10 10/10. Greedy Q4 and Q8 continuations agreethrough ` Paris.` and the following multiple-choice options; their tails differ, as does theIQ4_NL oracle continuation after ` Paris.` (expected greedy divergence under differentquantization). Most of the remaining oracle gap is implementation/format and the oracle's own4-bit quantization, not Q4 expert storage.
## Reproduce the export
The upstream safetensors are not redistributed here. With `config.json` and`model-00001-of-00001.safetensors` from the base model:
```bashpython3 scripts/export_inkling.py model-00001-of-00001.safetensors inkling_mini_q4.ink2python3 scripts/export_inkling.py model-00001-of-00001.safetensors inkling_mini_q8.ink2 --experts q8```
The exporter dequantizes NVFP4/MXFP8 experts to dense and re-quantizes them; Q8 matrices useper-64 scales. Container names omit the `model.llm.` prefix and the loader repacks into theengine's 4-row SDOT layout at load time.
## Limitations
- numallama's Inkling forward is a new text-only port. It matches the IQ4_NL oracle's top-1 and top-10 on the validation prompt, but long-form continuations will differ under greedy decoding.- No vision, audio, MTP, tool calling in the Inkling server, or continuous batching for this architecture.- Single-request server; `-T` / `-J` are not implemented for this path.- The engine and these derived weights are provided without warranty; verify behavior for your use case.
## License and attribution
The base model and architecture are by Thinking Machines, licensed Apache-2.0. This repositorycontains derivative quantized weights and numallama-format tooling. See `LICENSE` (Apache-2.0text), `NOTICE`, the upstream model card and the source revision above. The upstream IQ4_NL GGUFis a separate artifact and is not redistributed here.12333d7cb07fa1cbd8fde11e8ffa22ae7d60e5fa97c1a9990abea57d011f09d95ce inkling_mini_q4.ink26c3372de1bec96f8e11a0228d0b72f29cc8e4571a063ba0e85c3854ae9815238 inkling_mini_q8.ink2ffa341de10aa7762be207f1cdff70f494641a859875afc6c51eb707905248f3b inkling2_tokenizer.bin123version https://git-lfs.github.com/spec/v1oid sha256:ffa341de10aa7762be207f1cdff70f494641a859875afc6c51eb707905248f3bsize 288415912345678910111213141516171819202122232425262728layers 24 slots 48 dim 2304 inter 1152 heads 24/8 hd 128 vocab 201024 experts 128/8loop 6..18 x3 rank 64 rel 16/1024 window 1024 conv 4 res 6 local 007df7dftensors 694embed.weight dtype 1 dims 201024 2304 bytes 492106752layers.0.mlp.experts.w13 dtype 1 dims 128 2304 2304 bytes 721944576layers.23.mlp.experts.w2 dtype 1 dims 128 2304 1152 bytes 360972288layers.6.controllers.attn.down_weight dtype 1 dims 64 4608 bytes 313344norm.weight dtype 0 dims 2304 bytes 9216state ctx 128 slots 48 kv 12.6 MB conv 3833.9 KB slotmap 0 23 6 17 6M1 head top-1 id 178515 logit 3.264514M2 primitives: sconv=3.0 clip=1.0 mix[0]=0.3651M2 attention: score 2.2071 w 0.9009 out 2.7027 3.6035 (expect 2.7027 3.6035)M2 MoE layer0: finite=1 min -0.0000 max 0.0000 mean 0.0000M2 layer0: finite=1 min -10.0202 max 11.7704 mean -0.0149 blocks 1M3 layer5 full: finite=1 min -114.4969 max 116.5111 mean -0.0785INKLING full top-1 id 152717 logit 27.425213 (oracle 152717 / 27.307991) top 0 id 152717 logit 27.425213 top 1 id 149881 logit 25.828474 top 2 id 149876 logit 25.715889 top 3 id 167815 logit 25.613136 top 4 id 154706 logit 25.345329 top 5 id 149878 logit 25.296017 top 6 id 151107 logit 25.205133 top 7 id 25 logit 25.194050 top 8 id 145038 logit 24.810875 top 9 id 151015 logit 24.663324Q8 pack 3072x2304 max|diff| 0.00000Q4 expert pack skipped (experts dtype 1)123version https://git-lfs.github.com/spec/v1oid sha256:a1ba038baad662f8037eba14856de000c657ebe41973ec62d4521829fa15a176size 800232123version https://git-lfs.github.com/spec/v1oid sha256:8fdac78229f6c5693422dbbfd0ac0bac6952156d39f5135f63351411b6960749size 800232123version https://git-lfs.github.com/spec/v1oid sha256:4fedac9179a2e82b1da2579228562e2bf76eb5d76c66122f85ed4fcc2a989f96size 8002321234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/usr/bin/env python3"""Compare Inkling-2-Mini logits against the llama.cpp oracle.
usage: compare_inkling_logits.py oracle.bin candidate.bin [candidate.bin ...]
Each file is a flat float32 array over the unpadded vocabulary (200058 values), as written bytests/check_inkling (`logits_ours.bin`) or the oracle runner. Prints top-1, KL(oracle||cand),top-10 overlap, Pearson correlation and the largest logit difference; additionally the KL betweencandidate pairs, which separates the quantization loss from the forward/format difference."""import sysimport numpy as np
def softmax(x): x = x.astype(np.float64) x -= x.max() e = np.exp(x) return e / e.sum()
def kl(p, q): return float(np.sum(p * np.log((p + 1e-30) / (q + 1e-30))))
def main(): if len(sys.argv) < 3: raise SystemExit(__doc__) files = sys.argv[1:] logits = [np.fromfile(f, dtype=np.float32) for f in files] n = min(map(len, logits)) logits = [x[:n] for x in logits] base = logits[0] pb = softmax(base) tb = base.argsort()[-10:][::-1] print(f"vocab {n} oracle top1 {tb[0]} ({base[tb[0]]:.6f})") for name, x in zip(files[1:], logits[1:]): px = softmax(x) tx = x.argsort()[-10:][::-1] print(f"{name}: top1 {tx[0]} ({x[tx[0]]:.6f}) KL {kl(pb, px):.6f} " f"top10 {len(set(tb) & set(tx))}/10 corr {np.corrcoef(base, x)[0, 1]:.5f} " f"max|d| {np.max(np.abs(base - x)):.4f}") if len(logits) > 2: for i in range(1, len(logits)): for j in range(i + 1, len(logits)): a, b = softmax(logits[i]), softmax(logits[j]) print(f"{files[i]} vs {files[j]}: KL {kl(a, b):.6f} " f"corr {np.corrcoef(logits[i], logits[j])[0, 1]:.5f} " f"max|d| {np.max(np.abs(logits[i] - logits[j])):.4f}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539"""Export a Hugging Face Llama 3.x checkpoint (model.safetensors + config.json) to thellama3.c int8 (version 2) format, using only numpy (no torch / safetensors needed).
python3 export_hf_q8.py /path/to/Llama-3.2-1B-Instruct llama32_1b_instruct_q80.bin
Header extension (inside the 256-byte v2 header, after group_size, all little-endian): float rope_theta, float rope_factor, float low_freq_factor, float high_freq_factor, int original_max_position_embeddings (factor == 0 means "no llama3 rope scaling") int arch (0 = llama3, 1 = qwen2), float norm_eps, int qkv_bias, int special_start (first special token id), int bos_id, int eos_id int q4_mask: bit k set = matrix kind k (0 wq, 1 wk, 2 wv, 3 wo, 4 w1, 5 w2, 6 w3) is stored as Q4 int head_dim, n_experts, n_active, moe_hidden, qk_norm, norm_topk (Qwen3 / Qwen3-MoE; 0 = n/a) int q4_format: 1 = asymmetric groups of 32 with fp16 scale + min (0 / absent: the old symmetric Q4)fp32 section: attention norms, ffn norms, final norm, [qkv biases], [q_norm (L, head_dim), k_norm (L, head_dim)]MoE layers: router wg (L, n_experts, dim) in Q8 after wo; w1/w3 (L, n_experts * moe_hidden, dim) andw2 (L, n_experts * dim, moe_hidden), every expert a contiguous block of rows.If qkv_bias, the fp32 section continues after the final norm with bq (L, dim), bk (L, kv_dim), bv (L, kv_dim).Q8 tensors: int8 values, then fp32 scales per `gs` values. Q4 tensors (q4_format 1): groups of 32values u in 0..15 packed in 16 bytes (byte k = u[k] in the low nibble, u[k+16] in the high nibble), thenper group [s, m] as two fp16 (value = s * u + m). Embedding / classifier are always Q8.
python3 export_hf_q8.py <hf dir> <out.bin> [gs] [--q4 [kinds]] kinds e.g. wq,wk,wo,w1,w3 (default all)Supported: LlamaForCausalLM (Llama 3.x), Qwen2ForCausalLM (Qwen2.5), Qwen3ForCausalLM, Qwen3MoeForCausalLM."""import jsonimport osimport structimport sys
import numpy as np
def load_safetensors(path): """returns {name: np.ndarray(float32)} lazily converted from bf16/f16/f32""" with open(path, "rb") as f: n = struct.unpack("<Q", f.read(8))[0] header = json.loads(f.read(n)) base = 8 + n raw = np.memmap(path, dtype=np.uint8, mode="r") tensors = {} for name, info in header.items(): if name == "__metadata__": continue a, b = info["data_offsets"] buf = raw[base + a : base + b] dt = info["dtype"] if dt == "BF16": arr = (buf.view(np.uint16).astype(np.uint32) << 16).view(np.float32) elif dt == "F16": arr = buf.view(np.float16).astype(np.float32) elif dt == "F32": arr = np.array(buf.view(np.float32)) else: raise ValueError(f"unsupported dtype {dt} for {name}") tensors[name] = arr.reshape(info["shape"]) return tensors
def hf_to_meta_qk(w, n_heads): """undo the HF rotate-half permutation of wq/wk (or their biases) so RoPE can rotate adjacent pairs""" if w.ndim == 1: return w.reshape(n_heads, 2, -1).transpose(0, 2, 1).reshape(-1) d1, d2 = w.shape return w.reshape(n_heads, 2, d1 // n_heads // 2, d2).transpose(0, 2, 1, 3).reshape(d1, d2)
def quantize_q80(w, gs): g = w.astype(np.float32).reshape(-1, gs) scale = np.abs(g).max(axis=1) / 127.0 scale = np.where(scale > 1e-30, scale, 0.0).astype(np.float32) # all-(near-)zero groups: avoid 1/denormal inv = np.where(scale > 0, 1.0 / np.where(scale > 0, scale, 1.0), 0.0).astype(np.float32) q = np.round(g * inv[:, None]).astype(np.int8) err = np.abs(q.astype(np.float32) * scale[:, None] - g).max() return q, scale.astype(np.float32), err
KINDS = ["wq", "wk", "wv", "wo", "w1", "w2", "w3"]
def quantize_q4(w, gs=32, imp=None): """asymmetric 4-bit per group of 32: value = s * u + m, u in 0..15, s and m in fp16. For every group, candidate grids are tried (scale (15 + d) / (max - min), d in -1..1 step 0.1) and for each the integers are fixed and (s, m) solved by weighted least squares; the best fit wins. Weights: importance of the input channel (mean x^2 on calibration text) if given, otherwise |w| + rms(group) (larger weights matter more, as in llama.cpp's k-quants). Returns packed nibbles (byte k = u[k] | u[k+16] << 4) and per group [s, m] as fp16 pairs.""" rows, cols = w.reshape(-1, w.shape[-1]).shape g = w.astype(np.float32).reshape(-1, gs) if imp is None: wt = np.abs(g) + np.sqrt((g * g).mean(axis=1, keepdims=True)) else: # (cols,) or, for stacked MoE experts, (n_experts, cols): one row per block of rows imp = np.asarray(imp, np.float32).reshape(-1, cols) imp = imp / max(float(imp.mean()), 1e-30) per = rows // imp.shape[0] wt = np.repeat(imp, per, axis=0).reshape(rows, cols // gs, gs).reshape(-1, gs) wt = wt * (np.abs(g) + np.sqrt((g * g).mean(axis=1, keepdims=True))) wt = wt + 1e-12 gmin, gmax = g.min(axis=1), g.max(axis=1) rng = np.maximum(gmax - gmin, 1e-30) sw = wt.sum(axis=1) sx = (wt * g).sum(axis=1) best_err = np.full(len(g), np.inf, np.float32) best_s = rng / 15.0 best_m = gmin.copy() for d in np.arange(-1.0, 1.0001, 0.1): iscale = (15.0 + d) / rng u = np.clip(np.round((g - gmin[:, None]) * iscale[:, None]), 0, 15) sl = (wt * u).sum(axis=1) sll = (wt * u * u).sum(axis=1) slx = (wt * u * g).sum(axis=1) D = sw * sll - sl * sl ok = D > 1e-30 Ds = np.where(ok, D, 1.0) s_ = np.where(ok, (sw * slx - sl * sx) / Ds, rng / 15.0) m_ = np.where(ok, (sll * sx - sl * slx) / Ds, gmin) # the integers for the fitted (s, m), then the error inv = np.where(np.abs(s_) > 1e-30, 1.0 / np.where(np.abs(s_) > 1e-30, s_, 1.0), 0.0) u2 = np.clip(np.round((g - m_[:, None]) * inv[:, None]), 0, 15) err = (wt * (u2 * s_[:, None] + m_[:, None] - g) ** 2).sum(axis=1) better = err < best_err best_err[better] = err[better] best_s[better] = s_[better] best_m[better] = m_[better] s16 = best_s.astype(np.float16) m16 = best_m.astype(np.float16) sf, mf = s16.astype(np.float32), m16.astype(np.float32) # integers for the stored (fp16) values inv = np.where(np.abs(sf) > 1e-30, 1.0 / np.where(np.abs(sf) > 1e-30, sf, 1.0), 0.0) u = np.clip(np.round((g - mf[:, None]) * inv[:, None]), 0, 15).astype(np.uint8) packed = (u[:, :16] | (u[:, 16:] << 4)).astype(np.uint8) err = np.abs(u.astype(np.float32) * sf[:, None] + mf[:, None] - g).max() sm = np.stack([s16, m16], axis=1) # (groups, 2) fp16 return packed, sm, err
INPUT_OF = {"wq": "att_in", "wk": "att_in", "wv": "att_in", "wo": "wo_in", "w1": "ffn_in", "w3": "ffn_in", "w2": "w2_in"}_JOB = {}
def load_imatrix(path): """per-layer input-channel importance (mean x^2 on calibration text): a .imx file written by `runq <q8 model> -m imatrix -i data/calibration.txt -o stats.imx`, or an .npz from calibrate.py. MoE: ffn_in / w2_in are (n_experts, channels), one row per expert; experts that saw no calibration token get the mean over the other experts of the layer.""" if not path.endswith(".imx"): z = np.load(path) return {k: z[k] for k in z.files} raw = open(path, "rb").read() magic, L, dim, q_dim, H, E, mh = struct.unpack_from("<7i", raw, 0) assert magic == 0x31584D4E, "not an imatrix file" off = 7 * 4 + 8 EE = max(E, 1) def take(n): nonlocal off a = np.frombuffer(raw, np.float32, n, off).copy() off += 4 * n return a att = take(L * dim).reshape(L, dim) wo = take(L * q_dim).reshape(L, q_dim) ffn = take(L * EE * dim).reshape(L, EE, dim) w2 = take(L * EE * H).reshape(L, EE, H) out = {} for l in range(L): out[f"att_in.{l}.sq"] = att[l] out[f"wo_in.{l}.sq"] = wo[l] if E > 0: cnt = np.frombuffer(raw, np.int64, L * E, off).reshape(L, E)[l] for a in (ffn, w2): seen = cnt > 0 if seen.any() and not seen.all(): a[l][~seen] = a[l][seen].mean(axis=0) out[f"ffn_in.{l}.sq"] = ffn[l] out[f"w2_in.{l}.sq"] = w2[l] else: out[f"ffn_in.{l}.sq"] = ffn[l, 0] out[f"w2_in.{l}.sq"] = w2[l, 0] return out
def _quant_job(key): kind, l = key w = _JOB["get"][kind](l) if kind in _JOB["q4"] and kind != "wg": imp = _JOB["imp"].get(f"{INPUT_OF[kind]}.{l}.sq") if _JOB["imp"] else None q, sc, err = quantize_q4(w, imp=imp) else: q, sc, err = quantize_q80(w, _JOB["gs"]) return q.tobytes() + sc.tobytes(), float(err)
KINDS_HYB = KINDS + ["li", "lo"] # + linear-attention input (qkv|z|b|a) and output projections
def _hyb_job(key): kind, l = key w = _JOB["get"][kind](l) if kind in _JOB["q4"]: imp = _JOB["imp"].get(f"{_JOB['inp'][kind]}.{l}.sq") if _JOB["imp"] else None if imp is not None: # statistics rows can be wider (wo / out_proj share one width) imp = np.asarray(imp)[: w.shape[-1]] q, sc, err = quantize_q4(w, imp=imp) else: q, sc, err = quantize_q80(w, _JOB["gs"]) return q.tobytes() + sc.tobytes(), float(err)
def export_qwen35(cfg_all, T, out_path, q4_kinds, stats, gs): """Qwen3.5 / Qwen3.8 dense text model (model_type qwen3_5), arch 3. Hybrid layers: Gated DeltaNet linear attention, every `full_attention_interval`-th layer gated full attention with partial RoPE. Layout after the 256-byte header (which adds int hybrid[8] = full_interval, linear k heads, linear v heads, k head dim, v head dim, conv kernel, attention output gate, rotary dims): fp32: att norms (L, dim), ffn norms (L, dim), final norm, q_norm / k_norm (Lf, head_dim) of the full layers, then for the linear layers conv (Ll, conv_dim, K), dt_bias (Ll, nv), A = -exp(A_log) (Ll, nv), gated-norm weight (Ll, dv). All zero-centered RMSNorm weights are stored as 1 + w. Quantized: embedding; full layers wq (q rows), wgate, wk, wv, wo; linear layers w_in = [qkv | z | b | a] rows, w_out; every layer w1, w2, w3; classifier. Vision tower and MTP head are not exported.""" cfg = cfg_all.get("text_config", cfg_all) P = "model.language_model." if "model.language_model.embed_tokens.weight" in T else "model." dim, hidden, L = cfg["hidden_size"], cfg["intermediate_size"], cfg["num_hidden_layers"] nh, nkv, hd = cfg["num_attention_heads"], cfg["num_key_value_heads"], cfg["head_dim"] vocab, eps = cfg["vocab_size"], float(cfg["rms_norm_eps"]) rp = cfg.get("rope_parameters", {}) theta = float(rp.get("rope_theta", cfg.get("rope_theta", 10000.0))) rot = int(hd * rp.get("partial_rotary_factor", cfg.get("partial_rotary_factor", 1.0))) nk, nv = cfg["linear_num_key_heads"], cfg["linear_num_value_heads"] dk, dv, K = cfg["linear_key_head_dim"], cfg["linear_value_head_dim"], cfg["linear_conv_kernel_dim"] types = cfg["layer_types"] interval = cfg.get("full_attention_interval", 4) assert all((t == "full_attention") == ((l + 1) % interval == 0) for l, t in enumerate(types)), "irregular layer types" full = [l for l in range(L) if types[l] == "full_attention"] lin = [l for l in range(L) if types[l] != "full_attention"] gate = int(cfg.get("attn_output_gate", True)) seq_len = min(int(cfg.get("max_position_embeddings", 262144)), 262144) g = lambda n: T[P + n].astype(np.float32) lay = lambda l, n: T[f"{P}layers.{l}.{n}"].astype(np.float32) eos = 248046 if vocab > 200000 else cfg.get("eos_token_id", 0) bos = cfg.get("bos_token_id") or 248044 special_start = 248044 q4_mask = sum(1 << KINDS_HYB.index(k) for k in q4_kinds)
out = open(out_path, "wb") out.write(struct.pack("<Ii", 0x616B3432, 2)) out.write(struct.pack("<7i", dim, hidden, L, nh, nkv, vocab, seq_len)) out.write(struct.pack("<B", 0)) out.write(struct.pack("<i", gs)) out.write(struct.pack("<ffffi", theta, 0.0, 0.0, 0.0, 0)) out.write(struct.pack("<ifiiii", 3, eps, 0, special_start, bos, eos)) out.write(struct.pack("<i", q4_mask)) out.write(struct.pack("<6i", hd, 0, 0, 0, 1, 0)) out.write(struct.pack("<i", 1)) # q4_format out.write(struct.pack("<8i", interval, nk, nv, dk, dv, K, gate, rot)) out.write(b"\0" * (256 - out.tell()))
for l in range(L): out.write((1.0 + lay(l, "input_layernorm.weight")).tobytes()) for l in range(L): out.write((1.0 + lay(l, "post_attention_layernorm.weight")).tobytes()) out.write((1.0 + g("norm.weight")).tobytes()) for l in full: out.write((1.0 + lay(l, "self_attn.q_norm.weight")).tobytes()) for l in full: out.write((1.0 + lay(l, "self_attn.k_norm.weight")).tobytes()) conv_dim = 2 * nk * dk + nv * dv for l in lin: out.write(lay(l, "linear_attn.conv1d.weight").reshape(conv_dim, K).tobytes()) for l in lin: out.write(lay(l, "linear_attn.dt_bias").tobytes()) for l in lin: out.write((-np.exp(lay(l, "linear_attn.A_log"))).astype(np.float32).tobytes()) for l in lin: out.write(lay(l, "linear_attn.norm.weight").tobytes())
maxerr = 0.0 q, sc, err = quantize_q80(g("embed_tokens.weight"), gs) out.write(q.tobytes()); out.write(sc.tobytes())
def qrows(l): return lay(l, "self_attn.q_proj.weight").reshape(nh, 2, hd, dim) getters = { "wq": lambda i: qrows(full[i])[:, 0].reshape(nh * hd, dim), "wg": lambda i: qrows(full[i])[:, 1].reshape(nh * hd, dim), "wk": lambda i: lay(full[i], "self_attn.k_proj.weight"), "wv": lambda i: lay(full[i], "self_attn.v_proj.weight"), "wo": lambda i: lay(full[i], "self_attn.o_proj.weight"), "li": lambda i: np.concatenate([lay(lin[i], "linear_attn." + n + ".weight") for n in ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")], 0), "lo": lambda i: lay(lin[i], "linear_attn.out_proj.weight"), "w1": lambda l: lay(l, "mlp.gate_proj.weight"), "w2": lambda l: lay(l, "mlp.down_proj.weight"), "w3": lambda l: lay(l, "mlp.up_proj.weight"), } # importance: inputs of each kind; layer index = real layer inp = {"wq": "att_in", "wg": "att_in", "wk": "att_in", "wv": "att_in", "li": "att_in", "wo": "wo_in", "lo": "wo_in", "w1": "ffn_in", "w3": "ffn_in", "w2": "w2_in"} imp = {} if stats is not None: for l in range(L): for key in ("att_in", "wo_in", "ffn_in", "w2_in"): imp[f"{key}.{l}.sq"] = stats[f"{key}.{l}.sq"] real = {"wq": full, "wg": full, "wk": full, "wv": full, "wo": full, "li": lin, "lo": lin} q4set = set(q4_kinds) | ({"wg"} if "wq" in q4_kinds else set()) def getter_real(kind): f_ = getters[kind] if kind in real: idx = {l: i for i, l in enumerate(real[kind])} return lambda l: f_(idx[l]) return f_ _JOB.update(get={k: getter_real(k) for k in getters}, q4=q4set, gs=gs, imp=imp if stats is not None else None, inp=inp) keys = [(k, l) for k in ("wq", "wg", "wk", "wv", "wo") for l in full] keys += [(k, l) for k in ("li", "lo") for l in lin] keys += [(k, l) for k in ("w1", "w2", "w3") for l in range(L)] import multiprocessing as mp procs = int(os.environ.get("EXPORT_PROCS", "64")) with mp.get_context("fork").Pool(min(len(keys), os.cpu_count() or 1, procs)) as pool: for blob, err in pool.imap(_hyb_job, keys, chunksize=1): out.write(blob) maxerr = max(maxerr, err) q, sc, err = quantize_q80(T["lm_head.weight"].astype(np.float32), gs) out.write(q.tobytes()); out.write(sc.tobytes()) out.close() print(f"qwen3_5: dim={dim} hidden={hidden} layers={L} (full {len(full)}, linear {len(lin)}) heads={nh}/{nkv}x{hd} " f"rot={rot} linear={nk}k/{nv}v x {dk}/{dv} conv={K} vocab={vocab} q4={sorted(q4set)}") print(f"max quantization error {maxerr:.5f}; wrote {os.path.getsize(out_path) / 1e9:.2f} GB")
def main(): args = [a for a in sys.argv[1:]] smooth_alpha = None if "--smooth" in args: # SmoothQuant alpha, needs --imatrix stats (max |x|) i = args.index("--smooth") smooth_alpha = float(args[i + 1]) del args[i:i + 2] imatrix_path = None if "--imatrix" in args: i = args.index("--imatrix") imatrix_path = args[i + 1] del args[i:i + 2] q4_kinds = [] q4_explicit = False if "--q4" in args: i = args.index("--q4") if i + 1 < len(args) and not args[i + 1].startswith("-") and not args[i + 1].isdigit(): q4_kinds = args[i + 1].split(",") q4_explicit = True del args[i:i + 2] else: q4_kinds = [k for k in KINDS if k != "wv"] # wv (small, sensitive) stays Q8 del args[i] model_dir, out_path = args[0], args[1] gs = int(args[2]) if len(args) > 2 else 64 cfg = json.load(open(os.path.join(model_dir, "config.json"))) files = sorted(f for f in os.listdir(model_dir) if f.endswith(".safetensors")) T = {} for f in files: T.update(load_safetensors(os.path.join(model_dir, f))) if cfg.get("model_type") == "qwen3_5": if not q4_explicit and "--q4" in sys.argv and q4_kinds == [k for k in KINDS if k != "wv"]: q4_kinds = [k for k in KINDS_HYB if k != "wv"] for k in q4_kinds: assert k in KINDS_HYB, f"unknown matrix kind {k}" export_qwen35(cfg, T, out_path, q4_kinds, load_imatrix(imatrix_path) if imatrix_path else None, gs) return for k in q4_kinds: assert k in KINDS, f"unknown matrix kind {k}" q4_mask = sum(1 << KINDS.index(k) for k in q4_kinds)
dim = cfg["hidden_size"] hidden = cfg["intermediate_size"] L = cfg["num_hidden_layers"] nh = cfg["num_attention_heads"] nkv = cfg.get("num_key_value_heads", nh) vocab = cfg["vocab_size"] seq_len = cfg["max_position_embeddings"] head_dim = cfg.get("head_dim") or dim // nh mt = cfg.get("model_type", "llama") moe = mt == "qwen3_moe" n_experts = cfg.get("num_experts", 0) if moe else 0 n_active = cfg.get("num_experts_per_tok", 0) if moe else 0 moe_hidden = cfg.get("moe_intermediate_size", 0) if moe else 0 if moe: hidden = moe_hidden # the group size must divide the rows of w2 (= one expert's hidden size) qk_norm = int("model.layers.0.self_attn.q_norm.weight" in T) emb = T["model.embed_tokens.weight"] shared = cfg.get("tie_word_embeddings", False) or "lm_head.weight" not in T if not shared and np.array_equal(emb, T["lm_head.weight"]): shared = True
# the group size must divide both dim and hidden_dim (the rows of w2 have hidden_dim elements) while dim % gs or hidden % gs: gs //= 2 print(f"BACKOFF: group size -> {gs}")
theta = float(cfg.get("rope_theta", 10000.0)) rs = cfg.get("rope_scaling") or {} if rs.get("rope_type", rs.get("type")) == "llama3": rope = (theta, float(rs["factor"]), float(rs["low_freq_factor"]), float(rs["high_freq_factor"]), int(rs["original_max_position_embeddings"])) else: rope = (theta, 0.0, 0.0, 0.0, 0)
out = open(out_path, "wb") out.write(struct.pack("<Ii", 0x616B3432, 2)) out.write(struct.pack("<7i", dim, hidden, L, nh, nkv, vocab, seq_len)) out.write(struct.pack("<B", int(shared))) out.write(struct.pack("<i", gs)) out.write(struct.pack("<ffffi", *rope)) arch = {"llama": 0, "qwen2": 1, "qwen3": 2, "qwen3_moe": 2}[mt] qkv_bias = int(f"model.layers.0.self_attn.q_proj.bias" in T) special_start = {0: 128000, 1: 151643, 2: 151643}[arch] eos = cfg.get("eos_token_id", 0) eos = eos[0] if isinstance(eos, list) else eos bos = cfg.get("bos_token_id") or special_start out.write(struct.pack("<ifiiii", arch, float(cfg.get("rms_norm_eps", 1e-5)), qkv_bias, special_start, bos, eos)) out.write(struct.pack("<i", q4_mask)) out.write(struct.pack("<6i", head_dim, n_experts, n_active, moe_hidden, qk_norm, int(bool(cfg.get("norm_topk_prob", False))))) out.write(struct.pack("<i", 1)) # q4_format out.write(b"\0" * (256 - out.tell()))
p = "model.layers.{}." # ---- optional SmoothQuant: x' = x / s, W' = W * s (columns), folded into the producers of x stats = load_imatrix(imatrix_path) if imatrix_path else None hd = dim // nh SM = {} if smooth_alpha is not None: assert stats is not None, "--smooth needs --imatrix stats.npz" a = smooth_alpha
def sfac(xmax, wmax): return np.clip(xmax ** a / np.maximum(wmax, 1e-5) ** (1 - a), 1e-2, 1e4).astype(np.float32)
for l in range(L): q = p.format(l) colmax = lambda *names: np.max([np.abs(T[q + n].astype(np.float32)).max(0) for n in names], 0) SM[("att_in", l)] = sfac(stats[f"att_in.{l}.max"], colmax("self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight")) SM[("ffn_in", l)] = sfac(stats[f"ffn_in.{l}.max"], colmax("mlp.gate_proj.weight", "mlp.up_proj.weight")) SM[("w2_in", l)] = sfac(stats[f"w2_in.{l}.max"], colmax("mlp.down_proj.weight")) # attention output channels come from (shared, GQA) v channels: one factor per v channel xm = stats[f"wo_in.{l}.max"].reshape(nkv, nh // nkv, hd).max(1) wm = colmax("self_attn.o_proj.weight").reshape(nkv, nh // nkv, hd).max(1) sv = sfac(xm, wm).reshape(-1) # (kv_dim,) SM[("v", l)] = sv SM[("wo_in", l)] = np.repeat(sv.reshape(nkv, 1, hd), nh // nkv, 1).reshape(-1) print(f"SmoothQuant alpha={a}")
def S(key, l): return SM.get((key, l))
def eff(kind, l): """effective (smoothed) weight in HF layout""" q = p.format(l) name = {"wq": "self_attn.q_proj", "wk": "self_attn.k_proj", "wv": "self_attn.v_proj", "wo": "self_attn.o_proj", "w1": "mlp.gate_proj", "w2": "mlp.down_proj", "w3": "mlp.up_proj"}[kind] w = T[q + name + ".weight"].astype(np.float32) if not SM: return w cs = S(INPUT_OF[kind], l) w = w * cs[None, :] if kind == "wv": w = w / S("v", l)[:, None] if kind == "w3": w = w / S("w2_in", l)[:, None] return w
def experts(l, name): """all experts of a MoE layer stacked along the rows (expert e = rows block e)""" q = p.format(l) return np.concatenate([T[f"{q}mlp.experts.{e}.{name}.weight"].astype(np.float32) for e in range(n_experts)], 0)
def norm(name, key, l): n = T[p.format(l) + name].astype(np.float32) return n / S(key, l) if SM else n
for l in range(L): out.write(norm("input_layernorm.weight", "att_in", l).tobytes()) for l in range(L): out.write(norm("post_attention_layernorm.weight", "ffn_in", l).tobytes()) out.write(T["model.norm.weight"].astype(np.float32).tobytes()) if qkv_bias: for l in range(L): out.write(hf_to_meta_qk(T[p.format(l) + "self_attn.q_proj.bias"], nh).astype(np.float32).tobytes()) for l in range(L): out.write(hf_to_meta_qk(T[p.format(l) + "self_attn.k_proj.bias"], nkv).astype(np.float32).tobytes()) for l in range(L): bv = T[p.format(l) + "self_attn.v_proj.bias"].astype(np.float32) out.write((bv / S("v", l) if SM else bv).tobytes()) if qk_norm: # per-head norms, permuted inside the head like the q/k rows for l in range(L): out.write(hf_to_meta_qk(T[p.format(l) + "self_attn.q_norm.weight"].astype(np.float32), 1).tobytes()) for l in range(L): out.write(hf_to_meta_qk(T[p.format(l) + "self_attn.k_norm.weight"].astype(np.float32), 1).tobytes())
maxerr = 0.0
def write_q(w, q4=False): nonlocal maxerr q, sc, err = quantize_q4(w) if q4 else quantize_q80(w, gs) maxerr = max(maxerr, float(err)) out.write(q.tobytes()) out.write(sc.tobytes())
write_q(emb) getters = [ lambda l: hf_to_meta_qk(eff("wq", l), nh), lambda l: hf_to_meta_qk(eff("wk", l), nkv), lambda l: eff("wv", l), lambda l: eff("wo", l), (lambda l: experts(l, "gate_proj")) if moe else (lambda l: eff("w1", l)), (lambda l: experts(l, "down_proj")) if moe else (lambda l: eff("w2", l)), (lambda l: experts(l, "up_proj")) if moe else (lambda l: eff("w3", l)), ] imp = None if stats is not None: # importance of the (smoothed) inputs: E[(x/s)^2] imp = {} for l in range(L): for key in ("att_in", "wo_in", "ffn_in", "w2_in"): v = stats[f"{key}.{l}.sq"] imp[f"{key}.{l}.sq"] = v / S(key, l) ** 2 if SM else v _JOB.update(get=dict(zip(KINDS, getters)), q4=q4_kinds, gs=gs, imp=imp) keys = [(kind, l) for kind in KINDS[:4] for l in range(L)] if moe: _JOB["get"]["wg"] = lambda l: T[p.format(l) + "mlp.gate.weight"] keys += [("wg", l) for l in range(L)] keys += [(kind, l) for kind in KINDS[4:] for l in range(L)] import multiprocessing as mp procs = int(os.environ.get("EXPORT_PROCS", "64")) # Q4 of stacked MoE experts: ~10 GB per process with mp.get_context("fork").Pool(min(len(keys), os.cpu_count() or 1, procs)) as pool: for blob, err in pool.imap(_quant_job, keys, chunksize=1): out.write(blob) maxerr = max(maxerr, err) if not shared: write_q(T["lm_head.weight"]) out.close() print(f"dim={dim} hidden={hidden} layers={L} heads={nh} kv_heads={nkv} vocab={vocab} " f"seq_len={seq_len} shared={shared} gs={gs} rope={rope} arch={mt} qkv_bias={qkv_bias} q4={q4_kinds} " f"head_dim={head_dim} experts={n_experts}x{moe_hidden} top{n_active} qk_norm={qk_norm}") print(f"max quantization error {maxerr:.5f}; wrote {os.path.getsize(out_path) / 1e9:.2f} GB")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267#!/usr/bin/env python3"""Export the text backbone of thinkingmachines/Inkling-2-Mini to an INK2 container.
Layout: magic "INK2JSON", u64 manifest length, JSON manifest padded to 1 MiB, then tensordata at absolute offsets. The manifest holds the config and one entry per tensor(name, dtype f32|q8|q4, shape, offset, bytes). Q8 is int8 data followed by f32 scales per64 values; Q4 is packed nibbles (byte k = u[k] | u[k+16] << 4) followed by fp16 (scale, min)per group of 32. Q4 experts are stored as [expert][rows][cols] blocks, each expert self-contained. Names are the source names with the `model.llm.` prefix removed, so the loader andforward can use the original layout. Vision and MTP tensors are skipped.
usage: export_inkling.py SOURCE.safetensors OUTPUT.ink2 [--layers 0,1] [--procs 64] [--experts q4|q8] (experts default to q4; q8 keeps the source dequant exact within 1%)"""import argparseimport jsonimport osimport structimport sysimport numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from export_hf_q8 import quantize_q4, quantize_q80
DATA_START = 1 << 20DT = {"U8": np.uint8, "F8_E4M3": np.uint8, "F32": np.float32, "BF16": np.uint16}E2M1 = np.array([0, .5, 1, 1.5, 2, 3, 4, 6, -0., -.5, -1, -1.5, -2, -3, -4, -6], np.float32)_E4M3 = None
def e4m3(): global _E4M3 if _E4M3 is None: c = np.arange(256, dtype=np.uint8) ex = ((c & 0x7f) >> 3).astype(np.int32) ma = (c & 7).astype(np.float32) v = np.where(ex == 0, np.ldexp(ma, -9), np.ldexp(1 + ma / 8, ex - 7)) v = np.where(c & 0x80, -v, v).astype(np.float32) v[(c & 0x7f) == 0x7f] = np.nan _E4M3 = v return _E4M3
class Safetensors: def __init__(self, path): self.path = path with open(path, "rb") as f: n = struct.unpack("<Q", f.read(8))[0] self.header = json.loads(f.read(n)) self.base = 8 + n
def read(self, name, index=None): e = self.header[name] a, b = e["data_offsets"] with open(self.path, "rb") as f: f.seek(self.base + a) raw = np.frombuffer(f.read(b - a), DT[e["dtype"]]) a = raw.reshape(e["shape"]) if e["dtype"] == "BF16": a = (a.astype(np.uint32) << 16).view(np.float32) return a[index] if index is not None else a
def q8_blob(w): q, s, _ = quantize_q80(w.astype(np.float32), 64) return q.tobytes() + s.astype(np.float32).tobytes()
def q8_size(rows, cols): return rows * cols + rows * (cols // 64) * 4
def q4e_size(e, rows, cols): return e * (rows * cols // 2 + rows * (cols // 32) * 4)
def q8e_size(e, rows, cols): return e * q8_size(rows, cols)
def nvfp4(w, sc, amax, denom): out = np.empty((w.shape[0], w.shape[1] * 2), np.float32) out[:, 0::2] = E2M1[w & 15] out[:, 1::2] = E2M1[w >> 4] out.reshape(out.shape[0], -1, 16)[:] *= e4m3()[sc][:, :, None] return out * (amax / denom)
def mxfp8(w, sc): out = e4m3()[w].copy() bs = np.ldexp(np.ones(sc.shape, np.float32), sc.astype(np.int32) - 127) out.reshape(out.shape[0], -1, 32)[:] *= bs[:, :, None] return out
_W = None
def expert_worker(task): src, kind, e, off, stride, quant = task st, H, base = _W wname = src + "_weight" if not src.endswith("_weight") else src e0 = H[wname] a, b = e0["data_offsets"] with open(st, "rb") as f: f.seek(base + a) w = np.frombuffer(f.read(b - a), DT[e0["dtype"]]).reshape(e0["shape"])[e] sn = wname + "_scale" se = H[sn] a, b = se["data_offsets"] f.seek(base + a) sc = np.frombuffer(f.read(b - a), DT[se["dtype"]]).reshape(se["shape"])[e] if H[sn]["dtype"] == "F8_E4M3": # NVFP4 weights are U8 with E4M3 block scales an = wname + "_amax" dn = wname + "_outer_scale_denominator" st2, H2, base2 = _W with open(st, "rb") as f: ae = H[an]; a, b = ae["data_offsets"]; f.seek(base + a) amax = np.frombuffer(f.read(b - a), np.float32).reshape(ae["shape"])[e] de = H[dn]; a, b = de["data_offsets"]; f.seek(base + a) denom = np.frombuffer(f.read(b - a), np.float32)[0] dense = nvfp4(w, sc, amax, denom) else: # MXFP8 dense = mxfp8(w, sc) if quant == "q8": return q8_blob(dense) q, sm, _ = quantize_q4(dense) return q.tobytes() + sm.tobytes()
def main(): ap = argparse.ArgumentParser() ap.add_argument("source") ap.add_argument("output") ap.add_argument("--layers", default="") ap.add_argument("--procs", type=int, default=min(64, os.cpu_count() or 1)) ap.add_argument("--skip-embed", action="store_true") ap.add_argument("--experts", choices=("q4", "q8"), default="q4") args = ap.parse_args()
cfg = json.load(open(os.path.join(os.path.dirname(args.source), "config.json"))) tc = cfg.get("text_config", cfg) st = Safetensors(args.source) H = st.header L = tc["num_hidden_layers"] dim, inter = tc["hidden_size"], tc["intermediate_size"] nh, nkv, hd = tc["num_attention_heads"], tc["num_key_value_heads"], tc["head_dim"] E = tc["n_routed_experts"] loop = tc["loop_config"] local = set(tc.get("local_layer_ids", [])) want_layers = set(int(x) for x in args.layers.split(",")) if args.layers else set(range(L)) keep = [] for name in H: if name == "__metadata__" or name.startswith(("model.visual.", "model.vision_tower.", "mtp.")): continue if not name.startswith("model.llm."): continue nm = name[len("model.llm."):] if nm.startswith("layers.") and int(nm.split(".")[1]) not in want_layers: continue if nm.startswith("embed.") and args.skip_embed: continue if nm.startswith("unembed.") and args.skip_embed: continue keep.append(nm)
f32_suffix = (".static_w", "_sconv.weight", ".rel_logits_proj.proj", ".q_l2_clip.scale", ".rel_l2_clip.scale", ".attn_queries", ".mlp_queries", ".output_query", "cross_pass_queries", "cross_pass_kv_queries", "norm.weight", ".gate.bias") desc = [] for nm in keep: if nm.endswith(("_scale", "_amax", "_outer_scale_denominator")): continue src = "model.llm." + nm if nm.endswith(("w13_weight", "w2_weight")): rows, cols = (2 * inter, dim) if nm.endswith("w13_weight") else (dim, inter) kind = "w13" if nm.endswith("w13_weight") else "w2" size = q8e_size(E, rows, cols) if args.experts == "q8" else q4e_size(E, rows, cols) desc.append({"name": nm.replace("_weight", ""), "dtype": args.experts, "shape": [E, rows, cols], "src": src, "kind": kind, "expert": True, "size": size}) continue arr = st.read(src) if nm.endswith(f32_suffix) or ".attn_queries." in nm or ".mlp_queries." in nm: desc.append({"name": nm, "dtype": "f32", "shape": list(arr.shape), "src": src, "size": int(arr.size) * 4}) continue if arr.ndim != 2: raise SystemExit(f"{nm}: expected a 2-D matrix, got {arr.shape}") rows, cols = arr.shape if cols % 64: raise SystemExit(f"{nm}: cols {cols} not divisible by 64") desc.append({"name": nm, "dtype": "q8", "shape": [rows, cols], "src": src, "size": q8_size(rows, cols)})
off = DATA_START for d in desc: d["offset"] = off off = (off + d["size"] + 63) & ~63 total = off out = open(args.output, "wb") out.truncate(total) print(f"{len(desc)} tensors, {total/1e9:.2f} GB, data at {DATA_START}", flush=True)
# non-expert tensors (experts are written per expert below) for d in desc: if d.get("expert"): continue w = st.read(d["src"]) blob = w.astype(np.float32).tobytes() if d["dtype"] == "f32" else q8_blob(w) assert len(blob) == d["size"], (d["name"], len(blob), d["size"]) out.seek(d["offset"]) out.write(blob) print("non-expert tensors written", flush=True)
tasks = [] for d in desc: if not d.get("expert"): continue stride = d["size"] // E for e in range(E): tasks.append((d["src"], d["kind"], e, d["offset"], stride, d["dtype"])) if tasks: global _W _W = (args.source, H, st.base) import multiprocessing as mp with mp.get_context("fork").Pool(args.procs) as pool: for n, blob in enumerate(pool.imap(expert_worker, tasks, chunksize=1)): _, _, e, off0, stride, _ = tasks[n] out.seek(off0 + e * stride) out.write(blob) if (n + 1) % 512 == 0: print(f"experts {n+1}/{len(tasks)}", flush=True) out.close()
manifest = { "config": { "arch": "inkling2_loop", "phys_layers": L, "slots": L + (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"]), "dim": dim, "inter": inter, "heads": nh, "kv_heads": nkv, "head_dim": hd, "vocab": tc["vocab_size"], "unpadded_vocab": tc["unpadded_vocab_size"], "experts": E, "active": tc["num_experts_per_tok"], "loop_start": loop["core_start"], "loop_end": loop["core_end"], "passes": loop["num_passes"], "gate_rank": loop["gate_rank"], "d_rel": tc["d_rel"], "rel_extent": tc["rel_extent"], "window": tc["sliding_window_size"], "conv_k": tc["sconv_kernel_size"], "res_block": tc["n_layers_per_attn_res_block"], "local": sorted(local), "eps": tc["rms_norm_eps"], "qk_clip": tc["qk_l2_clip_threshold"], "rel_clip": tc["rel_l2_clip_threshold"], "log_floor": tc["log_scaling_n_floor"], "log_alpha": tc["log_scaling_alpha"], "final_softcap": tc["final_logit_softcapping"], "gate_softcap": tc["mlp_gate_softcap"], "up_softcap": tc["mlp_up_softcap"], "route_scale": tc["route_scale"], "eos": cfg["eos_token_id"], "special_start": 199998, }, "tensors": desc, } js = json.dumps(manifest, separators=(",", ":")).encode() if len(js) > DATA_START - 16: raise SystemExit("manifest does not fit the 1 MiB header") with open(args.output, "r+b") as f: f.seek(0) f.write(b"INK2JSON") f.write(struct.pack("<Q", len(js))) f.write(js) print("manifest", len(js), "bytes; done", args.output, flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%}{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
{%- macro emit_thinking_effort() -%} {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%} {%- if eff is string -%} {%- set key = eff | trim -%} {%- if key not in effort_map -%} {{- raise_exception("Unknown reasoning_effort: " ~ eff) -}} {%- endif -%} {%- set num = effort_map[key] -%} {%- else -%} {%- set num = eff | float -%} {%- endif -%} {%- if num < 0.0 or num > 0.99 -%} {{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}} {%- endif -%} {{- "<|message_system|><|content_text|>Thinking effort level: " -}} {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%} {{- "<|end_message|>" -}}{%- endmacro -%}
{%- if tools -%} {%- set tool_state = namespace(specs=[]) -%} {%- for tool in tools -%} {%- set fn = tool.function if tool.function is defined else tool -%} {%- set spec = { "description": (fn.description if fn.description is defined and fn.description else ""), "name": fn.name, "parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}), "type": (tool.type if tool.type is defined and tool.type else "function"), } -%} {%- set tool_state.specs = tool_state.specs + [spec] -%} {%- endfor -%} {{- "<|message_system|>tool_declare<|content_xml|>" -}} {{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}} {{- "<|end_message|>" -}}{%- endif -%}
{%- set state = namespace(effort_emitted=false) -%}{%- for message in messages -%} {%- if message.role not in role_token -%} {{- raise_exception("Unknown message role: " ~ message.role) -}} {%- endif -%} {%- if not state.effort_emitted and message.role != "system" -%} {{- emit_thinking_effort() -}} {%- set state.effort_emitted = true -%} {%- endif -%}
{%- set header = namespace(text=role_token[message.role]) -%} {%- if message.role == "tool" -%} {%- if message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- elif message.tool_call_id is defined and message.tool_call_id -%} {%- for prev in messages -%} {%- if prev.role == "assistant" and prev.tool_calls -%} {%- for tc in prev.tool_calls -%} {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%} {%- set header.text = header.text ~ tc.function.name -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- elif message.role == "assistant" and message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- endif -%} {%- set rtok = header.text -%} {%- set rendered -%}
{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%} {{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}} {%- endif -%}
{%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%} {{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}} {%- elif message.content -%} {%- for part in message.content -%} {%- if part is string -%} {{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}} {%- elif part.type is not defined or part.type in ("text", "input_text") -%} {%- set text_part = (part.text if part.text is defined and part.text is string else "") -%} {{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}} {%- elif part.type in ("image", "input_image", "image_url") -%} {%- if message.role not in ("user", "tool") -%} {{- raise_exception("Image content is only supported for user and tool messages") -}} {%- endif -%} {{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}} {%- elif part.type in ("audio", "input_audio", "audio_url") -%} {{- raise_exception("Inkling 2 does not accept audio input") -}} {%- else -%} {{- raise_exception("Unsupported content part type: " ~ part.type) -}} {%- endif -%} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" and message.tool_calls -%} {%- for tc in message.tool_calls -%} {%- set fn = tc.function -%} {%- if fn.name is not defined or fn.name is not string -%} {{- raise_exception("tool call function name must be a string") -}} {%- endif -%} {%- if message.name is defined and message.name and message.name != fn.name -%} {{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}} {%- endif -%} {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%} {%- if args is string -%} {{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}} {%- endif -%} {%- if args is not mapping -%} {{- raise_exception("tool call arguments must be an object") -}} {%- endif -%} {{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}} {{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}} {{- "{" -}} {%- for key, value in args | dictsort(case_sensitive=true) -%} {{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}} {%- if not loop.last -%},{%- endif -%} {%- endfor -%} {{- "}}<|end_message|>" -}} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" -%} {{- "<|content_model_end_sampling|>" -}} {%- endif -%} {%- endset -%} {%- if message.role == "assistant" -%} {%- generation -%}{{- rendered -}}{%- endgeneration -%} {%- else -%} {{- rendered -}} {%- endif -%}{%- endfor -%}
{%- if not state.effort_emitted -%} {{- emit_thinking_effort() -}}{%- endif -%}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122{ "dtype": "bfloat16", "architectures": [ "Inkling2LoopForConditionalGeneration" ], "model_type": "inkling2_loop", "eos_token_id": 200006, "text_config": { "model_type": "inkling2_loop_text", "model_max_length": 1048576, "torch_dtype": "bfloat16", "hidden_size": 2304, "num_hidden_layers": 24, "vocab_size": 201024, "num_attention_heads": 24, "num_key_value_heads": 8, "head_dim": 128, "d_rel": 16, "rel_extent": 1024, "q_bias": false, "o_bias": false, "log_scaling_n_floor": 8192, "log_scaling_alpha": 0.1, "rms_norm_eps": 1e-06, "use_value_norm_no_gamma": true, "qk_l2_clip_threshold": 22.627416997969522, "rel_l2_clip_threshold": 8.0, "local_layer_ids": [ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22 ], "sconv_kernel_size": 4, "unpadded_vocab_size": 200058, "final_logit_softcapping": 30.0, "swa_head_dim": 128, "swa_num_attention_heads": 24, "swa_num_key_value_heads": 8, "sliding_window_size": 1024, "n_layers_per_attn_res_block": 6, "attn_res_normalize_values": true, "n_routed_experts": 128, "num_experts_per_tok": 8, "n_shared_experts": 0, "intermediate_size": 1152, "mlp_gate_softcap": 4.0, "mlp_up_softcap": 25.0, "route_scale": 8.0, "use_gate_bias": true, "loop_config": { "core_start": 6, "core_end": 18, "num_passes": 3, "gate_rank": 64, "is_varloop": false } }, "vision_config": { "model_type": "inkling2_vision", "text_hidden_size": 2304, "temporal_patch_size": 2, "native_patch_size": 20, "adapter_merge_size": 2, "projection_hidden_dim": 4096, "projector_bias": false, "hidden_size": 1024, "num_hidden_layers": 23, "num_attention_heads": 16, "mlp_ratio": 4.0, "posemb_grid_size": 32, "layer_norm_eps": 1e-05 }, "mtp_config": { "hidden_size": 2304, "num_hidden_layers": 3, "num_attention_heads": 24, "num_key_value_heads": 8, "head_dim": 128, "intermediate_size": 9216, "max_position_embeddings": 1048576, "torch_dtype": "bfloat16", "q_bias": false, "o_bias": false, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "local_layer_ids": [ 0, 2 ], "sliding_window_size": 1024, "block_size": 8, "markov_rank": 256, "markov_head_type": "rnn_hidden", "target_layer_ids": [ 5, 23, 41, 48 ] }, "quantization_config": { "quant_method": "modelopt", "quant_algo": "NVFP4" }}123456{ "do_sample": true, "temperature": 1.0, "eos_token_id": 200006, "pad_token_id": 199999}123456789101112131415161718192021{ "additional_special_tokens": [ "<|endoftext|>", "<|message_user|>", "<|message_model|>", "<|message_system|>", "<|message_tool|>", "<|content_text|>", "<|content_image|>", "<|content_model_end_sampling|>", "<|content_thinking|>", "<|end_message|>", "<|content_tool_error|>", "<|content_xml|>", "<|begin_of_text|>", "<|content_invoke_tool_json|>", "<|content_invoke_tool_text|>" ], "eos_token": "<|content_model_end_sampling|>", "pad_token": "<|endoftext|>"}123version https://git-lfs.github.com/spec/v1oid sha256:7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6size 26178678123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548{ "tokenizer_class": "PreTrainedTokenizerFast", "model_max_length": 1048576, "clean_up_tokenization_spaces": false, "fix_mistral_regex": false, "extra_special_tokens": { "endoftext": "<|endoftext|>", "message_user": "<|message_user|>", "message_model": "<|message_model|>", "message_system": "<|message_system|>", "message_tool": "<|message_tool|>", "content_text": "<|content_text|>", "content_image": "<|content_image|>", "content_model_end_sampling": "<|content_model_end_sampling|>", "content_thinking": "<|content_thinking|>", "end_message": "<|end_message|>", "content_tool_error": "<|content_tool_error|>", "content_xml": "<|content_xml|>", "begin_of_text": "<|begin_of_text|>", "content_invoke_tool_json": "<|content_invoke_tool_json|>", "content_invoke_tool_text": "<|content_invoke_tool_text|>" }, "added_tokens_decoder": { "199998": { "content": "<|unused|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "199999": { "content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200000": { "content": "<|message_user|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200001": { "content": "<|message_model|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200002": { "content": "<|message_system|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200003": { "content": "<|message_tool|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200004": { "content": "<|content_text|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200005": { "content": "<|content_image|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200006": { "content": "<|content_model_end_sampling|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200007": { "content": "<|unused_200007|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200008": { "content": "<|content_thinking|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200009": { "content": "<|unused_200009|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200010": { "content": "<|end_message|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200011": { "content": "<|unused_200011|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200012": { "content": "<|unused_200012|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200013": { "content": "<|unused_200013|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200014": { "content": "<|unused_200014|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200015": { "content": "<|unused_200015|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200016": { "content": "<|unused_200016|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200017": { "content": "<|unused_200017|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200018": { "content": "<|unused_200018|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200019": { "content": "<|unused_200019|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200020": { "content": "<|unused_200020|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200021": { "content": "<|unused_200021|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200022": { "content": "<|content_tool_error|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200023": { "content": "<|unused_200023|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200024": { "content": "<|content_xml|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200025": { "content": "<|unused_200025|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200026": { "content": "<|unused_200026|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200027": { "content": "<|unused_200027|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200028": { "content": "<|begin_of_text|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200029": { "content": "<|unused_200029|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200030": { "content": "<|unused_200030|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200031": { "content": "<|unused_200031|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200032": { "content": "<|unused_200032|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200033": { "content": "<|unused_200033|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200034": { "content": "<|unused_200034|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200035": { "content": "<|unused_200035|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200036": { "content": "<|unused_200036|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200037": { "content": "<|unused_200037|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200038": { "content": "<|unused_200038|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200039": { "content": "<|unused_200039|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200040": { "content": "<|unused_200040|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200041": { "content": "<|unused_200041|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200042": { "content": "<|unused_200042|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200043": { "content": "<|unused_200043|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200044": { "content": "<|unused_200044|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200045": { "content": "<|unused_200045|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200046": { "content": "<|unused_200046|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200047": { "content": "<|unused_200047|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200048": { "content": "<|unused_200048|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200049": { "content": "<|content_invoke_tool_json|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200050": { "content": "<|unused_200050|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200051": { "content": "<|unused_200051|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200052": { "content": "<|unused_200052|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200053": { "content": "<|unused_200053|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200054": { "content": "<|unused_200054|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200055": { "content": "<|unused_200055|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200056": { "content": "<|unused_200056|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, "200057": { "content": "<|content_invoke_tool_text|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true } }, "response_template": { "defaults": { "role": "assistant" }, "start_anchor_pattern": "<\\|end_message\\|>|<\\|content_model_end_sampling\\|>", "fields": { "reasoning_content": { "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_thinking\\|>", "close": "<|end_message|>", "repeats": true, "join": "", "content": "text", "content_args": { "strip": false } }, "content": { "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_(?:text|tool_error|invoke_tool_text)\\|>", "close": "<|end_message|>", "repeats": true, "join": "", "content": "text", "content_args": { "strip": false } }, "tool_calls": { "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_invoke_tool_json\\|>", "close": "<|end_message|>", "repeats": true, "content": "json", "transform": { "type": "function", "function": { "name": "{content.name}", "arguments": "{content.args}" } } } } }, "eos_token": "<|content_model_end_sampling|>", "pad_token": "<|endoftext|>"}.gitattributes+1
LICENSEAdded+202
NOTICEAdded+11
README.mdAdded+133
checksums.sha256Added+3
inkling2_tokenizer.binAdded+3
quality/check_q8.logAdded+28
quality/logits_oracle.binAdded+3
quality/logits_q4.binAdded+3
quality/logits_q8.binAdded+3
scripts/compare_inkling_logits.pyAdded+53
scripts/export_hf_q8.pyAdded+539
scripts/export_inkling.pyAdded+267
source/chat_template.jinjaAdded+137
source/config.jsonAdded+122
source/generation_config.jsonAdded+6
source/special_tokens_map.jsonAdded+21
source/tokenizer.jsonAdded+3
source/tokenizer_config.jsonAdded+548