controlllmai ykhrustalev commited on
Commit
6688fba
·
0 Parent(s):

Duplicate from LiquidAI/LFM2.5-1.2B-Thinking-ONNX

Browse files

Co-authored-by: Yuri Khrustalev <ykhrustalev@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
+ onnx/model.onnx_data filter=lfs diff=lfs merge=lfs -text
37
+ onnx/model.onnx_data_1 filter=lfs diff=lfs merge=lfs -text
38
+ onnx/model.onnx_data_2 filter=lfs diff=lfs merge=lfs -text
39
+ onnx/model_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
40
+ onnx/model_fp16.onnx_data_1 filter=lfs diff=lfs merge=lfs -text
41
+ onnx/model_q4.onnx_data filter=lfs diff=lfs merge=lfs -text
42
+ onnx/model_q8.onnx_data filter=lfs diff=lfs merge=lfs -text
43
+ onnx/model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
44
+ onnx/model_quantized.onnx_data filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE TEXT
2
+
3
+
4
+
5
+
6
+ LFM Open License v1.0
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+ 1. Definitions.
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
10
+ "Licensor" shall mean Liquid AI, Inc.
11
+ "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.
12
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
13
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
14
+ "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.
15
+ "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.
16
+ "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.
17
+ "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."
18
+ "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.
19
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
20
+ "Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
21
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
22
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
23
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, 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.
24
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, 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.
25
+ 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:
26
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
27
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
28
+ (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
29
+ (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.
30
+ 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.
31
+ 5. Commercial Use Limitation.
32
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
33
+ (b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
34
+ (c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
35
+ 6. 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.
36
+ 7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
37
+ 8. 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.
38
+ 9. 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.
39
+ 10. 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.
40
+ 11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
41
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: lfm1.0
4
+ license_link: LICENSE
5
+ language:
6
+ - en
7
+ - ja
8
+ - ko
9
+ - fr
10
+ - es
11
+ - de
12
+ - it
13
+ - pt
14
+ - ar
15
+ - zh
16
+ pipeline_tag: text-generation
17
+ tags:
18
+ - liquid
19
+ - edge
20
+ - lfm2.5
21
+ - thinking
22
+ - reasoning
23
+ - onnx
24
+ - onnxruntime
25
+ - webgpu
26
+ base_model:
27
+ - LiquidAI/LFM2.5-1.2B-Thinking
28
+ ---
29
+
30
+ <div align="center">
31
+ <img src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png" alt="Liquid AI" style="width: 100%; max-width: 100%;">
32
+
33
+ <p>
34
+ <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
35
+ <a href="https://docs.liquid.ai/lfm"><strong>Documentation</strong></a> •
36
+ <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> •
37
+ <a href="https://www.liquid.ai/blog/"><strong>Blog</strong></a>
38
+ </p>
39
+ </div>
40
+
41
+ # LFM2.5-1.2B-Thinking-ONNX
42
+
43
+ ONNX export of [LFM2.5-1.2B-Thinking](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking) for cross-platform inference.
44
+
45
+ LFM2.5-Thinking is a reasoning model that generates step-by-step thinking before producing final answers. The model outputs its reasoning process within `<think>...</think>` tags, followed by the final response. This approach improves accuracy on complex tasks like math, coding, and logical reasoning.
46
+
47
+ ## Recommended Variants
48
+
49
+ | Precision | Size | Use Case |
50
+ |-----------|------|----------|
51
+ | Q4 | ~1.2GB | Recommended for most uses |
52
+ | FP16 | ~2.4GB | Higher quality |
53
+ | Q8 | ~1.7GB | Balance of quality and size |
54
+
55
+ ## Model Files
56
+
57
+ ```
58
+ onnx/
59
+ ├── model.onnx # FP32
60
+ ├── model_fp16.onnx # FP16
61
+ ├── model_q4.onnx # Q4 (recommended)
62
+ └── model_q8.onnx # Q8
63
+ ```
64
+
65
+ ## Python
66
+
67
+ ### Installation
68
+
69
+ ```bash
70
+ pip install onnxruntime transformers numpy huggingface_hub
71
+ # or with GPU support:
72
+ pip install onnxruntime-gpu transformers numpy huggingface_hub
73
+ ```
74
+
75
+ ### Inference
76
+
77
+ ```python
78
+ import re
79
+
80
+ import numpy as np
81
+ import onnxruntime as ort
82
+ from huggingface_hub import hf_hub_download
83
+ from transformers import AutoTokenizer
84
+
85
+ # Download model (Q4 recommended)
86
+ model_id = "LiquidAI/LFM2.5-1.2B-Thinking-ONNX"
87
+ model_path = hf_hub_download(model_id, "onnx/model_q4.onnx")
88
+ data_path = hf_hub_download(model_id, "onnx/model_q4.onnx_data")
89
+
90
+ # Load model and tokenizer
91
+ session = ort.InferenceSession(model_path)
92
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
93
+
94
+ # Prepare chat input
95
+ messages = [{"role": "user", "content": "What is 25 * 37?"}]
96
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
97
+ input_ids = np.array([tokenizer.encode(prompt, add_special_tokens=False)], dtype=np.int64)
98
+
99
+ # Initialize KV cache
100
+ ONNX_DTYPE = {"tensor(float)": np.float32, "tensor(float16)": np.float16, "tensor(int64)": np.int64}
101
+ cache = {}
102
+ for inp in session.get_inputs():
103
+ if inp.name in {"input_ids", "attention_mask", "position_ids"}:
104
+ continue
105
+ shape = [d if isinstance(d, int) else 1 for d in inp.shape]
106
+ for i, d in enumerate(inp.shape):
107
+ if isinstance(d, str) and "sequence" in d.lower():
108
+ shape[i] = 0
109
+ cache[inp.name] = np.zeros(shape, dtype=ONNX_DTYPE.get(inp.type, np.float32))
110
+
111
+ # Check if model uses position_ids
112
+ input_names = {inp.name for inp in session.get_inputs()}
113
+ use_position_ids = "position_ids" in input_names
114
+
115
+ # Generate tokens
116
+ seq_len = input_ids.shape[1]
117
+ generated_tokens = []
118
+
119
+ for step in range(512): # max tokens (reasoning may need more tokens)
120
+ if step == 0:
121
+ ids = input_ids
122
+ pos = np.arange(seq_len, dtype=np.int64).reshape(1, -1)
123
+ else:
124
+ ids = np.array([[generated_tokens[-1]]], dtype=np.int64)
125
+ pos = np.array([[seq_len + len(generated_tokens) - 1]], dtype=np.int64)
126
+
127
+ attn_mask = np.ones((1, seq_len + len(generated_tokens)), dtype=np.int64)
128
+ feed = {"input_ids": ids, "attention_mask": attn_mask, **cache}
129
+ if use_position_ids:
130
+ feed["position_ids"] = pos
131
+
132
+ outputs = session.run(None, feed)
133
+ next_token = int(np.argmax(outputs[0][0, -1]))
134
+ generated_tokens.append(next_token)
135
+
136
+ # Update cache
137
+ for i, out in enumerate(session.get_outputs()[1:], 1):
138
+ name = out.name.replace("present_conv", "past_conv").replace("present.", "past_key_values.")
139
+ if name in cache:
140
+ cache[name] = outputs[i]
141
+
142
+ if next_token == tokenizer.eos_token_id:
143
+ break
144
+
145
+ # Parse thinking and response
146
+ full_response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
147
+ think_match = re.search(r"<think>(.*?)</think>", full_response, re.DOTALL)
148
+ if think_match:
149
+ thinking = think_match.group(1).strip()
150
+ answer = full_response[think_match.end():].strip()
151
+ print(f"Thinking:\n{thinking}\n")
152
+ print(f"Answer:\n{answer}")
153
+ else:
154
+ print(full_response)
155
+ ```
156
+
157
+ ## WebGPU (Browser)
158
+
159
+ ### Installation
160
+
161
+ ```bash
162
+ npm install onnxruntime-web @huggingface/transformers
163
+ ```
164
+
165
+ ### Enable WebGPU
166
+
167
+ WebGPU is required for browser inference. To enable:
168
+
169
+ 1. **Chrome/Edge**: Navigate to `chrome://flags/#enable-unsafe-webgpu`, enable, and restart
170
+ 2. **Verify**: Check `chrome://gpu` for "WebGPU" status
171
+ 3. **Test**: Run `navigator.gpu.requestAdapter()` in DevTools console
172
+
173
+ ### Inference
174
+
175
+ ```javascript
176
+ import * as ort from "onnxruntime-web/webgpu";
177
+ import { AutoTokenizer } from "@huggingface/transformers";
178
+
179
+ // Check WebGPU availability
180
+ if (!navigator.gpu) {
181
+ throw new Error("WebGPU not available. Enable at chrome://flags/#enable-unsafe-webgpu");
182
+ }
183
+ const adapter = await navigator.gpu.requestAdapter();
184
+ if (!adapter) {
185
+ throw new Error("WebGPU adapter not found. Check chrome://gpu for status.");
186
+ }
187
+
188
+ ort.env.wasm.numThreads = 1;
189
+
190
+ const modelId = "LiquidAI/LFM2.5-1.2B-Thinking-ONNX";
191
+ const modelBase = `https://huggingface.co/${modelId}/resolve/main`;
192
+
193
+ // Load tokenizer
194
+ const tokenizer = await AutoTokenizer.from_pretrained(modelId);
195
+
196
+ // Load ONNX session with external data
197
+ const onnxPath = `${modelBase}/onnx/model_q4.onnx`;
198
+ const dataPath = `${modelBase}/onnx/model_q4.onnx_data`;
199
+ const session = await ort.InferenceSession.create(onnxPath, {
200
+ executionProviders: ["webgpu"],
201
+ externalData: [{ path: "model_q4.onnx_data", data: dataPath }],
202
+ });
203
+
204
+ // Model config (from config.json)
205
+ const hiddenSize = 2048;
206
+ const numKVHeads = 8;
207
+ const headDim = 256;
208
+
209
+ // Initialize KV cache
210
+ function initCache() {
211
+ const cache = {};
212
+ for (const name of session.inputNames) {
213
+ if (name.startsWith("past_conv")) {
214
+ cache[name] = new ort.Tensor("float32", new Float32Array(hiddenSize * 3), [1, hiddenSize, 3]);
215
+ } else if (name.startsWith("past_key_values")) {
216
+ cache[name] = new ort.Tensor("float32", new Float32Array(0), [1, numKVHeads, 0, headDim]);
217
+ }
218
+ }
219
+ return cache;
220
+ }
221
+
222
+ // Update cache from outputs
223
+ function updateCache(cache, outputs) {
224
+ for (const [name, tensor] of Object.entries(outputs)) {
225
+ if (name.startsWith("present_conv")) {
226
+ cache[name.replace("present_conv", "past_conv")] = tensor;
227
+ } else if (name.startsWith("present.")) {
228
+ cache[name.replace("present.", "past_key_values.")] = tensor;
229
+ }
230
+ }
231
+ }
232
+
233
+ // Build prompt and tokenize
234
+ const messages = [{ role: "user", content: "What is 25 * 37?" }];
235
+ const prompt = tokenizer.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
236
+ const inputIds = tokenizer.encode(prompt);
237
+
238
+ // Generation loop
239
+ const cache = initCache();
240
+ const eosTokenId = tokenizer.eos_token_id;
241
+ const generatedTokens = [];
242
+ let curLen = inputIds.length;
243
+ let ids = inputIds;
244
+
245
+ for (let step = 0; step < 512; step++) {
246
+ const inputIdsTensor = new ort.Tensor("int64", new BigInt64Array(ids.map(BigInt)), [1, ids.length]);
247
+ const attentionMask = new ort.Tensor("int64", new BigInt64Array(curLen).fill(1n), [1, curLen]);
248
+
249
+ const outputs = await session.run({ input_ids: inputIdsTensor, attention_mask: attentionMask, ...cache });
250
+
251
+ // Greedy decode: argmax of last token logits
252
+ const logits = outputs.logits;
253
+ const vocabSize = logits.dims[2];
254
+ const lastLogits = logits.data.slice((logits.dims[1] - 1) * vocabSize);
255
+ const nextToken = lastLogits.indexOf(Math.max(...lastLogits));
256
+
257
+ generatedTokens.push(nextToken);
258
+ if (nextToken === eosTokenId) break;
259
+
260
+ updateCache(cache, outputs);
261
+ ids = [nextToken];
262
+ curLen++;
263
+ }
264
+
265
+ // Parse thinking and response
266
+ const fullResponse = tokenizer.decode(generatedTokens, { skip_special_tokens: true });
267
+ const thinkMatch = fullResponse.match(/<think>([\s\S]*?)<\/think>/);
268
+ if (thinkMatch) {
269
+ const thinking = thinkMatch[1].trim();
270
+ const answer = fullResponse.slice(thinkMatch.index + thinkMatch[0].length).trim();
271
+ console.log("Thinking:", thinking);
272
+ console.log("Answer:", answer);
273
+ } else {
274
+ console.log(fullResponse);
275
+ }
276
+ ```
277
+
278
+ ### WebGPU Notes
279
+
280
+ - Recommended: `model_q4.onnx` for best performance/quality balance
281
+ - For higher quality: `model_fp16.onnx`
282
+ - Models use external data files (`.onnx_data`) that are loaded automatically
283
+ - int64 tensors require `BigInt64Array`
284
+ - Reasoning models may generate longer outputs; adjust max tokens as needed
285
+
286
+ ## Output Format
287
+
288
+ The model produces output in two parts:
289
+
290
+ 1. **Thinking**: Internal reasoning wrapped in `<think>...</think>` tags
291
+ 2. **Answer**: The final response after the closing `</think>` tag
292
+
293
+ Example output:
294
+ ```
295
+ <think>
296
+ To calculate 25 * 37, I can break this down:
297
+ 25 * 37 = 25 * (40 - 3) = 25 * 40 - 25 * 3 = 1000 - 75 = 925
298
+ </think>
299
+ The answer is 925.
300
+ ```
301
+
302
+ ## License
303
+
304
+ This model is released under the [LFM 1.0 License](LICENSE).
chat_template.jinja ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token -}}
2
+ {%- set keep_past_thinking = keep_past_thinking | default(false) -%}
3
+ {%- set ns = namespace(system_prompt="") -%}
4
+ {%- if messages[0]["role"] == "system" -%}
5
+ {%- set ns.system_prompt = messages[0]["content"] -%}
6
+ {%- set messages = messages[1:] -%}
7
+ {%- endif -%}
8
+ {%- if tools -%}
9
+ {%- set ns.system_prompt = ns.system_prompt + ("\n" if ns.system_prompt else "") + "List of tools: [" -%}
10
+ {%- for tool in tools -%}
11
+ {%- if tool is not string -%}
12
+ {%- set tool = tool | tojson -%}
13
+ {%- endif -%}
14
+ {%- set ns.system_prompt = ns.system_prompt + tool -%}
15
+ {%- if not loop.last -%}
16
+ {%- set ns.system_prompt = ns.system_prompt + ", " -%}
17
+ {%- endif -%}
18
+ {%- endfor -%}
19
+ {%- set ns.system_prompt = ns.system_prompt + "]" -%}
20
+ {%- endif -%}
21
+ {%- if ns.system_prompt -%}
22
+ {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
23
+ {%- endif -%}
24
+ {%- set ns.last_assistant_index = -1 -%}
25
+ {%- for message in messages -%}
26
+ {%- if message["role"] == "assistant" -%}
27
+ {%- set ns.last_assistant_index = loop.index0 -%}
28
+ {%- endif -%}
29
+ {%- endfor -%}
30
+ {%- for message in messages -%}
31
+ {{- "<|im_start|>" + message["role"] + "\n" -}}
32
+ {%- set content = message["content"] -%}
33
+ {%- if content is not string -%}
34
+ {%- set content = content | tojson -%}
35
+ {%- endif -%}
36
+ {%- if message["role"] == "assistant" and not keep_past_thinking and loop.index0 != ns.last_assistant_index -%}
37
+ {%- if "</think>" in content -%}
38
+ {%- set content = content.split("</think>")[-1] | trim -%}
39
+ {%- endif -%}
40
+ {%- endif -%}
41
+ {{- content + "<|im_end|>\n" -}}
42
+ {%- endfor -%}
43
+ {%- if add_generation_prompt -%}
44
+ {{- "<|im_start|>assistant\n" -}}
45
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Lfm2ForCausalLM"
4
+ ],
5
+ "block_auto_adjust_ff_dim": true,
6
+ "block_dim": 2048,
7
+ "block_ff_dim": 12288,
8
+ "block_ffn_dim_multiplier": 1.0,
9
+ "block_mlp_init_scale": 1.0,
10
+ "block_multiple_of": 256,
11
+ "block_norm_eps": 1e-05,
12
+ "block_out_init_scale": 1.0,
13
+ "block_use_swiglu": true,
14
+ "block_use_xavier_init": true,
15
+ "bos_token_id": 1,
16
+ "conv_L_cache": 3,
17
+ "conv_bias": false,
18
+ "conv_dim": 2048,
19
+ "conv_use_xavier_init": true,
20
+ "dtype": "bfloat16",
21
+ "eos_token_id": 7,
22
+ "hidden_size": 2048,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 12288,
25
+ "layer_types": [
26
+ "conv",
27
+ "conv",
28
+ "full_attention",
29
+ "conv",
30
+ "conv",
31
+ "full_attention",
32
+ "conv",
33
+ "conv",
34
+ "full_attention",
35
+ "conv",
36
+ "full_attention",
37
+ "conv",
38
+ "full_attention",
39
+ "conv",
40
+ "full_attention",
41
+ "conv"
42
+ ],
43
+ "max_position_embeddings": 128000,
44
+ "model_type": "lfm2",
45
+ "norm_eps": 1e-05,
46
+ "num_attention_heads": 32,
47
+ "num_heads": 32,
48
+ "num_hidden_layers": 16,
49
+ "num_key_value_heads": 8,
50
+ "pad_token_id": 0,
51
+ "rope_parameters": {
52
+ "rope_theta": 1000000.0,
53
+ "rope_type": "default"
54
+ },
55
+ "tie_embedding": true,
56
+ "tie_word_embeddings": true,
57
+ "transformers_version": "5.1.0",
58
+ "use_cache": true,
59
+ "use_pos_enc": true,
60
+ "vocab_size": 65536,
61
+ "transformers.js_config": {
62
+ "use_external_data_format": {
63
+ "model.onnx": 3,
64
+ "model_fp16.onnx": 2,
65
+ "model_quantized.onnx": 1,
66
+ "model_q4.onnx": 1,
67
+ "model_q4f16.onnx": 1
68
+ },
69
+ "kv_cache_dtype": {
70
+ "q4f16": "float16",
71
+ "fp16": "float16"
72
+ }
73
+ }
74
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 7,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "5.1.0"
7
+ }
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf4a28589b70ad89e2a7bd4bb96673388c83f84e0cee024a68edd50a26452fa8
3
+ size 140810
onnx/model.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81d09021f0d84568e3cc5f8420b0940a390698db3a2dd976aa737846b73fa4f3
3
+ size 2063007744
onnx/model.onnx_data_1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fea31f1d31cae36c22dc152158929e11166d5fec564ed5ac593708e5949f6a84
3
+ size 2072240128
onnx/model.onnx_data_2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b691a34d2969fce9abed636a029951c579964d8f899d62a0d6ca43d24df2121f
3
+ size 578879488
onnx/model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:112553fae9673ec1f71aadc3530c741abed58cdead71b9c19dd5d721417f0a40
3
+ size 140027
onnx/model_fp16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e29e346d8cecb9555b4b5abb1f5ab66fca8bda6eab075505261a22bfd3d0b12
3
+ size 2067623936
onnx/model_fp16.onnx_data_1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5382e7baed997a1106686033dbf7bd31278b37ffb61ceb87de6458a0c1c79d4
3
+ size 289439744
onnx/model_q4.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5bc6cf550a03b3af4e7b4cde18760cfc5a8b68d50f6213a8c91461bb7ed5eee
3
+ size 183173
onnx/model_q4.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ac2808138dc4e1c1d4e7bf1dcde0a8551305ac827641a68360a5984c79d37ce
3
+ size 850059264
onnx/model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:047e8393e85292a885d7443509d571e25441db7c31559195b67db0b1607ab0bc
3
+ size 182795
onnx/model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da02a690901817926fe4b8cda11e3fddc42604729dd4ce62c39df53a3ec2094d
3
+ size 760279040
onnx/model_q8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff624135022dd9d9e87ae4f4ed437991b80209d776d31e9e16ad2113ae065c15
3
+ size 188702
onnx/model_q8.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8eaed4e417f4d54778d75f1da212a7aa9ef16aba46a4ae742c7127fba222586
3
+ size 1768022016
onnx/model_quantized.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:916f4d713725879067f40eac140a9b93d9a74c50c3c00bf4f9b0e88d1c247c71
3
+ size 185703
onnx/model_quantized.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20753c26acaa4ae486b5e3c9a0c7b3abd4d6608029763c9ea83cdf56aea0a4f9
3
+ size 1520558080
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "legacy": false,
8
+ "model_input_names": [
9
+ "input_ids",
10
+ "attention_mask"
11
+ ],
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "pad_token": "<|pad|>",
14
+ "sp_model_kwargs": {},
15
+ "spaces_between_special_tokens": false,
16
+ "tokenizer_class": "TokenizersBackend",
17
+ "use_default_system_prompt": false,
18
+ "use_fast": true,
19
+ "chat_template": "{{- bos_token -}}\n{%- set keep_past_thinking = keep_past_thinking | default(false) -%}\n{%- set ns = namespace(system_prompt=\"\") -%}\n{%- if messages[0][\"role\"] == \"system\" -%}\n {%- set ns.system_prompt = messages[0][\"content\"] -%}\n {%- set messages = messages[1:] -%}\n{%- endif -%}\n{%- if tools -%}\n {%- set ns.system_prompt = ns.system_prompt + (\"\\n\" if ns.system_prompt else \"\") + \"List of tools: [\" -%}\n {%- for tool in tools -%}\n {%- if tool is not string -%}\n {%- set tool = tool | tojson -%}\n {%- endif -%}\n {%- set ns.system_prompt = ns.system_prompt + tool -%}\n {%- if not loop.last -%}\n {%- set ns.system_prompt = ns.system_prompt + \", \" -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set ns.system_prompt = ns.system_prompt + \"]\" -%}\n{%- endif -%}\n{%- if ns.system_prompt -%}\n {{- \"<|im_start|>system\\n\" + ns.system_prompt + \"<|im_end|>\\n\" -}}\n{%- endif -%}\n{%- set ns.last_assistant_index = -1 -%}\n{%- for message in messages -%}\n {%- if message[\"role\"] == \"assistant\" -%}\n {%- set ns.last_assistant_index = loop.index0 -%}\n {%- endif -%}\n{%- endfor -%}\n{%- for message in messages -%}\n {{- \"<|im_start|>\" + message[\"role\"] + \"\\n\" -}}\n {%- set content = message[\"content\"] -%}\n {%- if content is not string -%}\n {%- set content = content | tojson -%}\n {%- endif -%}\n {%- if message[\"role\"] == \"assistant\" and not keep_past_thinking and loop.index0 != ns.last_assistant_index -%}\n {%- if \"</think>\" in content -%}\n {%- set content = content.split(\"</think>\")[-1] | trim -%}\n {%- endif -%}\n {%- endif -%}\n {{- content + \"<|im_end|>\\n\" -}}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{- \"<|im_start|>assistant\\n\" -}}\n{%- endif -%}"
20
+ }