lulzx commited on
Commit
ae89444
·
verified ·
1 Parent(s): 8f8fa24

feat: Initial ONNX export of LiquidAI/LFM2.5-230M

Browse files

- Full set of variants: FP32, FP16, Q4 (GatherBlockQuantized + MatMulNBits), Q4F32, Q8
- Enhanced README with standalone Python + WebGPU inference examples (inspired by LFM2.5-350M-ONNX)
- Includes tokenizer, chat template, configs
- Verified with onnxruntime generation loop

.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ onnx/model.onnx_data filter=lfs diff=lfs merge=lfs -text
37
+ onnx/model_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
38
+ onnx/model_q4.onnx_data filter=lfs diff=lfs merge=lfs -text
39
+ onnx/model_q4f32.onnx_data filter=lfs diff=lfs merge=lfs -text
40
+ onnx/model_q8.onnx_data filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LFM Open License v1.0
2
+
3
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4
+
5
+ 1. Definitions.
6
+
7
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
8
+
9
+ "Licensor" shall mean Liquid AI, Inc.
10
+
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
+
13
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
14
+
15
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
16
+
17
+ "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.
18
+
19
+ "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.
20
+
21
+ "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.
22
+
23
+ "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."
24
+
25
+ "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.
26
+
27
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
28
+
29
+ "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.
30
+
31
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
32
+
33
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
34
+
35
+ 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.
36
+
37
+ 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.
38
+
39
+ 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:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (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
46
+
47
+ (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.
48
+
49
+ 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.
50
+
51
+ 5. Commercial Use Limitation.
52
+
53
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
54
+
55
+ (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.
56
+
57
+ (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.
58
+
59
+ 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.
60
+
61
+ 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.
62
+
63
+ 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.
64
+
65
+ 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.
66
+
67
+ 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.
68
+
69
+ 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.
70
+
71
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: lfm1.0
4
+ license_link: LICENSE
5
+ language:
6
+ - en
7
+ - ar
8
+ - zh
9
+ - fr
10
+ - de
11
+ - ja
12
+ - ko
13
+ - es
14
+ - pt
15
+ - it
16
+ pipeline_tag: text-generation
17
+ tags:
18
+ - liquid
19
+ - edge
20
+ - lfm2.5
21
+ - onnx
22
+ - onnxruntime
23
+ - webgpu
24
+ - conversational
25
+ base_model:
26
+ - LiquidAI/LFM2.5-230M
27
+ ---
28
+
29
+ <div align="center">
30
+ <img
31
+ src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
32
+ alt="Liquid AI"
33
+ style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
34
+ />
35
+ <div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;">
36
+ <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
37
+ <a href="https://docs.liquid.ai/lfm/getting-started/welcome"><strong>Docs</strong></a> •
38
+ <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> •
39
+ <a href="https://discord.com/invite/liquid-ai"><strong>Discord</strong></a>
40
+ </div>
41
+ </div>
42
+ <br>
43
+
44
+ # LFM2.5-230M-ONNX
45
+
46
+ ONNX export of [LFM2.5-230M](https://huggingface.co/LiquidAI/LFM2.5-230M) for cross-platform inference.
47
+
48
+ LFM2.5 is a hybrid architecture combining multiplicative gates and short convolutions, optimized for edge deployment with fast inference on CPU, GPU, and NPU hardware.
49
+
50
+ ## Recommended Variants
51
+
52
+ | Variant | Size | Description |
53
+ |---------|---------|-------------|
54
+ | FP16 | ~455 MB | All weights in FP16 |
55
+ | Q4 | ~200 MB | INT4 embedding (GatherBlockQuantized), INT4 lm_head (MatMulNBits, shared), INT4 MatMul weights |
56
+ | Q4F32 | ~390 MB | INT4 MatMul weights, FP32 embedding and norms |
57
+ | Q8 | ~470 MB | INT8 MatMul weights, FP32 embedding and norms |
58
+
59
+ Q4 uses GatherBlockQuantized for the token embedding and MatMulNBits for the lm_head,
60
+ reusing the same quantized weights and scales. All other linear layers are quantized to
61
+ INT4 via post-export MatMulNBitsQuantizer. Block size is 32.
62
+
63
+ Q4F32 keeps the embedding as a FP32 Gather and the lm_head as FP32 Transpose + MatMul.
64
+ Only the internal linear layers (attention projections, conv projections, MLP) are
65
+ quantized to INT4 via post-export MatMulNBitsQuantizer.
66
+
67
+ Q8 is the same structure as Q4F32 but with INT8 weights (asymmetric quantization).
68
+
69
+ ## Generation Parameters
70
+
71
+ | Parameter | Value |
72
+ |---------------------|-------|
73
+ | `temperature` | 0.1 |
74
+ | `top_k` | 50 |
75
+ | `repetition_penalty`| 1.05 |
76
+
77
+ ## Model Files
78
+
79
+ ```
80
+ onnx/
81
+ ├── model.onnx # FP32
82
+ ├── model_fp16.onnx # FP16
83
+ ├── model_q4.onnx # Q4
84
+ ├── model_q4f32.onnx # Q4F32
85
+ └── model_q8.onnx # Q8
86
+ ```
87
+
88
+ ## Python
89
+
90
+ ### Installation
91
+
92
+ ```bash
93
+ pip install onnxruntime transformers numpy huggingface_hub
94
+ # or with GPU support:
95
+ pip install onnxruntime-gpu transformers numpy huggingface_hub
96
+ ```
97
+
98
+ ### Inference
99
+
100
+ ```python
101
+ import numpy as np
102
+ import onnxruntime as ort
103
+ from huggingface_hub import hf_hub_download
104
+ from transformers import AutoTokenizer
105
+
106
+ # Download model
107
+ model_id = "LiquidAI/LFM2.5-230M-ONNX"
108
+ model_path = hf_hub_download(model_id, "onnx/model_q4.onnx")
109
+ data_path = hf_hub_download(model_id, "onnx/model_q4.onnx_data")
110
+
111
+ # Load model and tokenizer
112
+ session = ort.InferenceSession(model_path)
113
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
114
+
115
+ # Sampling parameters
116
+ TEMPERATURE = 0.1
117
+ TOP_K = 50
118
+ REPETITION_PENALTY = 1.05
119
+
120
+ # Prepare chat input
121
+ messages = [{"role": "user", "content": "What is the capital of France?"}]
122
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
123
+ input_ids = np.array([tokenizer.encode(prompt, add_special_tokens=False)], dtype=np.int64)
124
+
125
+ # Initialize KV cache
126
+ ONNX_DTYPE = {"tensor(float)": np.float32, "tensor(float16)": np.float16, "tensor(int64)": np.int64}
127
+ cache = {}
128
+ for inp in session.get_inputs():
129
+ if inp.name in {"input_ids", "attention_mask", "position_ids"}:
130
+ continue
131
+ shape = [d if isinstance(d, int) else 1 for d in inp.shape]
132
+ for i, d in enumerate(inp.shape):
133
+ if isinstance(d, str) and "sequence" in d.lower():
134
+ shape[i] = 0
135
+ cache[inp.name] = np.zeros(shape, dtype=ONNX_DTYPE.get(inp.type, np.float32))
136
+
137
+ # Check if model uses position_ids
138
+ input_names = {inp.name for inp in session.get_inputs()}
139
+ use_position_ids = "position_ids" in input_names
140
+
141
+
142
+ def sample_token(logits, generated_tokens):
143
+ """Sample next token with temperature, top-k, and repetition penalty."""
144
+ # Apply repetition penalty
145
+ for token_id in set(generated_tokens):
146
+ if logits[token_id] > 0:
147
+ logits[token_id] /= REPETITION_PENALTY
148
+ else:
149
+ logits[token_id] *= REPETITION_PENALTY
150
+
151
+ # Apply temperature
152
+ logits = logits / TEMPERATURE
153
+
154
+ # Top-k filtering
155
+ top_k_indices = np.argpartition(logits, -TOP_K)[-TOP_K:]
156
+ top_k_logits = logits[top_k_indices]
157
+
158
+ # Softmax over top-k
159
+ top_k_logits -= np.max(top_k_logits)
160
+ probs = np.exp(top_k_logits) / np.sum(np.exp(top_k_logits))
161
+
162
+ # Sample
163
+ chosen = np.random.choice(len(top_k_indices), p=probs)
164
+ return int(top_k_indices[chosen])
165
+
166
+
167
+ # Generate tokens
168
+ seq_len = input_ids.shape[1]
169
+ generated_tokens = []
170
+
171
+ for step in range(512): # max tokens
172
+ if step == 0:
173
+ ids = input_ids
174
+ pos = np.arange(seq_len, dtype=np.int64).reshape(1, -1)
175
+ else:
176
+ ids = np.array([[generated_tokens[-1]]], dtype=np.int64)
177
+ pos = np.array([[seq_len + len(generated_tokens) - 1]], dtype=np.int64)
178
+
179
+ attn_mask = np.ones((1, seq_len + len(generated_tokens)), dtype=np.int64)
180
+ feed = {"input_ids": ids, "attention_mask": attn_mask, **cache}
181
+ if use_position_ids:
182
+ feed["position_ids"] = pos
183
+
184
+ outputs = session.run(None, feed)
185
+ logits = outputs[0][0, -1].copy()
186
+ next_token = sample_token(logits, generated_tokens)
187
+ generated_tokens.append(next_token)
188
+
189
+ # Update cache
190
+ for i, out in enumerate(session.get_outputs()[1:], 1):
191
+ name = out.name.replace("present_conv", "past_conv").replace("present.", "past_key_values.")
192
+ if name in cache:
193
+ cache[name] = outputs[i]
194
+
195
+ if next_token == tokenizer.eos_token_id:
196
+ break
197
+
198
+ print(tokenizer.decode(generated_tokens, skip_special_tokens=True))
199
+ ```
200
+
201
+ ## WebGPU (Browser)
202
+
203
+ ### Installation
204
+
205
+ ```bash
206
+ npm install onnxruntime-web @huggingface/transformers
207
+ ```
208
+
209
+ ### Enable WebGPU
210
+
211
+ WebGPU is required for browser inference. To enable:
212
+
213
+ 1. **Chrome/Edge**: Navigate to `chrome://flags/#enable-unsafe-webgpu`, enable, and restart
214
+ 2. **Verify**: Check `chrome://gpu` for "WebGPU" status
215
+ 3. **Test**: Run `navigator.gpu.requestAdapter()` in DevTools console
216
+
217
+ ### Inference
218
+
219
+ ```javascript
220
+ import * as ort from "onnxruntime-web/webgpu";
221
+ import { AutoTokenizer } from "@huggingface/transformers";
222
+
223
+ // Check WebGPU availability
224
+ if (!navigator.gpu) {
225
+ throw new Error("WebGPU not available. Enable at chrome://flags/#enable-unsafe-webgpu");
226
+ }
227
+ const adapter = await navigator.gpu.requestAdapter();
228
+ if (!adapter) {
229
+ throw new Error("WebGPU adapter not found. Check chrome://gpu for status.");
230
+ }
231
+
232
+ ort.env.wasm.numThreads = 1;
233
+
234
+ const modelId = "LiquidAI/LFM2.5-230M-ONNX";
235
+ const modelBase = `https://huggingface.co/${modelId}/resolve/main`;
236
+
237
+ // Load tokenizer
238
+ const tokenizer = await AutoTokenizer.from_pretrained(modelId);
239
+
240
+ // Load ONNX session with external data
241
+ const onnxPath = `${modelBase}/onnx/model_q4.onnx`;
242
+ const dataPath = `${modelBase}/onnx/model_q4.onnx_data`;
243
+ const session = await ort.InferenceSession.create(onnxPath, {
244
+ executionProviders: ["webgpu"],
245
+ externalData: [{ path: "model_q4.onnx_data", data: dataPath }],
246
+ });
247
+
248
+ // Sampling parameters
249
+ const TEMPERATURE = 0.1;
250
+ const TOP_K = 50;
251
+ const REPETITION_PENALTY = 1.05;
252
+
253
+ // Model config (from config.json)
254
+ const hiddenSize = 1024;
255
+ const numKVHeads = 8;
256
+ const headDim = 64;
257
+
258
+ // Initialize KV cache
259
+ function initCache() {
260
+ const cache = {};
261
+ for (const name of session.inputNames) {
262
+ if (name.startsWith("past_conv")) {
263
+ cache[name] = new ort.Tensor("float32", new Float32Array(hiddenSize * 3), [1, hiddenSize, 3]);
264
+ } else if (name.startsWith("past_key_values")) {
265
+ cache[name] = new ort.Tensor("float32", new Float32Array(0), [1, numKVHeads, 0, headDim]);
266
+ }
267
+ }
268
+ return cache;
269
+ }
270
+
271
+ // Update cache from outputs
272
+ function updateCache(cache, outputs) {
273
+ for (const [name, tensor] of Object.entries(outputs)) {
274
+ if (name.startsWith("present_conv")) {
275
+ cache[name.replace("present_conv", "past_conv")] = tensor;
276
+ } else if (name.startsWith("present.")) {
277
+ cache[name.replace("present.", "past_key_values.")] = tensor;
278
+ }
279
+ }
280
+ }
281
+
282
+ // Sample next token with temperature, top-k, and repetition penalty
283
+ function sampleToken(logitsData, vocabSize, generatedTokens) {
284
+ const logits = new Float32Array(logitsData);
285
+
286
+ // Apply repetition penalty
287
+ const seen = new Set(generatedTokens);
288
+ for (const tokenId of seen) {
289
+ if (logits[tokenId] > 0) {
290
+ logits[tokenId] /= REPETITION_PENALTY;
291
+ } else {
292
+ logits[tokenId] *= REPETITION_PENALTY;
293
+ }
294
+ }
295
+
296
+ // Apply temperature
297
+ for (let i = 0; i < vocabSize; i++) {
298
+ logits[i] /= TEMPERATURE;
299
+ }
300
+
301
+ // Top-k: find top K indices
302
+ const indexed = Array.from(logits.slice(0, vocabSize), (v, i) => [v, i]);
303
+ indexed.sort((a, b) => b[0] - a[0]);
304
+ const topK = indexed.slice(0, TOP_K);
305
+
306
+ // Softmax over top-k
307
+ const maxLogit = topK[0][0];
308
+ const exps = topK.map(([v, i]) => [Math.exp(v - maxLogit), i]);
309
+ const sumExp = exps.reduce((s, [e]) => s + e, 0);
310
+ const probs = exps.map(([e, i]) => [e / sumExp, i]);
311
+
312
+ // Sample from distribution
313
+ let r = Math.random();
314
+ for (const [p, i] of probs) {
315
+ r -= p;
316
+ if (r <= 0) return i;
317
+ }
318
+ return probs[probs.length - 1][1];
319
+ }
320
+
321
+ // Build prompt and tokenize
322
+ const messages = [{ role: "user", content: "What is the capital of France?" }];
323
+ const prompt = tokenizer.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
324
+ const inputIds = tokenizer.encode(prompt);
325
+
326
+ // Generation loop
327
+ const cache = initCache();
328
+ const eosTokenId = tokenizer.eos_token_id;
329
+ const generatedTokens = [];
330
+ let curLen = inputIds.length;
331
+ let ids = inputIds;
332
+
333
+ for (let step = 0; step < 512; step++) {
334
+ const inputIdsTensor = new ort.Tensor("int64", new BigInt64Array(ids.map(BigInt)), [1, ids.length]);
335
+ const attentionMask = new ort.Tensor("int64", new BigInt64Array(curLen).fill(1n), [1, curLen]);
336
+
337
+ const outputs = await session.run({ input_ids: inputIdsTensor, attention_mask: attentionMask, ...cache });
338
+
339
+ const logits = outputs.logits;
340
+ const vocabSize = logits.dims[2];
341
+ const lastLogits = logits.data.slice((logits.dims[1] - 1) * vocabSize, logits.dims[1] * vocabSize);
342
+ const nextToken = sampleToken(lastLogits, vocabSize, generatedTokens);
343
+
344
+ generatedTokens.push(nextToken);
345
+ if (nextToken === eosTokenId) break;
346
+
347
+ updateCache(cache, outputs);
348
+ ids = [nextToken];
349
+ curLen++;
350
+ }
351
+
352
+ console.log(tokenizer.decode(generatedTokens, { skip_special_tokens: true }));
353
+ ```
354
+
355
+ ### WebGPU Notes
356
+
357
+ * Models use external data files (`.onnx_data`) that are loaded automatically
358
+ * int64 tensors require `BigInt64Array`
359
+
360
+ ## Building from Source
361
+
362
+ This ONNX package was created using the official [Liquid4All/onnx-export](https://github.com/Liquid4All/onnx-export) tool (the reference exporter for all LFM2/LFM2.5 ONNX checkpoints).
363
+
364
+ ```bash
365
+ git clone https://github.com/Liquid4All/onnx-export.git
366
+ cd onnx-export
367
+ uv sync
368
+
369
+ # Export all precisions (fp16, q4, q4f32, q8) + FP32 base
370
+ uv run lfm2-export LiquidAI/LFM2.5-230M --precision
371
+ ```
372
+
373
+ The output lands in `exports/LFM2.5-230M-ONNX/`. Copy its contents (or the `onnx/` subdir + metadata) to your target repo root for publishing to the Hugging Face Hub.
374
+
375
+ The builder manually constructs the ONNX graph (using `onnx.helper`) for maximum compatibility with ONNX Runtime WebGPU, Transformers.js, and Microsoft custom ops (SimplifiedLayerNormalization, RotaryEmbedding, GroupQueryAttention, GatherBlockQuantized, MatMulNBits, etc.). Standard `torch.onnx.export` is not used.
376
+
377
+ ## License
378
+
379
+ This model is released under the [LFM 1.0 License](LICENSE).
chat_template.jinja ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token -}}
2
+ {%- set preserve_thinking = preserve_thinking | default(false) -%}
3
+
4
+ {%- macro format_arg_value(arg_value) -%}
5
+ {%- if arg_value is string -%}
6
+ {{- "'" + arg_value + "'" -}}
7
+ {%- elif arg_value is mapping -%}
8
+ {{- arg_value | tojson -}}
9
+ {%- else -%}
10
+ {{- arg_value | string -}}
11
+ {%- endif -%}
12
+ {%- endmacro -%}
13
+
14
+ {%- macro parse_content(content) -%}
15
+ {%- if content is string -%}
16
+ {{- content -}}
17
+ {%- else -%}
18
+ {%- set _ns = namespace(result="") -%}
19
+ {%- for item in content -%}
20
+ {%- if item["type"] == "image" -%}
21
+ {%- set _ns.result = _ns.result + "<image>" -%}
22
+ {%- elif item["type"] == "text" -%}
23
+ {%- set _ns.result = _ns.result + item["text"] -%}
24
+ {%- else -%}
25
+ {%- set _ns.result = _ns.result + item | tojson -%}
26
+ {%- endif -%}
27
+ {%- endfor -%}
28
+ {{- _ns.result -}}
29
+ {%- endif -%}
30
+ {%- endmacro -%}
31
+
32
+ {%- macro render_tool_calls(tool_calls) -%}
33
+ {%- set tool_calls_ns = namespace(tool_calls=[]) -%}
34
+ {%- for tool_call in tool_calls -%}
35
+ {%- set func_name = tool_call["function"]["name"] -%}
36
+ {%- set func_args = tool_call["function"]["arguments"] -%}
37
+ {%- set args_ns = namespace(arg_strings=[]) -%}
38
+ {%- for arg_name, arg_value in func_args.items() -%}
39
+ {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%}
40
+ {%- endfor -%}
41
+ {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%}
42
+ {%- endfor -%}
43
+ {{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}}
44
+ {%- endmacro -%}
45
+
46
+ {%- set ns = namespace(system_prompt="", last_user_index=-1) -%}
47
+ {%- if messages[0]["role"] == "system" -%}
48
+ {%- if messages[0].get("content") -%}
49
+ {%- set ns.system_prompt = parse_content(messages[0]["content"]) -%}
50
+ {%- endif -%}
51
+ {%- set messages = messages[1:] -%}
52
+ {%- endif -%}
53
+ {%- if tools -%}
54
+ {%- set ns.system_prompt = ns.system_prompt + ("\n" if ns.system_prompt else "") + "List of tools: [" -%}
55
+ {%- for tool in tools -%}
56
+ {%- if tool is not string -%}
57
+ {%- set tool = tool | tojson -%}
58
+ {%- endif -%}
59
+ {%- set ns.system_prompt = ns.system_prompt + tool -%}
60
+ {%- if not loop.last -%}
61
+ {%- set ns.system_prompt = ns.system_prompt + ", " -%}
62
+ {%- endif -%}
63
+ {%- endfor -%}
64
+ {%- set ns.system_prompt = ns.system_prompt + "]" -%}
65
+ {%- endif -%}
66
+ {%- if ns.system_prompt -%}
67
+ {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
68
+ {%- endif -%}
69
+ {%- for message in messages -%}
70
+ {%- if message["role"] == "user" -%}
71
+ {%- set ns.last_user_index = loop.index0 -%}
72
+ {%- endif -%}
73
+ {%- endfor -%}
74
+ {%- for message in messages -%}
75
+ {{- "<|im_start|>" + message.role + "\n" -}}
76
+ {%- if message.role == "assistant" -%}
77
+ {%- generation -%}
78
+ {%- if message.thinking is defined and (preserve_thinking or loop.index0 > ns.last_user_index) -%}
79
+ {{- "<think>" + message.thinking + "</think>" -}}
80
+ {%- endif -%}
81
+ {%- set _cfm_tag = "CONTINUE_FINAL_MESSAGE_TAG " -%}
82
+ {%- set _has_cfm = false -%}
83
+ {%- if message.content is defined -%}
84
+ {%- set content = parse_content(message.content) -%}
85
+ {%- if not (preserve_thinking or loop.index0 > ns.last_user_index) -%}
86
+ {%- if "</think>" in content -%}
87
+ {%- set content = content.split("</think>")[-1] | trim -%}
88
+ {%- endif -%}
89
+ {%- endif -%}
90
+ {%- if message.tool_calls is defined and content.endswith(_cfm_tag) -%}
91
+ {%- set _has_cfm = true -%}
92
+ {%- set _trunc_len = (content | length) - (_cfm_tag | length) -%}
93
+ {{- content[:_trunc_len] -}}
94
+ {%- else -%}
95
+ {{- content -}}
96
+ {%- endif -%}
97
+ {%- endif -%}
98
+ {%- if message.tool_calls is defined -%}
99
+ {{- render_tool_calls(message.tool_calls) -}}
100
+ {%- endif -%}
101
+ {%- if _has_cfm -%}
102
+ {{- _cfm_tag -}}
103
+ {%- endif -%}
104
+ {{- "<|im_end|>\n" -}}
105
+ {%- endgeneration -%}
106
+ {%- else %}
107
+ {%- if message.get("content") -%}
108
+ {{- parse_content(message["content"]) -}}
109
+ {%- endif -%}
110
+ {{- "<|im_end|>\n" -}}
111
+ {%- endif %}
112
+ {%- endfor -%}
113
+ {%- if add_generation_prompt -%}
114
+ {{- "<|im_start|>assistant\n" -}}
115
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Lfm2ForCausalLM"
4
+ ],
5
+ "block__name_mlp": "parallel_mlp_merged",
6
+ "block_auto_adjust_ff_dim": false,
7
+ "block_dim": 1024,
8
+ "block_ff_dim": 2560,
9
+ "block_ffn_dim_multiplier": 1.0,
10
+ "block_ffn_te_autocast": false,
11
+ "block_ffn_use_quantized_params": false,
12
+ "block_mlp_init_scale": 1.0,
13
+ "block_multiple_of": 256,
14
+ "block_norm_eps": 1e-05,
15
+ "block_out_init_scale": 1.0,
16
+ "block_sequence_parallel_norm_across_tp": false,
17
+ "block_use_swiglu": true,
18
+ "block_use_xavier_init": true,
19
+ "bos_token_id": 1,
20
+ "conv_L_cache": 3,
21
+ "conv_bias": false,
22
+ "conv_dim": 1024,
23
+ "conv_use_xavier_init": true,
24
+ "dtype": "bfloat16",
25
+ "eos_token_id": 7,
26
+ "ffn_te_autocast": false,
27
+ "ffn_use_quantized_params": false,
28
+ "hidden_size": 1024,
29
+ "initializer_range": 0.02,
30
+ "intermediate_size": 2560,
31
+ "layer_types": [
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
+ "full_attention",
43
+ "conv",
44
+ "full_attention",
45
+ "conv"
46
+ ],
47
+ "max_position_embeddings": 128000,
48
+ "model_type": "lfm2",
49
+ "norm_eps": 1e-05,
50
+ "num_attention_heads": 16,
51
+ "num_heads": 16,
52
+ "num_hidden_layers": 14,
53
+ "num_key_value_heads": 8,
54
+ "pad_token_id": 0,
55
+ "rope_parameters": {
56
+ "rope_theta": 1000000.0,
57
+ "rope_type": "default"
58
+ },
59
+ "sequence_parallel_norm_across_tp": false,
60
+ "tie_embedding": true,
61
+ "transformers_version": "5.0.0.dev0",
62
+ "use_cache": true,
63
+ "use_pos_enc": true,
64
+ "vocab_size": 65536,
65
+ "transformers.js_config": {
66
+ "kv_cache_dtype": {
67
+ "fp32": "float32"
68
+ },
69
+ "use_external_data_format": true
70
+ }
71
+ }
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": "4.54.0"
7
+ }
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f85055f79e7e0e5d4f5c1de63cc61d587d5ba080165a7b8eb3f24c1835b755b
3
+ size 128784
onnx/model.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80116563ab2f55afdaeb0d7561f0f5c2a509f5b0770a290b4f595aa4f1c32147
3
+ size 951537664
onnx/model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5f6de5c62a5f2926864c02d1cb5af7ae3b9a9a91514bd685fad4ac14d04dbee
3
+ size 133966
onnx/model_fp16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a6396228fea9a9aa7f8682fd4b666e67b88f4a84df775264f9628aba4ab8c42
3
+ size 475768832
onnx/model_q4.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82a442c44d3d143432edff57984a4e7e8da65179d3a960a170d294aed8c5dd8d
3
+ size 154010
onnx/model_q4.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b51a4580a88a2cd0486032cfdaf8694b09359abca5a97df8deb0a314ea6e5b34
3
+ size 211111936
onnx/model_q4f32.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:532477d96f2bda9f7eef984799f3c049259970bf4533c528e71fca85da283528
3
+ size 153902
onnx/model_q4f32.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecc930d0f6e2f6fc2326730b82fd25cd1542da078af0d7ee2319edb39b9be939
3
+ size 403001344
onnx/model_q8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cfeb296227815f954a1b37c7d8a65c3e8bc264ecf463fc655963ab5bdb1e074
3
+ size 167040
onnx/model_q8.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65b7e60d582227df4a0ab97cc9cd18e0a73dad718200f172fac7f080986b4ac7
3
+ size 489345024
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": true,
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 preserve_thinking = preserve_thinking | default(false) -%}\n\n{%- macro format_arg_value(arg_value) -%}\n {%- if arg_value is string -%}\n {{- \"'\" + arg_value + \"'\" -}}\n {%- elif arg_value is mapping -%}\n {{- arg_value | tojson -}}\n {%- else -%}\n {{- arg_value | string -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro parse_content(content) -%}\n {%- if content is string -%}\n {{- content -}}\n {%- else -%}\n {%- set _ns = namespace(result=\"\") -%}\n {%- for item in content -%}\n {%- if item[\"type\"] == \"image\" -%}\n {%- set _ns.result = _ns.result + \"<image>\" -%}\n {%- elif item[\"type\"] == \"text\" -%}\n {%- set _ns.result = _ns.result + item[\"text\"] -%}\n {%- else -%}\n {%- set _ns.result = _ns.result + item | tojson -%}\n {%- endif -%}\n {%- endfor -%}\n {{- _ns.result -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_tool_calls(tool_calls) -%}\n {%- set tool_calls_ns = namespace(tool_calls=[]) -%}\n {%- for tool_call in tool_calls -%}\n {%- set func_name = tool_call[\"function\"][\"name\"] -%}\n {%- set func_args = tool_call[\"function\"][\"arguments\"] -%}\n {%- set args_ns = namespace(arg_strings=[]) -%}\n {%- for arg_name, arg_value in func_args.items() -%}\n {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + \"=\" + format_arg_value(arg_value)] -%}\n {%- endfor -%}\n {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + \"(\" + (args_ns.arg_strings | join(\", \")) + \")\"] -%}\n {%- endfor -%}\n {{- \"<|tool_call_start|>[\" + (tool_calls_ns.tool_calls | join(\", \")) + \"]<|tool_call_end|>\" -}}\n{%- endmacro -%}\n\n{%- set ns = namespace(system_prompt=\"\", last_user_index=-1) -%}\n{%- if messages[0][\"role\"] == \"system\" -%}\n {%- if messages[0].get(\"content\") -%}\n {%- set ns.system_prompt = parse_content(messages[0][\"content\"]) -%}\n {%- endif -%}\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{%- for message in messages -%}\n {%- if message[\"role\"] == \"user\" -%}\n {%- set ns.last_user_index = loop.index0 -%}\n {%- endif -%}\n{%- endfor -%}\n{%- for message in messages -%}\n {{- \"<|im_start|>\" + message.role + \"\\n\" -}}\n {%- if message.role == \"assistant\" -%}\n {%- generation -%}\n {%- if message.thinking is defined and (preserve_thinking or loop.index0 > ns.last_user_index) -%}\n {{- \"<think>\" + message.thinking + \"</think>\" -}}\n {%- endif -%}\n {%- set _cfm_tag = \"CONTINUE_FINAL_MESSAGE_TAG \" -%}\n {%- set _has_cfm = false -%}\n {%- if message.content is defined -%}\n {%- set content = parse_content(message.content) -%}\n {%- if not (preserve_thinking or loop.index0 > ns.last_user_index) -%}\n {%- if \"</think>\" in content -%}\n {%- set content = content.split(\"</think>\")[-1] | trim -%}\n {%- endif -%}\n {%- endif -%}\n {%- if message.tool_calls is defined and content.endswith(_cfm_tag) -%}\n {%- set _has_cfm = true -%}\n {%- set _trunc_len = (content | length) - (_cfm_tag | length) -%}\n {{- content[:_trunc_len] -}}\n {%- else -%}\n {{- content -}}\n {%- endif -%}\n {%- endif -%}\n {%- if message.tool_calls is defined -%}\n {{- render_tool_calls(message.tool_calls) -}}\n {%- endif -%}\n {%- if _has_cfm -%}\n {{- _cfm_tag -}}\n {%- endif -%}\n {{- \"<|im_end|>\\n\" -}}\n {%- endgeneration -%}\n {%- else %}\n {%- if message.get(\"content\") -%}\n {{- parse_content(message[\"content\"]) -}}\n {%- endif -%}\n {{- \"<|im_end|>\\n\" -}}\n {%- endif %}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{- \"<|im_start|>assistant\\n\" -}}\n{%- endif -%}"
20
+ }