Commit
da1fe36
·
0 Parent(s):

Initial commit

Browse files

Co-authored-by: EdoardoMosca <EdoardoMosca@users.noreply.huggingface.co>
Co-authored-by: Aurelien-Lac <Aurelien-Lac@users.noreply.huggingface.co>
Co-authored-by: iamleonie <iamleonie@users.noreply.huggingface.co>

Files changed (15) hide show
  1. .gitattributes +39 -0
  2. LICENSE +71 -0
  3. README.md +281 -0
  4. api.py +61 -0
  5. chat_template.jinja +125 -0
  6. config.json +119 -0
  7. hybrid.py +297 -0
  8. lfm2_vl.py +116 -0
  9. model.safetensors +3 -0
  10. modeling_d1.py +31 -0
  11. processor_config.json +39 -0
  12. prompt.py +354 -0
  13. runner.py +244 -0
  14. tokenizer.json +3 -0
  15. tokenizer_config.json +18 -0
.gitattributes ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ assets/di_pareto.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/d1-3b-smash.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ assets/ood_tasks.mp4 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,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: other
4
+ license_name: lfm1.0
5
+ license_link: LICENSE
6
+ language:
7
+ - ar
8
+ - zh
9
+ - en
10
+ - fr
11
+ - de
12
+ - hi
13
+ - id
14
+ - it
15
+ - ja
16
+ - ko
17
+ - pl
18
+ - pt
19
+ - ru
20
+ - es
21
+ - th
22
+ - vi
23
+ pipeline_tag: image-text-to-text
24
+ base_model: LiquidAI/LFM2.5-VL-3B
25
+ tags:
26
+ - liquid
27
+ - lfm2.5
28
+ - edge
29
+ - decision
30
+ - classification
31
+ - calibration
32
+ - system-one
33
+ - multimodal
34
+ ---
35
+
36
+ <div align="center">
37
+ <img
38
+ src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
39
+ alt="Liquid AI"
40
+ style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
41
+ />
42
+ <div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;">
43
+ <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
44
+ <a href="https://docs.liquid.ai/lfm/getting-started/welcome"><strong>Docs</strong></a> •
45
+ <a href="https://discord.com/invite/liquid-ai"><strong>Discord</strong></a>
46
+ </div>
47
+ </div>
48
+
49
+ # d1-3B
50
+
51
+ d1-3B is a 3B parameter **decision model** built on [LFM2.5-VL-3B](https://huggingface.co/LiquidAI/LFM2.5-VL-3B).
52
+ You give it a state (text, JSON, images, or a mix) and a set of questions. It returns calibrated,
53
+ typed answers in **one forward pass with zero output tokens**.
54
+
55
+ - **Best decision model under 10B on the Decision Index 0.2.1**: 48.57, ahead of every 4B and 9B model
56
+ and of Decider 35B-A3B (47.11).
57
+ - **Multimodal**: images and text in the same state. It scores 74.1 on 11 public image benchmarks
58
+ (LFM2.5-VL-3B: 73.9).
59
+ - **Fast**: 8 ms a decision on an NVIDIA RTX 4090, 9 ms on an AMD MI325X, 30 ms on an Apple M5 Pro.
60
+
61
+ Find more information about open d1 in our [blog post](https://www.liquid.ai/blog/open-d1).
62
+
63
+ ![image](https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/r2H7UlZ_m48SYAhZWIHiu.png)
64
+
65
+ > [!NOTE]
66
+ > 💻 **Demos**: Try d1-3B in a Hugging Face space without any setup:
67
+ > [**Open d1 Arcade**](https://huggingface.co/spaces/LiquidAI/system-one-arcade): Collection of 10 demos using d1-3B
68
+
69
+
70
+ ## 🗒️ Model Details
71
+
72
+ | Model | Parameters | Description |
73
+ |---|---|---|
74
+ | [LFM2.5-VL-3B](https://huggingface.co/LiquidAI/LFM2.5-VL-3B) | 3.1B | General-purpose vision-language model (base) |
75
+ | **[d1-3B](https://huggingface.co/LiquidAI/d1-3B)** | 3.1B | Post-trained for single-pass, calibrated decisions |
76
+
77
+ d1-3B is a multimodal decision model with the following features:
78
+
79
+ - **Total parameters**: 3.12B
80
+ - **Vision encoder**: SigLIP2 NaFlex shape-optimized 400M
81
+ - **Context length**: 32,768 tokens
82
+ - **Vocabulary size**: 128,000
83
+
84
+ We recommend d1-3B wherever a pipeline needs a yes/no, a pick from named options, or a rating:
85
+ routing and triage, moderation, intent and topic classification, extraction checks, reranking, LLM-as-a-judge
86
+ scoring, agent guardrails, and visual inspection. It is not a chat model and does not write text.
87
+
88
+ ## 🏃 How to use
89
+
90
+ Install the dependencies (requires `transformers>=5.14`):
91
+
92
+ ```bash
93
+ pip install "transformers>=5.14" torch torchvision pillow
94
+ ```
95
+
96
+ The model ships its own code, so load it with `trust_remote_code=True`:
97
+
98
+ ```python
99
+ import torch
100
+ from transformers import AutoModel
101
+ from transformers.image_utils import load_image
102
+
103
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
104
+ dtype = torch.float32 if device == "cpu" else torch.bfloat16
105
+ model = AutoModel.from_pretrained("LiquidAI/d1-3B", trust_remote_code=True, dtype=dtype).to(device)
106
+
107
+ # Text: several named questions over one state, answered in one pass
108
+ questions = {
109
+ "refund": {
110
+ "type": "noul",
111
+ "instructions": "Is the customer asking for a refund?",
112
+ },
113
+ "team": {
114
+ "type": "choice",
115
+ "instructions": "Which team should handle this?",
116
+ "criteria": {
117
+ "billing": "Charges, refunds, invoices",
118
+ "technical": "App or site faults",
119
+ "fraud": "Suspected unauthorised use",
120
+ },
121
+ },
122
+ "urgency": {
123
+ "type": "score",
124
+ "instructions": "How urgent is this?",
125
+ "criteria": ["Can wait", "Today", "Blocking the customer now"],
126
+ },
127
+ }
128
+ print(model.system_one("I was charged twice this month, please refund one of them.", questions))
129
+
130
+ # Image: the photo is the whole state
131
+ image = load_image("http://images.cocodataset.org/val2017/000000039769.jpg") # two cats on a sofa
132
+ cats = {
133
+ "type": "choice",
134
+ "instructions": "How many cats are there?",
135
+ "criteria": {"one": "One", "two": "Two", "more": "Three or more"},
136
+ }
137
+ print(model.system_one(None, {"cats": cats}, images=[image]))
138
+
139
+ # Batch: many requests, packed together with no padding
140
+ tickets = ["Where is my parcel? It was due Monday.", "The app crashes when I open settings."]
141
+ print(model.system_one_batch([(t, {"team": questions["team"]}) for t in tickets]))
142
+ ```
143
+
144
+ | call | |
145
+ |---|---|
146
+ | `system_one(state, questions, images=None)` | Named questions over one state, in one pass. The state and its images are read once for all questions. |
147
+ | `system_one_batch([(state, questions[, images]), ...])` | Many requests, packed with no padding. |
148
+
149
+ A state is a string, any JSON value, or `None` when the images are the whole state.
150
+
151
+ ### Questions and answers
152
+
153
+ Questions follow the Decision Index schema: `type`, `instructions`, and `criteria`.
154
+
155
+ | `type` | `criteria` | answer fields |
156
+ |---|---|---|
157
+ | `noul`: yes or no | optional: `{"true": "...", "false": "..."}` to define each side | `noul`: P(yes) |
158
+ | `choice`: one of named options | `{name: description}` | `choice`, `confidence`, `probabilities` |
159
+ | `score`: 2 to 10 ordered levels | a list of level descriptions, lowest first | `score` (the expected level), `confidence`, `probabilities`, `legend` |
160
+
161
+ Each call returns `{"answers": {name: answer}, "usage": {"input_tokens": n, "output_tokens": 0}}`.
162
+
163
+ ## ⚡ Speed
164
+
165
+ Warm calls, one request at a time: a single question, three questions over one state, a 3.4k-token
166
+ state and a 384 px image. The last column is throughput with 64 states packed into one pass.
167
+
168
+ ### Edge Inference
169
+
170
+ We measure latency on an Apple M5 Pro and, in collaboration with NVIDIA, on an NVIDIA Jetson AGX Thor,
171
+ a Jetson AGX Orin 64 GB and a Jetson Orin Nano.
172
+
173
+ | | one question | 3 questions, one pass | 3.4k-token state | 384 px image | 64 states, packed |
174
+ |---|---:|---:|---:|---:|---:|
175
+ | Apple M5 Pro (`mps`) | 30 ms | 41 ms | 640 ms | 62 ms | 78 / s |
176
+ | NVIDIA Jetson AGX Thor | 16 ms | 20 ms | 220 ms | 35 ms | 262 / s |
177
+ | NVIDIA Jetson AGX Orin 64 GB | 26 ms | 35 ms | 560 ms | 83 ms | 110 / s |
178
+ | NVIDIA Jetson Orin Nano | 50 ms | 73 ms | 1640 ms | 202 ms | 38 / s |
179
+
180
+ ### GPU Inference
181
+
182
+ We measure latency on an NVIDIA RTX 4090 and an AMD MI325X, in bf16, median of 20 runs.
183
+
184
+ | | one question | 3 questions, one pass | 3.4k-token state | 384 px image | 64 states, packed |
185
+ |---|---:|---:|---:|---:|---:|
186
+ | NVIDIA RTX 4090 | 8 ms | 21 ms | 102 ms | 17 ms | 475 / s |
187
+ | AMD MI325X | 9 ms | 14 ms | 44 ms | 18 ms | 1,106 / s |
188
+
189
+ On NVIDIA GPUs, `model.compile(mode="reduce-overhead")` runs single questions as CUDA graphs (the RTX 4090
190
+ row uses it). Without it, a single question takes 16 ms. The first call with a new shape pays for kernel
191
+ selection or compilation, so warm up the shapes you serve.
192
+
193
+ ## 📊 Performance
194
+
195
+ All results are on public benchmarks.
196
+
197
+ ### Decision Index 0.2.1
198
+
199
+ We scored d1-3B with the official scorer (not a leaderboard submission). All other rows come from the public leaderboard v0.2.1.
200
+
201
+ | Model | Size | Decision Index | Knowledge | Language | Retrieval | Tools | Arts |
202
+ |---|---:|---:|---:|---:|---:|---:|---:|
203
+ | Winnow-12B | 12B | 50.02 | 33.8 | 56.0 | 54.0 | 71.0 | 30.0 |
204
+ | **d1-3B** | **3B** | **48.57** | 23.8 | 56.4 | 52.8 | **74.5** | **36.3** |
205
+ | Decider 35B-A3B | 36B | 47.11 | 31.8 | 55.5 | 54.7 | 56.5 | 32.6 |
206
+ | JPT-9B | 9.7B | 46.89 | 31.7 | 56.7 | 44.6 | 67.0 | 28.6 |
207
+ | Decision 1.0 Lux | 9.7B | 43.49 | 30.9 | 48.0 | 50.0 | 57.2 | 26.4 |
208
+ | JPT-4B | 4.7B | 43.04 | 28.7 | 52.5 | 45.0 | 57.2 | 25.8 |
209
+ | Jet v6.2 | 4.7B | 42.60 | 28.7 | 43.9 | 48.2 | 62.9 | 27.0 |
210
+ | Decider 4B | 4.7B | 40.70 | 25.7 | 46.0 | 44.7 | 58.6 | 25.0 |
211
+ | Winnow-E4B | 8.0B | 39.89 | 22.3 | 45.1 | 43.8 | 62.5 | 22.8 |
212
+ | Decider 2B | 2.3B | 28.97 | 14.9 | 32.6 | 37.3 | 42.4 | 14.6 |
213
+
214
+ ### Benchmarks as decisions
215
+
216
+ Besides the Decision Index, we added a few other internal evaluations based on public benchmarks.
217
+
218
+ | Benchmark | d1-3B | Decider 4B | Decider 2B |
219
+ |---|---:|---:|---:|
220
+ | SQuAD 2.0 | **85.3** | 76.0 | 67.7 |
221
+ | Civil Comments | 93.0 | 92.8 | **93.6** |
222
+ | MASSIVE intent | 87.3 | **88.3** | 81.1 |
223
+ | HelpSteer2 | 36.7 | **42.0** | 32.0 |
224
+ | PubMedQA | **66.0** | 63.3 | 65.7 |
225
+ | BoolQ | 86.7 | **89.0** | 87.3 |
226
+ | XNLI | 85.0 | **88.6** | 85.0 |
227
+ | PAWS-X | **76.9** | 69.8 | 59.5 |
228
+ | **Mean** | **77.1** | 76.2 | 71.5 |
229
+
230
+ d1-3B also scores 71.8 on [DecisionBench](https://huggingface.co/datasets/Hanno-Labs/decision-bench) (eng v1,
231
+ all 23,900 rows) and 69.3 on [Fast Decisions](https://huggingface.co/datasets/fastino/fast-decisions)
232
+ (dev split).
233
+
234
+ ### Vision
235
+
236
+ Eleven public image benchmarks, read as decisions over each benchmark's options (at most 1,000 rows each),
237
+ compared with the base model:
238
+
239
+ | Benchmark | d1-3B | LFM2.5-VL-3B |
240
+ |---|---:|---:|
241
+ | AI2D | 79.9 | 80.9 |
242
+ | BLINK | 59.2 | 58.7 |
243
+ | CV-Bench | 82.1 | 87.6 |
244
+ | HallusionBench | 65.3 | 65.0 |
245
+ | MMBench | 84.9 | 84.3 |
246
+ | MME | 82.1 | 82.4 |
247
+ | MMStar | 59.9 | 61.2 |
248
+ | MMVP | 77.0 | 73.7 |
249
+ | POPE | 88.5 | 90.1 |
250
+ | VisualWebBench | 71.4 | 78.3 |
251
+ | VL-RewardBench | 65.0 | 50.9 |
252
+ | **Mean** | **74.1** | 73.9 |
253
+ | [ImajevBench](https://huggingface.co/datasets/mohit67890/imajev-bench) (dev and calibration, 253 rows) | 64.0 | 66.8 |
254
+
255
+ With the images removed, the same questions score 45.1, so the answers come from the images.
256
+
257
+ ## 📬 Contact
258
+
259
+ - Got questions or want to connect? [Join our Discord community](https://discord.com/invite/liquid-ai)
260
+ - If you are interested in custom solutions with edge deployment, please contact [our sales team](https://www.liquid.ai/contact).
261
+
262
+ ## Citation
263
+
264
+ ```bibtex
265
+ @article{liquidAI2026opend1,
266
+ author = {Liquid AI},
267
+ title = {Open d1: Edge decision models for text, vision, and audio},
268
+ journal = {Liquid AI Blog},
269
+ year = {2026},
270
+ note = {https://www.liquid.ai/blog/open-d1},
271
+ }
272
+ ```
273
+
274
+ ```bibtex
275
+ @article{liquidai2025lfm2,
276
+ title = {LFM2 Technical Report},
277
+ author = {Liquid AI},
278
+ journal = {arXiv preprint arXiv:2511.23404},
279
+ year = {2025}
280
+ }
281
+ ```
api.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The System One API: named questions over a state in, typed answers out.
2
+
3
+ model.system_one(state, {"refund": {"type": "noul", "instructions": "Is this a refund request?"}})
4
+ # {"answers": {"refund": {"type": "noul", "noul": p}}, "usage": {"input_tokens": n, "output_tokens": 0}}
5
+
6
+ A state is a string, any JSON value, or None with pictures alone. A question is a dict in the Decision
7
+ Index's schema (`type`, `instructions`, `criteria`) or one of `prompt`'s classes.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping, Sequence
13
+ from typing import Any
14
+
15
+ from .prompt import Choice, Noul, Question, as_question
16
+
17
+
18
+ def answer(q: Question, probs: Sequence[float]) -> dict:
19
+ """A noul's P(yes); a choice's pick and its probabilities; a score's expected level."""
20
+ if isinstance(q, Noul):
21
+ return {"type": "noul", "noul": probs[0]}
22
+ best = max(range(len(probs)), key=probs.__getitem__)
23
+ if isinstance(q, Choice):
24
+ names = list(q.criteria)
25
+ return {"type": "choice", "choice": names[best], "confidence": probs[best],
26
+ "probabilities": dict(zip(names, probs))}
27
+ return {"type": "score", "score": sum(i * p for i, p in enumerate(probs)), "confidence": probs[best],
28
+ "probabilities": {str(i): p for i, p in enumerate(probs)},
29
+ "legend": {str(i): text for i, text in enumerate(q.criteria)}}
30
+
31
+
32
+ class SystemOneApi:
33
+ """`system_one` and `system_one_batch`, and the plain probabilities under them, over a model's
34
+ `run(requests)`: each `(state, questions, images)` request's probabilities (in its questions' order)
35
+ and the tokens it read."""
36
+
37
+ def run(self, requests: Sequence[tuple[Any, list[Question], Sequence]]) -> list[tuple[list[list[float]], int]]:
38
+ raise NotImplementedError
39
+
40
+ def probabilities(self, state: Any, questions: Sequence, images: Sequence | None = None) -> list[list[float]]:
41
+ """Each question's distribution over its options (`yes`, `no` for a noul), in one pass."""
42
+ return self.run([(state, [as_question(q) for q in questions], images or ())])[0][0]
43
+
44
+ def probabilities_batch(self, requests: Sequence[tuple]) -> list[list[list[float]]]:
45
+ """`probabilities` for many `(state, questions[, images])` requests, packed as `system_one_batch`."""
46
+ reqs = [(r[0], [as_question(q) for q in r[1]], (r[2] if len(r) > 2 else None) or ()) for r in requests]
47
+ return [probs for probs, _ in self.run(reqs)]
48
+
49
+ def system_one(self, state: Any, questions: Mapping[str, Any], images: Sequence | None = None) -> dict:
50
+ """Named questions over one state, and its pictures if any, in one forward pass."""
51
+ return self.system_one_batch([(state, questions, images)])[0]
52
+
53
+ def system_one_batch(self, requests: Sequence[tuple]) -> list[dict]:
54
+ """Many `(state, questions)` or `(state, questions, images)` requests. Single-question requests
55
+ are packed together with no padding; a request with several questions reads its state once."""
56
+ named = [(r[0], {n: as_question(q) for n, q in r[1].items()}, (r[2] if len(r) > 2 else None) or ())
57
+ for r in requests]
58
+ done = self.run([(state, list(qs.values()), images) for state, qs, images in named])
59
+ return [{"answers": {n: answer(q, p) for (n, q), p in zip(qs.items(), probs)},
60
+ "usage": {"input_tokens": read, "output_tokens": 0}}
61
+ for (_, qs, _), (probs, read) in zip(named, done)]
chat_template.jinja ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 | replace("\\", "\\\\") | replace("'", "\\'") | replace("\n", "\\n") | replace("\r", "\\r")) + "'" -}}
7
+ {%- elif arg_value is mapping or arg_value is iterable -%}
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
+ {%- elif content is mapping -%}
18
+ {{- content | tojson -}}
19
+ {%- elif content is iterable -%}
20
+ {%- set _ns = namespace(result="") -%}
21
+ {%- for item in content -%}
22
+ {%- if item is string -%}
23
+ {%- set _ns.result = _ns.result + item -%}
24
+ {%- elif item is mapping and item.get("type") == "image" -%}
25
+ {%- set _ns.result = _ns.result + "<image>" -%}
26
+ {%- elif item is mapping and item.get("type") == "text" -%}
27
+ {%- set _ns.result = _ns.result + ((item.get("text") or "") | string) -%}
28
+ {%- else -%}
29
+ {%- set _ns.result = _ns.result + (item | tojson) -%}
30
+ {%- endif -%}
31
+ {%- endfor -%}
32
+ {{- _ns.result -}}
33
+ {%- endif -%}
34
+ {%- endmacro -%}
35
+
36
+ {%- macro render_tool_calls(tool_calls) -%}
37
+ {%- set tool_calls_ns = namespace(tool_calls=[]) -%}
38
+ {%- for tool_call in tool_calls -%}
39
+ {%- set func = tool_call["function"] if "function" in tool_call else tool_call -%}
40
+ {%- set func_name = func["name"] -%}
41
+ {%- set func_args = func.get("arguments") -%}
42
+ {%- set args_ns = namespace(arg_strings=[]) -%}
43
+ {%- if func_args is mapping -%}
44
+ {%- for arg_name, arg_value in func_args.items() -%}
45
+ {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%}
46
+ {%- endfor -%}
47
+ {%- elif func_args is string and (func_args | trim) not in ["", "{}", "null"] -%}
48
+ {{- raise_exception("Tool call arguments must be a mapping, got a JSON-encoded string: parse arguments with json.loads() before applying the chat template") -}}
49
+ {%- endif -%}
50
+ {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%}
51
+ {%- endfor -%}
52
+ {{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}}
53
+ {%- endmacro -%}
54
+
55
+ {%- set ns = namespace(system_prompt="", last_user_index=-1) -%}
56
+ {%- if messages and messages[0]["role"] == "system" -%}
57
+ {%- if messages[0].get("content") -%}
58
+ {%- set ns.system_prompt = parse_content(messages[0]["content"]) -%}
59
+ {%- endif -%}
60
+ {%- set messages = messages[1:] -%}
61
+ {%- endif -%}
62
+ {%- if tools -%}
63
+ {%- set ns.system_prompt = ns.system_prompt + ("\n" if ns.system_prompt else "") + "List of tools: [" -%}
64
+ {%- for tool in tools -%}
65
+ {%- if tool is not string -%}
66
+ {%- set tool = tool | tojson -%}
67
+ {%- endif -%}
68
+ {%- set ns.system_prompt = ns.system_prompt + tool -%}
69
+ {%- if not loop.last -%}
70
+ {%- set ns.system_prompt = ns.system_prompt + ", " -%}
71
+ {%- endif -%}
72
+ {%- endfor -%}
73
+ {%- set ns.system_prompt = ns.system_prompt + "]" -%}
74
+ {%- endif -%}
75
+ {%- if ns.system_prompt -%}
76
+ {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
77
+ {%- endif -%}
78
+ {%- for message in messages -%}
79
+ {%- if message["role"] == "user" -%}
80
+ {%- set ns.last_user_index = loop.index0 -%}
81
+ {%- endif -%}
82
+ {%- endfor -%}
83
+ {%- for message in messages -%}
84
+ {{- "<|im_start|>" + message.role + "\n" -}}
85
+ {%- if message.role == "assistant" -%}
86
+ {%- generation -%}
87
+ {%- set keep_thinking = preserve_thinking or loop.index0 > ns.last_user_index -%}
88
+ {%- set thinking = message.thinking or message.reasoning or message.reasoning_content -%}
89
+ {%- set thinking = thinking if thinking is string else "" -%}
90
+ {%- if thinking and keep_thinking -%}
91
+ {{- "<think>" + thinking + "</think>" -}}
92
+ {%- endif -%}
93
+ {%- set _cfm_tag = "CONTINUE_FINAL_MESSAGE_TAG " -%}
94
+ {%- set _has_cfm = false -%}
95
+ {%- set content = "" -%}
96
+ {%- if message.get("content") -%}
97
+ {%- set content = parse_content(message.content) -%}
98
+ {%- endif -%}
99
+ {%- if not keep_thinking and "</think>" in content -%}
100
+ {%- set content = content.split("</think>")[-1] | trim -%}
101
+ {%- endif -%}
102
+ {%- if content.endswith(_cfm_tag) -%}
103
+ {%- set _has_cfm = true -%}
104
+ {%- set _trunc_len = (content | length) - (_cfm_tag | length) -%}
105
+ {%- set content = content[:_trunc_len] -%}
106
+ {%- endif -%}
107
+ {{- content -}}
108
+ {%- if message.tool_calls -%}
109
+ {{- render_tool_calls(message.tool_calls) -}}
110
+ {%- endif -%}
111
+ {%- if _has_cfm -%}
112
+ {{- _cfm_tag -}}
113
+ {%- endif -%}
114
+ {{- "<|im_end|>\n" -}}
115
+ {%- endgeneration -%}
116
+ {%- else %}
117
+ {%- if message.get("content") -%}
118
+ {{- parse_content(message["content"]) -}}
119
+ {%- endif -%}
120
+ {{- "<|im_end|>\n" -}}
121
+ {%- endif %}
122
+ {%- endfor -%}
123
+ {%- if add_generation_prompt -%}
124
+ {{- "<|im_start|>assistant\n" -}}
125
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Lfm2VlForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoModel": "modeling_d1.D1Model"
7
+ },
8
+ "bos_token_id": 124894,
9
+ "do_image_splitting": true,
10
+ "do_resize": true,
11
+ "downsample_factor": 2,
12
+ "dtype": "bfloat16",
13
+ "encoder_patch_size": 16,
14
+ "eos_token_id": 124900,
15
+ "image_token_id": 124907,
16
+ "max_image_tokens": 256,
17
+ "max_num_patches": 1024,
18
+ "max_pixels_tolerance": 2.0,
19
+ "max_tiles": 10,
20
+ "min_image_tokens": 64,
21
+ "min_tiles": 2,
22
+ "model_type": "lfm2_vl",
23
+ "pad_token_id": 124893,
24
+ "projector_bias": true,
25
+ "projector_hidden_act": "gelu",
26
+ "projector_hidden_size": 2048,
27
+ "projector_use_layernorm": false,
28
+ "text_config": {
29
+ "architectures": [
30
+ "Lfm2ForCausalLM"
31
+ ],
32
+ "block__name_mlp": "parallel_mlp_merged",
33
+ "block_auto_adjust_ff_dim": false,
34
+ "block_dim": 2048,
35
+ "block_ffn_dim_multiplier": 1.0,
36
+ "block_multiple_of": 256,
37
+ "block_norm_eps": 1e-05,
38
+ "block_use_swiglu": true,
39
+ "bos_token_id": 124894,
40
+ "conv_L_cache": 3,
41
+ "conv_bias": false,
42
+ "conv_dim": 2048,
43
+ "dtype": "bfloat16",
44
+ "eos_token_id": 124900,
45
+ "full_attn_idxs": null,
46
+ "hidden_size": 2048,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 10752,
49
+ "layer_types": [
50
+ "conv",
51
+ "conv",
52
+ "full_attention",
53
+ "conv",
54
+ "conv",
55
+ "full_attention",
56
+ "conv",
57
+ "conv",
58
+ "conv",
59
+ "full_attention",
60
+ "conv",
61
+ "conv",
62
+ "conv",
63
+ "full_attention",
64
+ "conv",
65
+ "conv",
66
+ "conv",
67
+ "full_attention",
68
+ "conv",
69
+ "conv",
70
+ "conv",
71
+ "full_attention",
72
+ "conv",
73
+ "conv",
74
+ "full_attention",
75
+ "conv",
76
+ "conv",
77
+ "full_attention",
78
+ "conv",
79
+ "conv"
80
+ ],
81
+ "max_position_embeddings": 32768,
82
+ "model_type": "lfm2",
83
+ "norm_eps": 1e-05,
84
+ "num_attention_heads": 32,
85
+ "num_heads": 32,
86
+ "num_hidden_layers": 30,
87
+ "num_key_value_heads": 8,
88
+ "output_softcap": 0.0,
89
+ "pad_token_id": 124893,
90
+ "rope_parameters": {
91
+ "rope_theta": 1000000.0,
92
+ "rope_type": "default"
93
+ },
94
+ "tie_word_embeddings": true,
95
+ "use_cache": true,
96
+ "use_pos_enc": true,
97
+ "vocab_size": 128000
98
+ },
99
+ "tie_word_embeddings": true,
100
+ "tile_size": 512,
101
+ "transformers_version": "5.14.1",
102
+ "use_image_special_tokens": true,
103
+ "use_thumbnail": true,
104
+ "vision_config": {
105
+ "attention_dropout": 0.0,
106
+ "dtype": "bfloat16",
107
+ "hidden_act": "gelu_pytorch_tanh",
108
+ "hidden_size": 1152,
109
+ "intermediate_size": 4304,
110
+ "layer_norm_eps": 1e-06,
111
+ "model_type": "siglip2_vision_model",
112
+ "num_attention_heads": 16,
113
+ "num_channels": 3,
114
+ "num_hidden_layers": 27,
115
+ "num_patches": 256,
116
+ "patch_size": 16,
117
+ "vision_use_head": false
118
+ }
119
+ }
hybrid.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The pieces every LFM hybrid is made of, and the one shape that makes many
2
+ questions cost about one forward.
3
+
4
+ A model runs a batch of right-padded chains `(B, T)`, or a tree: a trunk of P
5
+ tokens (the state) and N branches (the questions) that each continue it, packed
6
+ back to back on one axis with no padding, `[trunk | branch 0 | branch 1 | ...]`.
7
+ Everything that works token by token (norms, projections, the MLP) runs once
8
+ over the packed axis. A convolution continues each branch from the trunk's last
9
+ inputs. Attention runs by parts: the trunk causally, every branch token over the
10
+ trunk in one flash call that reads the trunk's keys once for all questions
11
+ (under sliding attention, one fp32 product over the trunk's last window-1 keys),
12
+ each branch over its own tokens in one varlen flash call, the two merged by
13
+ their log-sum-exp. Nothing is cached, copied or padded.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Callable
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from transformers.modeling_layers import GradientCheckpointingLayer
24
+ from transformers.modeling_outputs import BaseModelOutputWithPast
25
+
26
+ Tensor = torch.Tensor
27
+
28
+
29
+ class Tree:
30
+ """A trunk of `p` tokens and branches of `lengths` tokens, packed on one axis."""
31
+
32
+ def __init__(self, p: int, lengths: Tensor):
33
+ self.p, self.n = p, len(lengths)
34
+ self.cu = F.pad(lengths.cumsum(0), (1, 0)).int() # where each branch starts, past the trunk
35
+ self.longest = int(lengths.max())
36
+ self.branch = torch.repeat_interleave(torch.arange(self.n, device=lengths.device), lengths)
37
+ self.offset = torch.arange(len(self.branch), device=lengths.device) - self.cu[self.branch]
38
+ # a branch starts where the trunk ends
39
+ self.positions = torch.cat((torch.arange(p, device=lengths.device), p + self.offset))
40
+ self.leaves = p + self.cu[1:].long() - 1 # each branch's last token
41
+ self._conv = {}
42
+
43
+ def conv_order(self, keep: int) -> tuple[Tensor, Tensor]:
44
+ """Gather and keep indices that run one causal conv over all branches,
45
+ each led by the trunk's last `keep` inputs. Indices are into the whole
46
+ input left-padded by `keep` zeros."""
47
+ if keep not in self._conv:
48
+ p, total, dev = self.p, len(self.branch), self.branch.device
49
+ slot = torch.arange(total, device=dev) + keep * (self.branch + 1)
50
+ order = torch.empty(total + self.n * keep, dtype=torch.long, device=dev)
51
+ order[slot] = keep + p + torch.arange(total, device=dev)
52
+ lead = (self.cu[:-1] + keep * torch.arange(self.n, device=dev))[:, None]
53
+ order[lead + torch.arange(keep, device=dev)] = p + torch.arange(keep, device=dev)
54
+ self._conv[keep] = order, slot - keep
55
+ return self._conv[keep]
56
+
57
+
58
+ # --------------------------------------------------------------------------- #
59
+ # norms and rotary
60
+ # --------------------------------------------------------------------------- #
61
+
62
+
63
+ class RMSNorm(nn.Module):
64
+ def __init__(self, dim: int, eps: float):
65
+ super().__init__()
66
+ self.weight = nn.Parameter(torch.ones(dim))
67
+ self.eps = eps
68
+
69
+ def forward(self, x: Tensor) -> Tensor:
70
+ x32 = x.float()
71
+ return (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight
72
+
73
+
74
+ def cos_sin(angles: Tensor) -> tuple[Tensor, Tensor]:
75
+ angles = torch.cat((angles, angles), dim=-1)
76
+ return angles.cos(), angles.sin()
77
+
78
+
79
+ def rotate(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
80
+ """Half-split RoPE in fp32; `cos`/`sin` broadcast over the head axis."""
81
+ x32 = x.float()
82
+ a, b = x32.chunk(2, dim=-1)
83
+ return (x32 * cos + torch.cat((-b, a), dim=-1) * sin).type_as(x)
84
+
85
+
86
+ def rope(x: Tensor, pos: Tensor, theta: float, rotated: int) -> Tensor:
87
+ """RoPE over `(B, T, H, D)` at positions `pos` `(T,)`, pairs past `rotated` left as they are."""
88
+ dim = x.shape[-1]
89
+ inv = 1.0 / theta ** (torch.arange(0, dim, 2, device=x.device).float() / dim)
90
+ inv[rotated:] = 0.0
91
+ cos, sin = cos_sin(pos.float()[:, None] * inv)
92
+ return rotate(x, cos[:, None], sin[:, None])
93
+
94
+
95
+ # --------------------------------------------------------------------------- #
96
+ # causal convolution
97
+ # --------------------------------------------------------------------------- #
98
+
99
+
100
+ def causal_conv(x: Tensor, weight: Tensor, tree: Tree | None) -> Tensor:
101
+ """Depthwise causal conv over `(B, C, T)`; a tree's branches continue its trunk."""
102
+ keep = weight.shape[-1] - 1
103
+ padded = F.pad(x, (keep, 0))
104
+ if tree is None:
105
+ return F.conv1d(padded, weight, groups=x.shape[1])
106
+ order, kept = tree.conv_order(keep)
107
+ branches = F.conv1d(padded[..., order], weight, groups=x.shape[1])[..., kept]
108
+ if tree.p == 0:
109
+ return branches
110
+ return torch.cat((F.conv1d(padded[..., : keep + tree.p], weight, groups=x.shape[1]), branches), dim=-1)
111
+
112
+
113
+ # --------------------------------------------------------------------------- #
114
+ # attention, `(B, H, T, D)`
115
+ # --------------------------------------------------------------------------- #
116
+
117
+
118
+ # queries per explicit product off the flash kernels, which bounds its fp32 scores
119
+ CHUNK = 1024
120
+
121
+
122
+ def _fused(q: Tensor) -> bool:
123
+ """Whether the flash kernels take these queries: a GPU in half precision, ROCm or CUDA from Ampere on."""
124
+ if not q.is_cuda or q.dtype not in (torch.float16, torch.bfloat16):
125
+ return False
126
+ return bool(torch.version.hip) or torch.cuda.get_device_capability(q.device)[0] >= 8
127
+
128
+
129
+ def _explicit(q: Tensor, k: Tensor, v: Tensor, allowed: Tensor | None, scale: float) -> tuple[Tensor, Tensor]:
130
+ """Attention with its log-sum-exp, in fp32, for small key sets. GQA by broadcast."""
131
+ groups = q.shape[1] // k.shape[1]
132
+ k, v = k.repeat_interleave(groups, dim=1).float(), v.repeat_interleave(groups, dim=1).float()
133
+ scores = (q.float() @ k.transpose(-1, -2)) * scale
134
+ if allowed is not None:
135
+ scores = scores.masked_fill(~allowed, float("-inf"))
136
+ return torch.softmax(scores, dim=-1).nan_to_num() @ v, torch.logsumexp(scores, dim=-1)
137
+
138
+
139
+ def _cat(parts: list[tuple[Tensor, Tensor]]) -> tuple[Tensor, Tensor]:
140
+ return torch.cat([o for o, _ in parts], dim=2), torch.cat([lse for _, lse in parts], dim=2)
141
+
142
+
143
+ def _over_trunk(q: Tensor, k: Tensor, v: Tensor, scale: float) -> tuple[Tensor, Tensor]:
144
+ """Every branch token over all of the trunk, with its log-sum-exp. Each KV
145
+ head's query group is folded into the query axis, so the trunk's keys are
146
+ read once and never repeated."""
147
+ batch, heads, length, dim = q.shape
148
+ kv = k.shape[1]
149
+ if not _fused(q):
150
+ return _cat([_explicit(part, k, v, None, scale) for part in q.split(CHUNK, dim=2)])
151
+ folded = q.reshape(batch, kv, heads // kv * length, dim)
152
+ out, lse = torch.ops.aten._scaled_dot_product_flash_attention(folded, k, v, 0.0, False, False, scale=scale)[:2]
153
+ return out.reshape(batch, heads, length, dim).float(), lse.reshape(batch, heads, length)
154
+
155
+
156
+ def _own(q: Tensor, k: Tensor, v: Tensor, tree: Tree, window: int | None, scale: float) -> tuple[Tensor, Tensor]:
157
+ """Each branch over its own tokens, causally (within `window`), with its log-sum-exp."""
158
+ if not _fused(q) and len(tree.branch) <= CHUNK: # small enough for one masked product
159
+ same, off = tree.branch[:, None] == tree.branch[None], tree.offset
160
+ allowed = same & (off[None] <= off[:, None])
161
+ if window is not None:
162
+ allowed &= off[None] > off[:, None] - window
163
+ return _explicit(q, k, v, allowed, scale)
164
+ if not _fused(q): # branch by branch: memory grows with the longest question, not with the batch
165
+ parts = []
166
+ for a, b in zip(tree.cu[:-1].tolist(), tree.cu[1:].tolist()):
167
+ off = torch.arange(b - a, device=q.device)
168
+ allowed = off[None] <= off[:, None]
169
+ if window is not None:
170
+ allowed &= off[None] > off[:, None] - window
171
+ parts.append(_explicit(q[:, :, a:b], k[:, :, a:b], v[:, :, a:b], allowed, scale))
172
+ return _cat(parts)
173
+ local = {} if window is None else {"window_size_left": window - 1, "window_size_right": 0}
174
+ out, lse = torch.ops.aten._flash_attention_forward(
175
+ *(t[0].transpose(0, 1) for t in (q, k, v)), tree.cu, tree.cu, tree.longest, tree.longest,
176
+ 0.0, True, False, scale=scale, **local)[:2]
177
+ return out.transpose(0, 1)[None].float(), lse[None]
178
+
179
+
180
+ def _merge(a: tuple[Tensor, Tensor], b: tuple[Tensor, Tensor]) -> Tensor:
181
+ (oa, la), (ob, lb) = a, b
182
+ m = torch.maximum(la, lb)
183
+ wa, wb = (la - m).exp(), (lb - m).exp()
184
+ return (oa * wa[..., None] + ob * wb[..., None]) / (wa + wb)[..., None]
185
+
186
+
187
+ def _windowed(q: Tensor, k: Tensor, v: Tensor, window: int, scale: float) -> Tensor:
188
+ """Causal attention within `window`, as local blocks: each block of `window`
189
+ queries sees its own block and the one before it."""
190
+ batch, heads, length, dim = q.shape
191
+ blocks = -(-length // window)
192
+
193
+ def split(t: Tensor) -> Tensor: # (B, H, T, D) -> (B, blocks, H, window, D)
194
+ t = F.pad(t, (0, 0, 0, blocks * window - length))
195
+ return t.reshape(batch, t.shape[1], blocks, window, dim).transpose(1, 2)
196
+
197
+ def with_previous(t: Tensor) -> Tensor:
198
+ return torch.cat((F.pad(t, (0, 0, 0, 0, 0, 0, 1, 0))[:, :-1], t), dim=3)
199
+
200
+ qb, kb, vb = split(q), with_previous(split(k)), with_previous(split(v))
201
+ qpos = torch.arange(window, device=q.device)[:, None] + window
202
+ kpos = torch.arange(2 * window, device=q.device)[None, :]
203
+ allowed = (kpos <= qpos) & (kpos > qpos - window)
204
+ first = allowed & (kpos >= window) # block 0 has no block before it
205
+ mask = torch.stack([first] + [allowed] * (blocks - 1))[:, None].repeat(batch, 1, 1, 1)
206
+ out = F.scaled_dot_product_attention(qb.flatten(0, 1), kb.flatten(0, 1), vb.flatten(0, 1),
207
+ attn_mask=mask, scale=scale, enable_gqa=True)
208
+ out = out.reshape(batch, blocks, heads, window, dim).transpose(1, 2)
209
+ return out.reshape(batch, heads, blocks * window, dim)[:, :, :length]
210
+
211
+
212
+ def causal_attention(q: Tensor, k: Tensor, v: Tensor, window: int | None, scale: float) -> Tensor:
213
+ """Right-padded chains: causal, within `window` if set."""
214
+ if window is None or q.shape[2] <= window:
215
+ return F.scaled_dot_product_attention(q, k, v, is_causal=True, scale=scale, enable_gqa=True)
216
+ return _windowed(q, k, v, window, scale)
217
+
218
+
219
+ def attention(q: Tensor, k: Tensor, v: Tensor, tree: Tree | None, window: int | None, scale: float) -> Tensor:
220
+ """Chains, or a tree: the trunk causally, each branch over the trunk and over
221
+ its own tokens."""
222
+ if tree is None:
223
+ return causal_attention(q, k, v, window, scale)
224
+ p = tree.p
225
+ qb = q[:, :, p:]
226
+ mine = _own(qb, k[:, :, p:], v[:, :, p:], tree, window, scale)
227
+ if p == 0:
228
+ return mine[0].to(q.dtype)
229
+ trunk = causal_attention(q[:, :, :p], k[:, :, :p], v[:, :, :p], window, scale)
230
+ if window is None:
231
+ seen = _over_trunk(qb, k[:, :, :p], v[:, :, :p], scale)
232
+ else: # only the trunk's last window-1 keys are in reach of a branch
233
+ tail = min(p, window - 1)
234
+ allowed = torch.arange(p - tail, p, device=q.device)[None] > tree.positions[p:, None] - window
235
+ seen = _explicit(qb, k[:, :, p - tail:p], v[:, :, p - tail:p], allowed, scale)
236
+ return torch.cat((trunk, _merge(seen, mine).to(q.dtype)), dim=2)
237
+
238
+
239
+ # --------------------------------------------------------------------------- #
240
+ # the stack
241
+ # --------------------------------------------------------------------------- #
242
+
243
+
244
+ class DecoderLayer(GradientCheckpointingLayer):
245
+ """Norm, operator (`conv` or `self_attn`), residual; norm, MLP, residual.
246
+ `sandwich` adds a norm on each branch's output."""
247
+
248
+ def __init__(self, kind: str, operator: nn.Module, mlp: nn.Module, dim: int, eps: float, sandwich: bool):
249
+ super().__init__()
250
+ self.operator_name = "conv" if kind == "conv" else "self_attn"
251
+ setattr(self, self.operator_name, operator)
252
+ self.feed_forward = mlp
253
+ self.operator_norm = RMSNorm(dim, eps)
254
+ self.ffn_norm = RMSNorm(dim, eps)
255
+ self.post_operator_norm = RMSNorm(dim, eps) if sandwich else nn.Identity()
256
+ self.post_ffn_norm = RMSNorm(dim, eps) if sandwich else nn.Identity()
257
+
258
+ def forward(self, x: Tensor, pos: Tensor, tree: Tree | None = None) -> Tensor:
259
+ h = x + self.post_operator_norm(getattr(self, self.operator_name)(self.operator_norm(x), pos, tree))
260
+ return h + self.post_ffn_norm(self.feed_forward(self.ffn_norm(h)))
261
+
262
+
263
+ class LanguageModel(nn.Module):
264
+ """Embedding, the hybrid stack and the final norm, called like HF's text models.
265
+
266
+ Rows are right-padded, so the causal operators never let a pad reach a real
267
+ token and there is no attention mask to apply.
268
+ """
269
+
270
+ def __init__(self, cfg, operator: Callable[[str], nn.Module], mlp: Callable[[], nn.Module],
271
+ eps: float, sandwich: bool = False):
272
+ super().__init__()
273
+ self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size)
274
+ self.layers = nn.ModuleList(
275
+ DecoderLayer(kind, operator(kind), mlp(), cfg.hidden_size, eps, sandwich) for kind in cfg.layer_types)
276
+ self.embedding_norm = RMSNorm(cfg.hidden_size, eps) # the final norm, despite its name
277
+
278
+ def get_input_embeddings(self) -> nn.Embedding:
279
+ return self.embed_tokens
280
+
281
+ def run(self, h: Tensor, tree: Tree | None = None) -> Tensor:
282
+ pos = tree.positions if tree is not None else torch.arange(h.shape[1], device=h.device)
283
+ for layer in self.layers:
284
+ h = layer(h, pos, tree)
285
+ return self.embedding_norm(h)
286
+
287
+ def forward(self, input_ids=None, inputs_embeds=None, **_) -> BaseModelOutputWithPast:
288
+ h = self.embed_tokens(input_ids) if inputs_embeds is None else inputs_embeds
289
+ return BaseModelOutputWithPast(last_hidden_state=self.run(h))
290
+
291
+ def answer(self, trunk: Tensor, questions: Tensor, lengths: Tensor) -> Tensor:
292
+ """Final hidden states at the last token of every question, in one pass.
293
+ `trunk` `(1, P, d)` embeddings; `questions` the ids of all questions back
294
+ to back, `(sum(lengths),)`."""
295
+ tree = Tree(trunk.shape[1], lengths)
296
+ h = self.run(torch.cat((trunk, self.embed_tokens(questions)[None]), dim=1), tree)
297
+ return h[0, tree.leaves]
lfm2_vl.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFM2-VL and LFM2 on the hybrid stack.
2
+
3
+ HF's classes stay the frame (the SigLIP2 tower, the projector, the image
4
+ features, loading and saving); only the language model is replaced, with HF's
5
+ module names, so checkpoints load and save unchanged. A state with any number
6
+ of questions runs as one `hybrid.Tree`, with the same outputs as HF's own
7
+ implementation.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from transformers import Lfm2Config, Lfm2VlConfig
16
+ from transformers.models.lfm2.modeling_lfm2 import Lfm2ForCausalLM as HfLfm2
17
+ from transformers.models.lfm2_vl.modeling_lfm2_vl import Lfm2VlForConditionalGeneration as HfLfm2Vl
18
+
19
+ from .hybrid import LanguageModel, RMSNorm, Tree, attention, causal_conv, rope
20
+
21
+
22
+ class Attention(nn.Module):
23
+ """GQA with per-head q/k norms and RoPE over the whole head."""
24
+
25
+ def __init__(self, cfg):
26
+ super().__init__()
27
+ self.heads, self.kv_heads = cfg.num_attention_heads, cfg.num_key_value_heads
28
+ self.head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // self.heads
29
+ self.q_proj = nn.Linear(cfg.hidden_size, self.heads * self.head_dim, bias=False)
30
+ self.k_proj = nn.Linear(cfg.hidden_size, self.kv_heads * self.head_dim, bias=False)
31
+ self.v_proj = nn.Linear(cfg.hidden_size, self.kv_heads * self.head_dim, bias=False)
32
+ self.out_proj = nn.Linear(self.heads * self.head_dim, cfg.hidden_size, bias=False)
33
+ self.q_layernorm = RMSNorm(self.head_dim, cfg.norm_eps)
34
+ self.k_layernorm = RMSNorm(self.head_dim, cfg.norm_eps)
35
+ self.theta = cfg.rope_parameters["rope_theta"]
36
+ self.scale = self.head_dim**-0.5
37
+
38
+ def forward(self, x: torch.Tensor, pos: torch.Tensor, tree: Tree | None) -> torch.Tensor:
39
+ batch, length, _ = x.shape
40
+ q = self.q_layernorm(self.q_proj(x).view(batch, length, self.heads, self.head_dim))
41
+ k = self.k_layernorm(self.k_proj(x).view(batch, length, self.kv_heads, self.head_dim))
42
+ v = self.v_proj(x).view(batch, length, self.kv_heads, self.head_dim)
43
+ q, k = rope(q, pos, self.theta, self.head_dim // 2), rope(k, pos, self.theta, self.head_dim // 2)
44
+ y = attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), tree, None, self.scale)
45
+ return self.out_proj(y.transpose(1, 2).flatten(2))
46
+
47
+
48
+ class ShortConv(nn.Module):
49
+ """`out(C * conv(B * x))`; HF's `nn.Conv1d` holds the taps, `causal_conv` runs them."""
50
+
51
+ def __init__(self, cfg):
52
+ super().__init__()
53
+ dim, taps = cfg.hidden_size, cfg.conv_L_cache
54
+ self.conv = nn.Conv1d(dim, dim, taps, groups=dim, bias=cfg.conv_bias, padding=taps - 1)
55
+ self.in_proj = nn.Linear(dim, 3 * dim, bias=cfg.conv_bias)
56
+ self.out_proj = nn.Linear(dim, dim, bias=cfg.conv_bias)
57
+
58
+ def forward(self, x: torch.Tensor, pos: torch.Tensor, tree: Tree | None) -> torch.Tensor:
59
+ b, c, u = self.in_proj(x).transpose(1, 2).chunk(3, dim=1)
60
+ z = causal_conv(b * u, self.conv.weight, tree)
61
+ if self.conv.bias is not None:
62
+ z = z + self.conv.bias[:, None]
63
+ return self.out_proj((c * z).transpose(1, 2))
64
+
65
+
66
+ class MLP(nn.Module):
67
+ def __init__(self, cfg):
68
+ super().__init__()
69
+ hidden = cfg.intermediate_size
70
+ if cfg.block_auto_adjust_ff_dim: # HF's sizing rule, kept exactly
71
+ hidden = int(2 * hidden / 3)
72
+ if cfg.block_ffn_dim_multiplier is not None:
73
+ hidden = int(cfg.block_ffn_dim_multiplier * hidden)
74
+ hidden = cfg.block_multiple_of * ((hidden + cfg.block_multiple_of - 1) // cfg.block_multiple_of)
75
+ self.w1 = nn.Linear(cfg.hidden_size, hidden, bias=False)
76
+ self.w3 = nn.Linear(cfg.hidden_size, hidden, bias=False)
77
+ self.w2 = nn.Linear(hidden, cfg.hidden_size, bias=False)
78
+
79
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
80
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
81
+
82
+
83
+ def language_model(cfg) -> LanguageModel:
84
+ return LanguageModel(cfg, lambda kind: ShortConv(cfg) if kind == "conv" else Attention(cfg),
85
+ lambda: MLP(cfg), cfg.norm_eps)
86
+
87
+
88
+ class Lfm2VlForConditionalGeneration(HfLfm2Vl):
89
+ """HF's LFM2-VL with the hybrid language model, under HF's name so a saved
90
+ checkpoint reads as HF's."""
91
+
92
+ def __init__(self, config: Lfm2VlConfig):
93
+ super().__init__(config)
94
+ self.model.language_model = language_model(config.text_config)
95
+
96
+ def answer(self, trunk: torch.Tensor, questions: torch.Tensor, lengths: torch.Tensor, **vision) -> torch.Tensor:
97
+ """Logits at the last token of every question, the state (and its image)
98
+ read once: `trunk` `(1, P)` ids, `questions` their ids back to back."""
99
+ embeds = self.get_input_embeddings()(trunk)
100
+ if vision:
101
+ features = torch.cat(self.model.get_image_features(**vision).pooler_output).to(embeds.dtype)
102
+ slots = self.model.get_placeholder_mask(trunk, inputs_embeds=embeds, image_features=features)
103
+ embeds = embeds.masked_scatter(slots, features)
104
+ return self.lm_head(self.model.language_model.answer(embeds, questions, lengths))
105
+
106
+
107
+ class Lfm2ForCausalLM(HfLfm2):
108
+ """HF's LFM2 with the hybrid language model, under HF's name."""
109
+
110
+ def __init__(self, config: Lfm2Config):
111
+ super().__init__(config)
112
+ self.model = language_model(config)
113
+
114
+ def answer(self, trunk: torch.Tensor, questions: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
115
+ return self.lm_head(self.model.answer(self.model.embed_tokens(trunk), questions, lengths))
116
+
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50e03317847caf6df9a9aee27ed40f20554a86a21e60d1d47ba41a422b546c0c
3
+ size 6247065504
modeling_d1.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`AutoModel.from_pretrained(repo, trust_remote_code=True)`: LFM2-VL with the System One API.
2
+
3
+ model.system_one(state, {name: question}, images=None) # one forward pass
4
+ model.system_one_batch([(state, {name: question}), ...]) # many states, packed with no padding
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping, Sequence
10
+ from functools import cached_property
11
+ from typing import Any
12
+
13
+ from .lfm2_vl import Lfm2VlForConditionalGeneration
14
+ from .runner import SystemOne
15
+
16
+
17
+ class D1Model(Lfm2VlForConditionalGeneration):
18
+ @cached_property
19
+ def engine(self) -> SystemOne:
20
+ from transformers import AutoTokenizer
21
+
22
+ return SystemOne(model=self.eval(), tokenizer=AutoTokenizer.from_pretrained(self.name_or_path))
23
+
24
+ def system_one(self, state: Any, questions: Mapping[str, Any], images: Sequence | None = None) -> dict:
25
+ """Named questions over a state (text, JSON, or None with images alone):
26
+ `{"answers": {name: answer}, "usage": {"input_tokens": n, "output_tokens": 0}}`."""
27
+ return self.engine.system_one(state, questions, images)
28
+
29
+ def system_one_batch(self, requests: Sequence[tuple]) -> list[dict]:
30
+ """`(state, questions)` or `(state, questions, images)` requests, one response each."""
31
+ return self.engine.system_one_batch(requests)
processor_config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "data_format": "channels_first",
4
+ "do_image_splitting": true,
5
+ "do_normalize": true,
6
+ "do_pad": true,
7
+ "do_rescale": true,
8
+ "do_resize": true,
9
+ "downsample_factor": 2,
10
+ "encoder_patch_size": 16,
11
+ "image_mean": [
12
+ 0.5,
13
+ 0.5,
14
+ 0.5
15
+ ],
16
+ "image_processor_type": "Lfm2VlImageProcessor",
17
+ "image_std": [
18
+ 0.5,
19
+ 0.5,
20
+ 0.5
21
+ ],
22
+ "max_image_tokens": 256,
23
+ "max_num_patches": 1024,
24
+ "max_pixels_tolerance": 2.0,
25
+ "max_tiles": 10,
26
+ "min_image_tokens": 64,
27
+ "min_tiles": 2,
28
+ "resample": 3,
29
+ "rescale_factor": 0.00392156862745098,
30
+ "return_row_col_info": true,
31
+ "size": {
32
+ "height": 512,
33
+ "width": 512
34
+ },
35
+ "tile_size": 512,
36
+ "use_thumbnail": true
37
+ },
38
+ "processor_class": "Lfm2VlProcessor"
39
+ }
prompt.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The prompt and the readout. A System One decision is a single forward pass that stops at the answer
2
+ slot: everything the model sees is built here, and the answer is a softmax over its options' tokens.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import math
9
+ import re
10
+ from dataclasses import dataclass
11
+ from functools import lru_cache
12
+ from typing import Any, Mapping, Sequence
13
+
14
+ # The system turn: none by default.
15
+ SYSTEMS: dict[str, str | None] = {
16
+ "none": None,
17
+ "isolated": (
18
+ "You are a System One decision model. Answer only the current isolated "
19
+ "question from the shared state. Other questions do not exist."
20
+ ),
21
+ }
22
+ DEFAULT_SYSTEM = "none"
23
+
24
+ IM_START = "<|im_start|>"
25
+ IM_END = "<|im_end|>"
26
+
27
+
28
+ # --------------------------------------------------------------------------- #
29
+ # question types
30
+ # --------------------------------------------------------------------------- #
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Choice:
35
+ instructions: str
36
+ criteria: Mapping[str, str | None]
37
+ type: str = "choice"
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Noul:
42
+ instructions: str
43
+ criteria: Mapping[str, Any] | None = None
44
+ type: str = "noul"
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Score:
49
+ instructions: str
50
+ criteria: Sequence[str]
51
+ type: str = "score"
52
+
53
+
54
+ Question = Choice | Noul | Score
55
+
56
+
57
+ # --------------------------------------------------------------------------- #
58
+ # verbalizer
59
+ # --------------------------------------------------------------------------- #
60
+
61
+
62
+ def option_codes(labels: Sequence[str]) -> list[str]:
63
+ """Native letters when the labels already are letters, else A..Z, else 00..; one rule for every
64
+ cardinality."""
65
+ labs = [str(x).strip() for x in labels]
66
+ if labs and all(len(k) == 1 and k.isalpha() for k in labs):
67
+ return labs
68
+ if len(labs) <= 26:
69
+ return [chr(ord("A") + i) for i in range(len(labs))]
70
+ return [f"{i:02d}" for i in range(len(labs))]
71
+
72
+
73
+ _FALLBACK_POOL = (
74
+ [chr(c) for c in range(ord("A"), ord("Z") + 1)]
75
+ + [f"{i:02d}" for i in range(100)]
76
+ + [chr(c) for c in range(ord("a"), ord("z") + 1)]
77
+ + [f"#{i}" for i in range(200)]
78
+ # Where a tokenizer splits digits, "00".."99" and "#i" are two tokens, and two capital letters are
79
+ # often one. Last in the pool, so a tokenizer with digit pairs never reaches it.
80
+ + [chr(a) + chr(b) for a in range(ord("A"), ord("Z") + 1) for b in range(ord("A"), ord("Z") + 1)]
81
+ )
82
+
83
+
84
+ @lru_cache(maxsize=4096)
85
+ def _aliases_cached(tokenizer_key: int, codes: tuple[str, ...]) -> tuple[tuple[str, int], ...]:
86
+ tokenizer = _TOKENIZERS[tokenizer_key]
87
+ used: set[int] = set()
88
+ out: list[tuple[str, int]] = []
89
+
90
+ def take(raw: str) -> bool:
91
+ enc = tokenizer.encode(raw, add_special_tokens=False)
92
+ if len(enc) != 1 or enc[0] in used:
93
+ return False
94
+ out.append((raw, enc[0]))
95
+ used.add(enc[0])
96
+ return True
97
+
98
+ for code in codes:
99
+ if take(code):
100
+ continue
101
+ if not any(take(raw) for raw in _FALLBACK_POOL):
102
+ raise RuntimeError(f"no single-token alias left for {len(codes)} options")
103
+ return tuple(out)
104
+
105
+
106
+ _TOKENIZERS: dict[int, object] = {}
107
+
108
+
109
+ def aliases(tokenizer, labels: Sequence[str]) -> list[tuple[str, int]]:
110
+ """Assign every label a distinct single-token code: [(code, token_id)].
111
+
112
+ Memoised on the codes rather than on the labels: the codes are positional
113
+ unless the labels are already letters, so every option list of one length
114
+ shares an entry.
115
+ """
116
+ _TOKENIZERS.setdefault(id(tokenizer), tokenizer)
117
+ codes = tuple(option_codes(labels))
118
+ return list(_aliases_cached(id(tokenizer), codes))
119
+
120
+
121
+ @lru_cache(maxsize=8192)
122
+ def _ids_cached(tokenizer_key: int, texts: tuple[str, ...]) -> tuple[int, ...]:
123
+ tokenizer = _TOKENIZERS[tokenizer_key]
124
+ out, seen = [], set()
125
+ for t in texts:
126
+ enc = tokenizer.encode(t, add_special_tokens=False)
127
+ if len(enc) == 1 and enc[0] not in seen:
128
+ out.append(enc[0])
129
+ seen.add(enc[0])
130
+ return tuple(out)
131
+
132
+
133
+ def _ids(tokenizer, texts: Sequence[str]) -> list[int]:
134
+ _TOKENIZERS.setdefault(id(tokenizer), tokenizer)
135
+ return list(_ids_cached(id(tokenizer), tuple(texts)))
136
+
137
+
138
+ def as_question(q: Mapping | Question) -> Question:
139
+ """A question in the Decision Index's JSON, `{"type": "noul" | "choice" | "score", "instructions",
140
+ "criteria"}`, as one of the classes above; a class passes through."""
141
+ if not isinstance(q, Mapping):
142
+ return q
143
+ kind = q.get("type", "choice")
144
+ if kind == "noul":
145
+ return Noul(q["instructions"], q.get("criteria"))
146
+ if kind == "score":
147
+ return Score(q["instructions"], list(q["criteria"]))
148
+ return Choice(q["instructions"], q["criteria"])
149
+
150
+
151
+ YES_FORMS = ("yes", "Yes", "YES")
152
+ NO_FORMS = ("no", "No", "NO")
153
+
154
+
155
+ def readout_ids(tokenizer, q: Question) -> list[list[int]]:
156
+ """Token ids to score, one group per option, max-pooled: the answer is a softmax over these and
157
+ nothing else."""
158
+ if isinstance(q, Noul):
159
+ yes, no = _ids(tokenizer, YES_FORMS), _ids(tokenizer, NO_FORMS)
160
+ if not yes or not no:
161
+ raise RuntimeError("tokenizer has no single-token yes/no")
162
+ return [yes, no]
163
+ if isinstance(q, Score):
164
+ groups = [_ids(tokenizer, [str(i)]) for i in range(len(q.criteria))]
165
+ if any(not g for g in groups):
166
+ raise RuntimeError(
167
+ f"score with {len(q.criteria)} levels needs single-token digits; "
168
+ "the primitive is defined for 2 to 10"
169
+ )
170
+ return groups
171
+ groups = []
172
+ for code, tid in aliases(tokenizer, list(q.criteria.keys())):
173
+ extra = _ids(tokenizer, [f" {code}"])
174
+ groups.append([tid] + [i for i in extra if i != tid])
175
+ if not groups:
176
+ raise RuntimeError("choice with no options")
177
+ return groups
178
+
179
+
180
+ def readout(tokenizer, q: Question, logz, calibration=None) -> list[float]:
181
+ """Option probabilities from the log-probabilities at the answer slot.
182
+
183
+ `logz` is indexed by token id: a vocabulary tensor, or a dict holding at
184
+ least the question's option tokens. Each option scores its best form.
185
+ """
186
+ scores = [max(float(logz[i]) for i in g) for g in readout_ids(tokenizer, q)]
187
+ if calibration is not None:
188
+ scores = calibration.apply(q, scores)
189
+ m = max(scores)
190
+ exps = [math.exp(s - m) for s in scores]
191
+ return [e / sum(exps) for e in exps]
192
+
193
+
194
+ # --------------------------------------------------------------------------- #
195
+ # state and question rendering
196
+ # --------------------------------------------------------------------------- #
197
+
198
+
199
+ DEFAULT_MODEL = "LiquidAI/LFM2.5-VL-3B"
200
+
201
+ # How a state is rendered: `json_only`, the default, writes every state as the object it is; `json` keeps
202
+ # three shortcuts (`Message:`, `Passage:` / `Asked:`, a lone question's text); `sections` writes nested
203
+ # states as labelled blocks.
204
+ DEFAULT_STATE_STYLE = "json_only"
205
+
206
+
207
+ def _is_scalar(v: Any) -> bool:
208
+ return v is None or isinstance(v, (str, int, float, bool)) and "\n" not in str(v)
209
+
210
+
211
+ def _sections(obj: Any, path: str, out: list[str]) -> None: # noqa: C901
212
+ """Flatten a nested state into labelled blocks, keeping real newlines.
213
+
214
+ `json.dumps` escapes every newline inside a log line or a record, so a
215
+ multi-line record would arrive as one string of `\n`; this keeps it readable.
216
+ """
217
+ head = f"[{path}]\n" if path else ""
218
+ if isinstance(obj, dict):
219
+ scalars = [(k, v) for k, v in obj.items() if _is_scalar(v)]
220
+ rest = [(k, v) for k, v in obj.items() if not _is_scalar(v)]
221
+ if scalars:
222
+ body = "\n".join(f"{k}: {'' if v is None else v}" for k, v in scalars)
223
+ out.append(f"{head}{body}")
224
+ for k, v in rest:
225
+ _sections(v, f"{path}.{k}" if path else str(k), out)
226
+ return
227
+ if isinstance(obj, (list, tuple)):
228
+ if obj and all(_is_scalar(v) for v in obj):
229
+ body = "\n".join(f"- {'' if v is None else v}" for v in obj)
230
+ out.append(f"{head}{body}")
231
+ return
232
+ for i, v in enumerate(obj, start=1):
233
+ _sections(v, f"{path} {i}/{len(obj)}" if path else f"{i}/{len(obj)}", out)
234
+ return
235
+ out.append(f"{head}{'' if obj is None else obj}")
236
+
237
+
238
+ def render_state(state: Any) -> str:
239
+ if isinstance(state, str):
240
+ return state
241
+ out: list[str] = []
242
+ _sections(state, "", out)
243
+ return "\n\n".join(out)
244
+
245
+
246
+ def state_block(state: Any, style: str = DEFAULT_STATE_STYLE) -> str:
247
+ """Flatten a state into the block that precedes QUESTION:.
248
+
249
+ Without `_only`, three shapes get a shortcut: a bare utterance becomes
250
+ `Message:`, a passage and a question `Passage:` / `Asked:`, a lone question
251
+ its text. The `_only` styles (the default) render every state as the object
252
+ it is.
253
+ """
254
+ if isinstance(state, dict) and not style.endswith("_only"):
255
+ keys = set(state.keys())
256
+ if keys == {"text"}:
257
+ return f"Message: {state['text']}\n\n"
258
+ if {"passage", "question"} <= keys and len(keys) == 2:
259
+ return f"Passage: {state['passage']}\n\nAsked: {state['question']}\n\n"
260
+ if keys == {"question"}:
261
+ return f"{state['question']}\n\n"
262
+ if style.startswith("json"):
263
+ if isinstance(state, str):
264
+ return f"{state}\n\n"
265
+ return json.dumps(state, ensure_ascii=False, indent=2) + "\n\n"
266
+ return f"{render_state(state)}\n\n"
267
+
268
+
269
+ _PLACEHOLDER = re.compile(r"^opt\d+$")
270
+
271
+
272
+ def _option_line(code: str, label: str, desc: str | None, style: str) -> str:
273
+ text = desc or label.replace("_", " ")
274
+ if style == "name_desc" and not _PLACEHOLDER.match(label) and label != text:
275
+ return f"{code} {label}: {text}"
276
+ return f"{code} {text}"
277
+
278
+
279
+ def question_block(tokenizer, q: Question, option_style: str = "desc") -> str:
280
+ if isinstance(q, Choice):
281
+ labels = list(q.criteria.keys())
282
+ codes = aliases(tokenizer, labels)
283
+ lines = "\n".join(
284
+ _option_line(codes[i][0], lab, q.criteria[lab], option_style)
285
+ for i, lab in enumerate(labels)
286
+ )
287
+ return (
288
+ f"{q.instructions}\n\nOptions:\n{lines}\n\n"
289
+ "Reply with the option code only."
290
+ )
291
+ if isinstance(q, Noul):
292
+ extra = ""
293
+ if q.criteria:
294
+ extra = f"\nYes: {q.criteria.get('true')}\nNo: {q.criteria.get('false')}"
295
+ return f"{q.instructions}{extra}\n\nReply with yes or no only."
296
+ if isinstance(q, Score):
297
+ legend = "\n".join(f"{i} {name}" for i, name in enumerate(q.criteria))
298
+ return (
299
+ f"{q.instructions}\n\n{legend}\n\n"
300
+ f"Reply with a single digit 0-{len(q.criteria) - 1} only."
301
+ )
302
+ raise TypeError(f"unknown question type {type(q)}")
303
+
304
+
305
+ def prefix_text(
306
+ tokenizer,
307
+ state: Any,
308
+ bos: str = "",
309
+ style: str = DEFAULT_STATE_STYLE,
310
+ system: str = DEFAULT_SYSTEM,
311
+ images: str = "",
312
+ ) -> str:
313
+ """Everything before the question, shared by all questions on one state: the pictures' markup
314
+ (`images`, as the chat template writes them) at the head of the user turn, then the state. With no
315
+ state (`None`) the question follows the pictures directly."""
316
+ text = SYSTEMS[system]
317
+ turn = "" if text is None else f"{IM_START}system\n{text}{IM_END}\n"
318
+ body = "" if state is None else f"{state_block(state, style)}\nQUESTION:\n"
319
+ return f"{bos}{turn}{IM_START}user\n{images}{body}"
320
+
321
+
322
+ # What sits between the assistant header and the answer slot, per model type: nothing on LFM2-VL, whose
323
+ # template opens no reasoning block.
324
+ DEFAULT_LEAD = ""
325
+ LEADS: dict[str, str] = {}
326
+
327
+
328
+ def default_lead(model_type: str | None) -> str:
329
+ """What a checkpoint's own template writes before a non-thinking answer."""
330
+ return LEADS.get(model_type, DEFAULT_LEAD)
331
+
332
+
333
+ def suffix_text(
334
+ tokenizer, q: Question, lead: str = DEFAULT_LEAD, option_style: str = "desc"
335
+ ) -> str:
336
+ """The question and the assistant header, up to the answer slot."""
337
+ body = question_block(tokenizer, q, option_style)
338
+ return f"{body}{IM_END}\n{IM_START}assistant\n{lead}"
339
+
340
+
341
+ def render(
342
+ tokenizer,
343
+ state: Any,
344
+ q: Question,
345
+ bos: str = "",
346
+ lead: str = DEFAULT_LEAD,
347
+ style: str = DEFAULT_STATE_STYLE,
348
+ system: str = DEFAULT_SYSTEM,
349
+ option_style: str = "desc",
350
+ images: str = "",
351
+ ) -> str:
352
+ return prefix_text(tokenizer, state, bos, style, system, images) + suffix_text(
353
+ tokenizer, q, lead, option_style
354
+ )
runner.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-pass typed decisions on a causal LFM backbone.
2
+
3
+ The model sees the state and the question once, and the answer is read off the
4
+ logits at the answer slot. Nothing is decoded, so a schema violation is
5
+ impossible and `tokens generated per decision` is zero.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Any, Sequence
12
+
13
+ import torch
14
+
15
+ from .api import SystemOneApi
16
+ from .lfm2_vl import Lfm2ForCausalLM, Lfm2VlForConditionalGeneration
17
+ from .prompt import (
18
+ DEFAULT_MODEL,
19
+ DEFAULT_STATE_STYLE,
20
+ DEFAULT_SYSTEM,
21
+ IM_START,
22
+ Question,
23
+ default_lead,
24
+ prefix_text,
25
+ readout,
26
+ render,
27
+ suffix_text,
28
+ )
29
+
30
+ # Every picture is bounded at this many pixels before the processor.
31
+ VISION_MAX_PIXELS = 1024 * 1024
32
+
33
+
34
+ # LFM2 models run on the hybrid stack (`hybrid.py`); any other model type through transformers as it is.
35
+ MODELS = {
36
+ "lfm2_vl": Lfm2VlForConditionalGeneration,
37
+ "lfm2": Lfm2ForCausalLM,
38
+ }
39
+
40
+
41
+ def load_backbone(model_id: str = DEFAULT_MODEL, dtype=torch.bfloat16):
42
+ """The checkpoint and its tokenizer, with SDPA attention."""
43
+ from transformers import AutoModelForImageTextToText, AutoTokenizer, PretrainedConfig
44
+
45
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
46
+ if tok.pad_token_id is None:
47
+ tok.pad_token = tok.eos_token
48
+ kind = PretrainedConfig.get_config_dict(model_id)[0].get("model_type")
49
+ cls = MODELS.get(kind, AutoModelForImageTextToText)
50
+ return cls.from_pretrained(model_id, dtype=dtype, attn_implementation="sdpa"), tok
51
+
52
+
53
+ def cap_pixels(image, max_pixels: int = VISION_MAX_PIXELS):
54
+ """A picture downscaled to at most `max_pixels`, bicubic."""
55
+ image = image.convert("RGB") if hasattr(image, "convert") else image
56
+ w, h = image.size
57
+ if w * h <= max_pixels:
58
+ return image
59
+ try:
60
+ from PIL import Image
61
+ except ImportError as e: # optional for text
62
+ raise ImportError("resizing a picture needs Pillow") from e
63
+
64
+ scale = math.sqrt(max_pixels / (w * h))
65
+ return image.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.BICUBIC)
66
+
67
+
68
+ class SystemOne(SystemOneApi):
69
+ """State in, calibrated distribution out, one forward pass."""
70
+
71
+ def __init__(
72
+ self,
73
+ model_id: str = DEFAULT_MODEL,
74
+ device: str | None = None,
75
+ calibration=None,
76
+ lead: str | None = None,
77
+ state_style: str = DEFAULT_STATE_STYLE,
78
+ system: str = DEFAULT_SYSTEM,
79
+ option_style: str = "desc",
80
+ compile: bool = False,
81
+ token_budget: int = 65536,
82
+ model=None,
83
+ tokenizer=None,
84
+ ):
85
+ """`model` and `tokenizer`, when given, are a backbone already loaded (`D1Model` passes itself);
86
+ it stays on its device unless `device` says otherwise."""
87
+ if model is None:
88
+ model, tokenizer = load_backbone(model_id)
89
+ else:
90
+ model_id, device = model.config._name_or_path, device or next(model.parameters()).device
91
+ self.model, self.tokenizer = model, tokenizer
92
+ self.model_id = model_id
93
+ if lead is None:
94
+ lead = default_lead(self.model.config.model_type)
95
+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
96
+ self.model.to(self.device).eval()
97
+ bos = getattr(self.tokenizer, "bos_token", None)
98
+ self.bos = bos if isinstance(bos, str) else ""
99
+ self.calibration = calibration
100
+ self.lead = lead
101
+ self.state_style = state_style
102
+ self.system = system
103
+ self.option_style = option_style
104
+ self.token_budget = token_budget
105
+ self.processor = None
106
+ # CUDA graphs for single questions on NVIDIA, where eager time is mostly kernel launches.
107
+ if compile and torch.version.hip:
108
+ raise ValueError("compile=True needs CUDA: on ROCm the CUDA graphs fault after a few dozen calls")
109
+ self._one_pass = (torch.compile(self.model.forward, mode="reduce-overhead")
110
+ if compile else self.model)
111
+
112
+ # ---------------------------------------------------------------- prompt
113
+
114
+ def render(self, state: Any, q: Question) -> str:
115
+ return render(
116
+ self.tokenizer, state, q, self.bos, self.lead, self.state_style,
117
+ self.system, self.option_style,
118
+ )
119
+
120
+ # --------------------------------------------------------------- forward
121
+
122
+ def _logz_ids(self, rows: list[list[int]]) -> list[torch.Tensor]:
123
+ """Log-softmax at the answer slot, one row per token list, in one pass.
124
+
125
+ The rows are one tree (`hybrid.py`): their common start is its trunk and
126
+ is read once; the rest of each row is a branch, packed with no padding.
127
+ Mathematically each row alone; in bf16 the kernels differ by batch shape.
128
+ """
129
+ if len(rows) == 1: # nothing to share: a plain chain is faster than a tree of one
130
+ row = self._one_pass(input_ids=torch.tensor(rows, device=self.device), logits_to_keep=1).logits[0, -1]
131
+ return [row.float() - torch.logsumexp(row.float(), dim=-1)]
132
+ shared = 0 # every row keeps at least its last token
133
+ while shared < min(map(len, rows)) - 1 and len({r[shared] for r in rows}) == 1:
134
+ shared += 1
135
+ return self._tree_logz(rows[0][:shared], [r[shared:] for r in rows])
136
+
137
+ def _tree_logz(self, trunk: list[int], rows: list[list[int]], **vision) -> list[torch.Tensor]:
138
+ """`trunk` then each of `rows`, read at each row's end."""
139
+ packed = torch.tensor([t for r in rows for t in r], device=self.device)
140
+ lengths = torch.tensor([len(r) for r in rows], device=self.device)
141
+ trunk = torch.tensor([trunk], dtype=torch.long, device=self.device)
142
+ logits = self.model.answer(trunk, packed, lengths, **vision).float()
143
+ return list(logits - torch.logsumexp(logits, dim=-1, keepdim=True))
144
+
145
+ def plan_batches(self, texts: Sequence[str], token_budget: int | None = None) -> list[list[int]]:
146
+ """Consecutive batches of at most `token_budget` tokens: rows are packed,
147
+ so a batch costs its real tokens."""
148
+ return self._plan([len(self.tokenizer.encode(t, add_special_tokens=False)) for t in texts], token_budget)
149
+
150
+ def _plan(self, lengths: Sequence[int], token_budget: int | None = None) -> list[list[int]]:
151
+ if not lengths:
152
+ return []
153
+ budget = token_budget or self.token_budget
154
+ out: list[list[int]] = [[]]
155
+ used = 0
156
+ for i, n in enumerate(lengths):
157
+ if out[-1] and used + n > budget:
158
+ out.append([])
159
+ used = 0
160
+ out[-1].append(i)
161
+ used += n
162
+ return out
163
+
164
+ # --------------------------------------------------------------- readout
165
+
166
+ def _readout(self, q: Question, logz: torch.Tensor) -> list[float]:
167
+ return readout(self.tokenizer, q, logz, self.calibration)
168
+
169
+ # ------------------------------------------------------------------- api
170
+
171
+ @torch.inference_mode()
172
+ def run(self, requests: Sequence[tuple[Any, list[Question], Sequence]]) -> list[tuple[list[list[float]], int]]:
173
+ """Each `(state, questions, images)` request's probabilities and the tokens it read. Requests of one
174
+ question and no pictures are packed together, one tree per token budget; any other request is its
175
+ own pass, its state (and pictures) the trunk and its questions the branches."""
176
+ out: list = [None] * len(requests)
177
+ single = [i for i, (_, qs, images) in enumerate(requests) if len(qs) == 1 and not images]
178
+ rows = [self.tokenizer.encode(self.render(requests[i][0], requests[i][1][0]), add_special_tokens=False)
179
+ for i in single]
180
+ for chunk in self._plan([len(r) for r in rows]):
181
+ for j, z in zip(chunk, self._logz_ids([rows[j] for j in chunk])):
182
+ out[single[j]] = ([self._readout(requests[single[j]][1][0], z)], len(rows[j]))
183
+ for i, (state, qs, images) in enumerate(requests):
184
+ if out[i] is None:
185
+ out[i] = self._request(state, qs, images)
186
+ return out
187
+
188
+ def _request(self, state: Any, qs: list[Question], images: Sequence) -> tuple[list[list[float]], int]:
189
+ pics = [cap_pixels(im) for im in images]
190
+ prefix = prefix_text(self.tokenizer, state, self.bos, self.state_style, self.system,
191
+ self._image_markup(len(pics)) if pics else "")
192
+ suffixes = [suffix_text(self.tokenizer, q, self.lead, self.option_style) for q in qs]
193
+ vision: dict = {}
194
+ if not pics:
195
+ trunk = self.tokenizer.encode(prefix, add_special_tokens=False)
196
+ elif len(qs) == 1: # the whole prompt in one plain pass
197
+ inputs = self._image_inputs(prefix + suffixes[0], pics)
198
+ row = self._one_pass(**inputs, logits_to_keep=1).logits[0, -1].float()
199
+ return [self._readout(qs[0], row - torch.logsumexp(row, dim=-1))], int(inputs["input_ids"].shape[1])
200
+ else:
201
+ vision = self._image_inputs(prefix, pics)
202
+ trunk = vision.pop("input_ids")[0].tolist()
203
+ vision.pop("attention_mask", None)
204
+ branches = [self.tokenizer.encode(s, add_special_tokens=False) for s in suffixes]
205
+ probs: list[list[float]] = []
206
+ for chunk in self._plan([len(b) for b in branches]):
207
+ zs = self._tree_logz(trunk, [branches[j] for j in chunk], **vision)
208
+ probs += [self._readout(qs[j], z) for j, z in zip(chunk, zs)]
209
+ return probs, len(trunk) + sum(map(len, branches))
210
+
211
+ def tokens(self, state: Any, questions: Sequence[Question]) -> int:
212
+ """The longest prompt one of `questions` makes over a text state: its state's tokens and its own."""
213
+ prefix = prefix_text(self.tokenizer, state, self.bos, self.state_style, self.system)
214
+ return len(self.tokenizer.encode(prefix, add_special_tokens=False)) + max(
215
+ len(self.tokenizer.encode(suffix_text(self.tokenizer, q, self.lead, self.option_style),
216
+ add_special_tokens=False)) for q in questions)
217
+
218
+ # ---------------------------------------------------------------- vision
219
+
220
+ def _image_markup(self, n: int) -> str:
221
+ """What the chat template writes for `n` images at the head of a user turn (`<image>` each on LFM2-VL)."""
222
+ if self.processor is None:
223
+ self.processor = self._load_processor()
224
+ msgs = [{"role": "user", "content": [*([{"type": "image"}] * n), {"type": "text", "text": "\x00"}]}]
225
+ text = self.processor.apply_chat_template(msgs, add_generation_prompt=False, tokenize=False)
226
+ head = f"{IM_START}user\n"
227
+ return text[text.index(head) + len(head):text.index("\x00")]
228
+
229
+ def _load_processor(self):
230
+ from transformers import AutoProcessor
231
+
232
+ return AutoProcessor.from_pretrained(self.model.config._name_or_path, trust_remote_code=True)
233
+
234
+ def _image_inputs(self, text: str, images: Sequence) -> dict:
235
+ """Token ids and pixel inputs for one prompt holding `images`; the prompt carries its own BOS."""
236
+ inputs = self.processor(text=[text], images=[list(images)], return_tensors="pt", add_special_tokens=False)
237
+ if "pixel_attention_mask" in inputs:
238
+ # LFM2-VL's processor pads every image to 1024 patches and the tower
239
+ # masks the padding out; cutting it gives the same answer for up to
240
+ # half the work.
241
+ n = int(inputs["pixel_attention_mask"].sum(1).max())
242
+ inputs["pixel_values"] = inputs["pixel_values"][:, :n]
243
+ inputs["pixel_attention_mask"] = inputs["pixel_attention_mask"][:, :n]
244
+ return {k: (v.to(self.device) if hasattr(v, "to") else v) for k, v in inputs.items()}
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8096ecb9f54599d756c8de728a598a340bc1e43c0deb77ddd62456c38349fcee
3
+ size 17905750
tokenizer_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "local_files_only": false,
9
+ "max_length": null,
10
+ "model_max_length": 1000000000000000019884624838656,
11
+ "pad_to_multiple_of": null,
12
+ "pad_token": "<|pad|>",
13
+ "pad_token_type_id": 0,
14
+ "padding_side": "left",
15
+ "processor_class": "Lfm2VlProcessor",
16
+ "tokenizer_class": "TokenizersBackend",
17
+ "use_default_system_prompt": false
18
+ }