Image-Text-to-Text
MLX
Safetensors
lfm2_vl
mlx-vlm
lfm2
lfm2-vl
lfm2.5
decision
system-one
edge
classification
calibration
conversational
custom_code
8-bit precision
Instructions to use DJLougen/d1-3B-MLX-8bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use DJLougen/d1-3B-MLX-8bit with MLX:
# Make sure mlx-vlm is installed # pip install --upgrade mlx-vlm from mlx_vlm import load, generate from mlx_vlm.prompt_utils import apply_chat_template from mlx_vlm.utils import load_config # Load the model model, processor = load("DJLougen/d1-3B-MLX-8bit") config = load_config("DJLougen/d1-3B-MLX-8bit") # Prepare input image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] prompt = "Describe this image." # Apply chat template formatted_prompt = apply_chat_template( processor, config, prompt, num_images=1 ) # Generate output output = generate(model, processor, formatted_prompt, image) print(output) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use DJLougen/d1-3B-MLX-8bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "DJLougen/d1-3B-MLX-8bit"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "DJLougen/d1-3B-MLX-8bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Hermes Agent
How to use DJLougen/d1-3B-MLX-8bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "DJLougen/d1-3B-MLX-8bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default DJLougen/d1-3B-MLX-8bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use DJLougen/d1-3B-MLX-8bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "DJLougen/d1-3B-MLX-8bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "DJLougen/d1-3B-MLX-8bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
MLX conversion of LiquidAI/d1-3B @ da1fe36 (mlx-8bit)
Browse files- .gitattributes +1 -0
- LICENSE +71 -0
- README.md +110 -0
- api.py +61 -0
- chat_template.jinja +125 -0
- config.json +129 -0
- hybrid.py +297 -0
- lfm2_vl.py +116 -0
- model.safetensors +3 -0
- modeling_d1.py +31 -0
- processor_config.json +34 -0
- prompt.py +354 -0
- runner.py +244 -0
- system_one.py +357 -0
- tokenizer.json +3 -0
- tokenizer_config.json +18 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ 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 |
+
tokenizer.json 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,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: mlx
|
| 3 |
+
base_model: LiquidAI/d1-3B
|
| 4 |
+
license: other
|
| 5 |
+
license_name: lfm1.0
|
| 6 |
+
license_link: LICENSE
|
| 7 |
+
pipeline_tag: image-text-to-text
|
| 8 |
+
language:
|
| 9 |
+
- ar
|
| 10 |
+
- zh
|
| 11 |
+
- en
|
| 12 |
+
- fr
|
| 13 |
+
- de
|
| 14 |
+
- hi
|
| 15 |
+
- id
|
| 16 |
+
- it
|
| 17 |
+
- ja
|
| 18 |
+
- ko
|
| 19 |
+
- pl
|
| 20 |
+
- pt
|
| 21 |
+
- ru
|
| 22 |
+
- es
|
| 23 |
+
- th
|
| 24 |
+
- vi
|
| 25 |
+
tags:
|
| 26 |
+
- mlx
|
| 27 |
+
- mlx-vlm
|
| 28 |
+
- lfm2
|
| 29 |
+
- lfm2-vl
|
| 30 |
+
- lfm2.5
|
| 31 |
+
- decision
|
| 32 |
+
- system-one
|
| 33 |
+
- edge
|
| 34 |
+
- classification
|
| 35 |
+
- calibration
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
# d1-3B MLX (8-bit)
|
| 39 |
+
|
| 40 |
+
## What
|
| 41 |
+
|
| 42 |
+
An MLX-native 8-bit conversion of [LiquidAI/d1-3B](https://huggingface.co/LiquidAI/d1-3B), pinned at revision `da1fe36a861f24690f27f622dca1d8688503d113`. Upstream d1-3B is a 3B-parameter **decision model** (System One) finetuned from LiquidAI/LFM2.5-VL-3B: named questions over a state (text, JSON, or images) → calibrated typed answers in ONE forward pass. Answers are read off the logits at the answer slot — nothing is decoded, so tokens generated per decision is zero and a schema violation is impossible. Question types: `noul` (yes/no → P(yes)), `choice` (named options → pick + probabilities), `score` (ordered levels → expected level + probabilities + legend).
|
| 43 |
+
|
| 44 |
+
Model file: `model.safetensors` (3,718,720,809 bytes), 3.72 GB, 9.52 bits-per-weight average, SHA-256 `c003549c43780cdcdef9fe3af8647ddde573e7eeea816315f7718179f109cce8`.
|
| 45 |
+
|
| 46 |
+
Quantization is RTN affine (`mlx_vlm convert -q --q-bits 8 --q-group-size 64`). The **language model weights are quantized; the vision tower, multi-modal projector, and all layer norms stay BF16** (mlx-vlm's default multimodal skip), verified from the shard dtypes. This repo is the balanced option in the release; see also [DJLougen/d1-3B-MLX-bf16](https://huggingface.co/DJLougen/d1-3B-MLX-bf16) (reference/parity anchor) and [DJLougen/d1-3B-MLX-4bit](https://huggingface.co/DJLougen/d1-3B-MLX-4bit) (fastest decode, smallest).
|
| 47 |
+
|
| 48 |
+
## Why
|
| 49 |
+
|
| 50 |
+
The upstream checkpoint is distributed in transformers format for PyTorch. This conversion maps it to the MLX layout and quantizes the language model to 8-bit so Apple Silicon users can run System One decisions in 3.72 GB versus the BF16 repo's 6.25 GB.
|
| 51 |
+
|
| 52 |
+
## Why it matters
|
| 53 |
+
|
| 54 |
+
A decision model answers in a single forward pass with calibrated probabilities, so what matters is that quantization does not move the answers. The BF16 conversion itself is verified: all 707 source tensors map to the MLX layout (key remap plus 22 conv-weight transposes), shapes all match, and every BF16 tensor is bit-exact (max |diff| = 0). Functionally, the same three questions (noul + score + choice) over the same state through the upstream transformers runner (MPS, BF16) and the BF16 MLX conversion differ by at most **0.0044** in per-option probability, with identical argmax decisions everywhere. This 8-bit variant agrees with BF16 on smoke decisions (refund noul 0.9841, BF16 0.9841; team choice billing 0.9825, BF16 0.9825).
|
| 55 |
+
|
| 56 |
+
Per the upstream card: Decision Index 0.2.1 score 48.57, best decision model under 10B; scores 74.1 on 11 public image benchmarks; multimodal images+text; 16 languages; context 32,768 tokens; vision encoder SigLIP2 NaFlex. Those are upstream claims, not ours.
|
| 57 |
+
|
| 58 |
+
## Results
|
| 59 |
+
|
| 60 |
+
Local, single-machine measurement on an Apple M3 Max with 36 GB unified memory, Python 3.12, mlx 0.32.3, mlx-vlm 0.7.6, transformers 5.19.0, macOS. Greedy, warm runs. "Decision" is a single noul question over a short text state, median of n=10. Decode/prefill numbers are from a 246-token image prompt. These are local results, not a vendor benchmark.
|
| 61 |
+
|
| 62 |
+
| Metric | Value |
|
| 63 |
+
|---|---:|
|
| 64 |
+
| Decision latency (median, n=10) | 52.0 ms (51.3–53.6) |
|
| 65 |
+
| Decode tok/s (246-token image prompt) | 79.0 |
|
| 66 |
+
| Prefill tok/s | 746 |
|
| 67 |
+
| TTFT | 0.349 s |
|
| 68 |
+
| Active memory | 3.72 GB |
|
| 69 |
+
|
| 70 |
+
Decision latency is a single forward pass (no tokens generated); quantization does not speed it up much at this size (prefill-dominated). Decode tok/s scales strongly with quantization: 79.0 tok/s here versus 50.4 at BF16 and 134.0 at 4-bit.
|
| 71 |
+
|
| 72 |
+
## How to use
|
| 73 |
+
|
| 74 |
+
Install mlx 0.32.3+ and mlx-vlm 0.7.6+ on Apple Silicon. Each repo ships `system_one.py`, a faithful MLX port of the upstream transformers System One runner (prompt rendering and logit readout are identical; the forward pass goes through mlx-vlm). It supports noul / choice / score, string or JSON states, and images (capped at 1024×1024 pixels like upstream).
|
| 75 |
+
|
| 76 |
+
CLI:
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
python system_one.py --model DJLougen/d1-3B-MLX-8bit --state '<text or JSON>' --questions '<JSON>' [--image path]
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Python:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
from system_one import SystemOne
|
| 86 |
+
SystemOne("DJLougen/d1-3B-MLX-8bit").system_one(state, questions, images)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Plain generation with mlx-vlm:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
python -m mlx_vlm.generate \
|
| 93 |
+
--model DJLougen/d1-3B-MLX-8bit \
|
| 94 |
+
--image image.jpg --prompt "Describe this image." --max-tokens 128
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Note: one forward pass is made **per question** (upstream packs several questions of one state into a shared trunk with no padding — same answers, more compute). A `calibration` hook exists but no calibration data ships with these repos.
|
| 98 |
+
|
| 99 |
+
## Known issues
|
| 100 |
+
|
| 101 |
+
- Quantization is RTN (no AWQ/GPTQ calibration); the vision tower stays BF16.
|
| 102 |
+
- The helper re-reads the state once per question; upstream's packed-tree batching is not ported.
|
| 103 |
+
- Decision latency was measured on short text states only; no long-context decision measurements.
|
| 104 |
+
- Generation numbers are from one machine (M3 Max 36 GB), short prompts, greedy; not a vendor benchmark.
|
| 105 |
+
- d1-3B is a decision model, not a chat model; the backbone can generate but that is not its purpose.
|
| 106 |
+
- The upstream `.py` files (modeling_d1.py, runner.py, prompt.py, api.py, hybrid.py, lfm2_vl.py) are copied into each repo for provenance; they are transformers code and inert for mlx-vlm.
|
| 107 |
+
|
| 108 |
+
## License
|
| 109 |
+
|
| 110 |
+
The weights and associated upstream-derived model artifacts are distributed under Liquid AI's [LFM Open License v1.0](LICENSE), as required by the upstream d1-3B repository. The verbatim LICENSE file (10,574 bytes) is included in this repo.
|
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,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"quantization": {
|
| 29 |
+
"group_size": 64,
|
| 30 |
+
"bits": 8,
|
| 31 |
+
"mode": "affine"
|
| 32 |
+
},
|
| 33 |
+
"quantization_config": {
|
| 34 |
+
"group_size": 64,
|
| 35 |
+
"bits": 8,
|
| 36 |
+
"mode": "affine"
|
| 37 |
+
},
|
| 38 |
+
"text_config": {
|
| 39 |
+
"architectures": [
|
| 40 |
+
"Lfm2ForCausalLM"
|
| 41 |
+
],
|
| 42 |
+
"block__name_mlp": "parallel_mlp_merged",
|
| 43 |
+
"block_auto_adjust_ff_dim": false,
|
| 44 |
+
"block_dim": 2048,
|
| 45 |
+
"block_ffn_dim_multiplier": 1.0,
|
| 46 |
+
"block_multiple_of": 256,
|
| 47 |
+
"block_norm_eps": 1e-05,
|
| 48 |
+
"block_use_swiglu": true,
|
| 49 |
+
"bos_token_id": 124894,
|
| 50 |
+
"conv_L_cache": 3,
|
| 51 |
+
"conv_bias": false,
|
| 52 |
+
"conv_dim": 2048,
|
| 53 |
+
"dtype": "bfloat16",
|
| 54 |
+
"eos_token_id": 124900,
|
| 55 |
+
"full_attn_idxs": null,
|
| 56 |
+
"hidden_size": 2048,
|
| 57 |
+
"initializer_range": 0.02,
|
| 58 |
+
"intermediate_size": 10752,
|
| 59 |
+
"layer_types": [
|
| 60 |
+
"conv",
|
| 61 |
+
"conv",
|
| 62 |
+
"full_attention",
|
| 63 |
+
"conv",
|
| 64 |
+
"conv",
|
| 65 |
+
"full_attention",
|
| 66 |
+
"conv",
|
| 67 |
+
"conv",
|
| 68 |
+
"conv",
|
| 69 |
+
"full_attention",
|
| 70 |
+
"conv",
|
| 71 |
+
"conv",
|
| 72 |
+
"conv",
|
| 73 |
+
"full_attention",
|
| 74 |
+
"conv",
|
| 75 |
+
"conv",
|
| 76 |
+
"conv",
|
| 77 |
+
"full_attention",
|
| 78 |
+
"conv",
|
| 79 |
+
"conv",
|
| 80 |
+
"conv",
|
| 81 |
+
"full_attention",
|
| 82 |
+
"conv",
|
| 83 |
+
"conv",
|
| 84 |
+
"full_attention",
|
| 85 |
+
"conv",
|
| 86 |
+
"conv",
|
| 87 |
+
"full_attention",
|
| 88 |
+
"conv",
|
| 89 |
+
"conv"
|
| 90 |
+
],
|
| 91 |
+
"max_position_embeddings": 32768,
|
| 92 |
+
"model_type": "lfm2",
|
| 93 |
+
"norm_eps": 1e-05,
|
| 94 |
+
"num_attention_heads": 32,
|
| 95 |
+
"num_heads": 32,
|
| 96 |
+
"num_hidden_layers": 30,
|
| 97 |
+
"num_key_value_heads": 8,
|
| 98 |
+
"output_softcap": 0.0,
|
| 99 |
+
"pad_token_id": 124893,
|
| 100 |
+
"rope_parameters": {
|
| 101 |
+
"rope_theta": 1000000.0,
|
| 102 |
+
"rope_type": "default"
|
| 103 |
+
},
|
| 104 |
+
"tie_word_embeddings": true,
|
| 105 |
+
"use_cache": true,
|
| 106 |
+
"use_pos_enc": true,
|
| 107 |
+
"vocab_size": 128000
|
| 108 |
+
},
|
| 109 |
+
"tie_word_embeddings": true,
|
| 110 |
+
"tile_size": 512,
|
| 111 |
+
"transformers_version": "5.14.1",
|
| 112 |
+
"use_image_special_tokens": true,
|
| 113 |
+
"use_thumbnail": true,
|
| 114 |
+
"vision_config": {
|
| 115 |
+
"attention_dropout": 0.0,
|
| 116 |
+
"dtype": "bfloat16",
|
| 117 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 118 |
+
"hidden_size": 1152,
|
| 119 |
+
"intermediate_size": 4304,
|
| 120 |
+
"layer_norm_eps": 1e-06,
|
| 121 |
+
"model_type": "siglip2_vision_model",
|
| 122 |
+
"num_attention_heads": 16,
|
| 123 |
+
"num_channels": 3,
|
| 124 |
+
"num_hidden_layers": 27,
|
| 125 |
+
"num_patches": 256,
|
| 126 |
+
"patch_size": 16,
|
| 127 |
+
"vision_use_head": false
|
| 128 |
+
}
|
| 129 |
+
}
|
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:c003549c43780cdcdef9fe3af8647ddde573e7eeea816315f7718179f109cce8
|
| 3 |
+
size 3718720809
|
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,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"image_processor": {
|
| 3 |
+
"do_image_splitting": true,
|
| 4 |
+
"do_normalize": true,
|
| 5 |
+
"do_pad": true,
|
| 6 |
+
"do_rescale": true,
|
| 7 |
+
"do_resize": true,
|
| 8 |
+
"downsample_factor": 2,
|
| 9 |
+
"encoder_patch_size": 16,
|
| 10 |
+
"image_mean": [
|
| 11 |
+
0.5,
|
| 12 |
+
0.5,
|
| 13 |
+
0.5
|
| 14 |
+
],
|
| 15 |
+
"image_processor_type": "Lfm2VlNumpyImageProcessor",
|
| 16 |
+
"image_std": [
|
| 17 |
+
0.5,
|
| 18 |
+
0.5,
|
| 19 |
+
0.5
|
| 20 |
+
],
|
| 21 |
+
"max_image_tokens": 256,
|
| 22 |
+
"max_num_patches": 1024,
|
| 23 |
+
"max_pixels_tolerance": 2.0,
|
| 24 |
+
"max_tiles": 10,
|
| 25 |
+
"min_image_tokens": 64,
|
| 26 |
+
"min_tiles": 2,
|
| 27 |
+
"patch_size": 16,
|
| 28 |
+
"resample": 3,
|
| 29 |
+
"rescale_factor": 0.00392156862745098,
|
| 30 |
+
"tile_size": 512,
|
| 31 |
+
"use_thumbnail": true
|
| 32 |
+
},
|
| 33 |
+
"processor_class": "Lfm2VlProcessor"
|
| 34 |
+
}
|
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()}
|
system_one.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""System One decisions on Apple Silicon: one forward pass, typed answers.
|
| 2 |
+
|
| 3 |
+
A faithful MLX port of the transformers System One runner that ships with
|
| 4 |
+
LiquidAI/d1-3B (`prompt.py`, `runner.py`, `api.py`). The prompt rendering and
|
| 5 |
+
the logit readout are identical; the forward pass runs through mlx-vlm.
|
| 6 |
+
|
| 7 |
+
python system_one.py --model DJLougen/d1-3B-MLX-bf16 \
|
| 8 |
+
--state '{"text": "I was charged twice this month, please refund one of them."}' \
|
| 9 |
+
--questions '{"refund": {"type": "noul", "instructions": "Is this a refund request?"}}'
|
| 10 |
+
|
| 11 |
+
The model sees the state and the question once, and the answer is read off the
|
| 12 |
+
logits at the answer slot. Nothing is decoded, so a schema violation is
|
| 13 |
+
impossible and tokens generated per decision is zero.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import sys
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any, Mapping, Sequence
|
| 25 |
+
|
| 26 |
+
# --------------------------------------------------------------------------- #
|
| 27 |
+
# question types (Decision Index JSON schema)
|
| 28 |
+
# --------------------------------------------------------------------------- #
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class Choice:
|
| 33 |
+
instructions: str
|
| 34 |
+
criteria: Mapping[str, str | None]
|
| 35 |
+
type: str = "choice"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass(frozen=True)
|
| 39 |
+
class Noul:
|
| 40 |
+
instructions: str
|
| 41 |
+
criteria: Mapping[str, Any] | None = None
|
| 42 |
+
type: str = "noul"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass(frozen=True)
|
| 46 |
+
class Score:
|
| 47 |
+
instructions: str
|
| 48 |
+
criteria: Sequence[str]
|
| 49 |
+
type: str = "score"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
Question = Choice | Noul | Score
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def as_question(q: Mapping | Question) -> Question:
|
| 56 |
+
"""`{"type": "noul" | "choice" | "score", "instructions", "criteria"}` as a class; a class passes through."""
|
| 57 |
+
if not isinstance(q, Mapping):
|
| 58 |
+
return q
|
| 59 |
+
kind = q.get("type", "choice")
|
| 60 |
+
if kind == "noul":
|
| 61 |
+
return Noul(q["instructions"], q.get("criteria"))
|
| 62 |
+
if kind == "score":
|
| 63 |
+
return Score(q["instructions"], list(q["criteria"]))
|
| 64 |
+
return Choice(q["instructions"], q["criteria"])
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# --------------------------------------------------------------------------- #
|
| 68 |
+
# verbalizer: option -> single-token ids
|
| 69 |
+
# --------------------------------------------------------------------------- #
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def option_codes(labels: Sequence[str]) -> list[str]:
|
| 73 |
+
"""Native letters when the labels already are letters, else A..Z, else 00.."""
|
| 74 |
+
labs = [str(x).strip() for x in labels]
|
| 75 |
+
if labs and all(len(k) == 1 and k.isalpha() for k in labs):
|
| 76 |
+
return labs
|
| 77 |
+
if len(labs) <= 26:
|
| 78 |
+
return [chr(ord("A") + i) for i in range(len(labs))]
|
| 79 |
+
return [f"{i:02d}" for i in range(len(labs))]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
_FALLBACK_POOL = (
|
| 83 |
+
[chr(c) for c in range(ord("A"), ord("Z") + 1)]
|
| 84 |
+
+ [f"{i:02d}" for i in range(100)]
|
| 85 |
+
+ [chr(c) for c in range(ord("a"), ord("z") + 1)]
|
| 86 |
+
+ [f"#{i}" for i in range(200)]
|
| 87 |
+
+ [chr(a) + chr(b) for a in range(ord("A"), ord("Z") + 1) for b in range(ord("A"), ord("Z") + 1)]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def aliases(tokenizer, labels: Sequence[str]) -> list[tuple[str, int]]:
|
| 92 |
+
"""Assign every label a distinct single-token code: [(code, token_id)]."""
|
| 93 |
+
used: set[int] = set()
|
| 94 |
+
out: list[tuple[str, int]] = []
|
| 95 |
+
|
| 96 |
+
def take(raw: str) -> bool:
|
| 97 |
+
enc = tokenizer.encode(raw, add_special_tokens=False)
|
| 98 |
+
if len(enc) != 1 or enc[0] in used:
|
| 99 |
+
return False
|
| 100 |
+
out.append((raw, enc[0]))
|
| 101 |
+
used.add(enc[0])
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
for code in option_codes(labels):
|
| 105 |
+
if take(code):
|
| 106 |
+
continue
|
| 107 |
+
if not any(take(raw) for raw in _FALLBACK_POOL):
|
| 108 |
+
raise RuntimeError(f"no single-token alias left for {len(option_codes(labels))} options")
|
| 109 |
+
return out
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _ids(tokenizer, texts: Sequence[str]) -> list[int]:
|
| 113 |
+
"""Single-token ids for the texts that encode to one token, deduped, in order."""
|
| 114 |
+
out, seen = [], set()
|
| 115 |
+
for t in texts:
|
| 116 |
+
enc = tokenizer.encode(t, add_special_tokens=False)
|
| 117 |
+
if len(enc) == 1 and enc[0] not in seen:
|
| 118 |
+
out.append(enc[0])
|
| 119 |
+
seen.add(enc[0])
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
YES_FORMS = ("yes", "Yes", "YES")
|
| 124 |
+
NO_FORMS = ("no", "No", "NO")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def readout_ids(tokenizer, q: Question) -> list[list[int]]:
|
| 128 |
+
"""Token ids to score, one group per option, max-pooled."""
|
| 129 |
+
if isinstance(q, Noul):
|
| 130 |
+
yes, no = _ids(tokenizer, YES_FORMS), _ids(tokenizer, NO_FORMS)
|
| 131 |
+
if not yes or not no:
|
| 132 |
+
raise RuntimeError("tokenizer has no single-token yes/no")
|
| 133 |
+
return [yes, no]
|
| 134 |
+
if isinstance(q, Score):
|
| 135 |
+
groups = [_ids(tokenizer, [str(i)]) for i in range(len(q.criteria))]
|
| 136 |
+
if any(not g for g in groups):
|
| 137 |
+
raise RuntimeError(
|
| 138 |
+
f"score with {len(q.criteria)} levels needs single-token digits; "
|
| 139 |
+
"the primitive is defined for 2 to 10"
|
| 140 |
+
)
|
| 141 |
+
return groups
|
| 142 |
+
groups = []
|
| 143 |
+
for code, tid in aliases(tokenizer, list(q.criteria.keys())):
|
| 144 |
+
extra = _ids(tokenizer, [f" {code}"])
|
| 145 |
+
groups.append([tid] + [i for i in extra if i != tid])
|
| 146 |
+
if not groups:
|
| 147 |
+
raise RuntimeError("choice with no options")
|
| 148 |
+
return groups
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def readout(tokenizer, q: Question, logz, calibration=None) -> list[float]:
|
| 152 |
+
"""Option probabilities from the log-probabilities at the answer slot.
|
| 153 |
+
|
| 154 |
+
`logz` is indexed by token id (a 1-D array over the vocabulary). Each
|
| 155 |
+
option scores its best form; the answer is a softmax over these and
|
| 156 |
+
nothing else.
|
| 157 |
+
"""
|
| 158 |
+
scores = [max(float(logz[i]) for i in g) for g in readout_ids(tokenizer, q)]
|
| 159 |
+
if calibration is not None:
|
| 160 |
+
scores = calibration.apply(q, scores)
|
| 161 |
+
m = max(scores)
|
| 162 |
+
exps = [math.exp(s - m) for s in scores]
|
| 163 |
+
return [e / sum(exps) for e in exps]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# --------------------------------------------------------------------------- #
|
| 167 |
+
# prompt rendering (identical to upstream prompt.py, state_style json_only)
|
| 168 |
+
# --------------------------------------------------------------------------- #
|
| 169 |
+
|
| 170 |
+
IM_START = "<|im_start|>"
|
| 171 |
+
IM_END = "<|im_end|>"
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def state_block(state: Any) -> str:
|
| 175 |
+
"""The default `json_only` style: a string passes through, anything else as JSON."""
|
| 176 |
+
if isinstance(state, str):
|
| 177 |
+
return f"{state}\n\n"
|
| 178 |
+
return json.dumps(state, ensure_ascii=False, indent=2) + "\n\n"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _option_line(code: str, label: str, desc: str | None) -> str:
|
| 182 |
+
return f"{code} {desc or label.replace('_', ' ')}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def question_block(tokenizer, q: Question) -> str:
|
| 186 |
+
if isinstance(q, Choice):
|
| 187 |
+
labels = list(q.criteria.keys())
|
| 188 |
+
codes = aliases(tokenizer, labels)
|
| 189 |
+
lines = "\n".join(_option_line(codes[i][0], lab, q.criteria[lab]) for i, lab in enumerate(labels))
|
| 190 |
+
return f"{q.instructions}\n\nOptions:\n{lines}\n\nReply with the option code only."
|
| 191 |
+
if isinstance(q, Noul):
|
| 192 |
+
extra = ""
|
| 193 |
+
if q.criteria:
|
| 194 |
+
extra = f"\nYes: {q.criteria.get('true')}\nNo: {q.criteria.get('false')}"
|
| 195 |
+
return f"{q.instructions}{extra}\n\nReply with yes or no only."
|
| 196 |
+
if isinstance(q, Score):
|
| 197 |
+
legend = "\n".join(f"{i} {name}" for i, name in enumerate(q.criteria))
|
| 198 |
+
return f"{q.instructions}\n\n{legend}\n\nReply with a single digit 0-{len(q.criteria) - 1} only."
|
| 199 |
+
raise TypeError(f"unknown question type {type(q)}")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def prefix_text(state: Any, bos: str = "", images: str = "") -> str:
|
| 203 |
+
"""Everything before the question: pictures' markup at the head of the user turn, then the state."""
|
| 204 |
+
body = "" if state is None else f"{state_block(state)}\nQUESTION:\n"
|
| 205 |
+
return f"{bos}{IM_START}user\n{images}{body}"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def suffix_text(tokenizer, q: Question) -> str:
|
| 209 |
+
"""The question and the assistant header, up to the answer slot (no lead on LFM2-VL)."""
|
| 210 |
+
return f"{question_block(tokenizer, q)}{IM_END}\n{IM_START}assistant\n"
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def render(tokenizer, state: Any, q: Question, bos: str = "", images: str = "") -> str:
|
| 214 |
+
return prefix_text(state, bos, images) + suffix_text(tokenizer, q)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def answer(q: Question, probs: Sequence[float]) -> dict:
|
| 218 |
+
"""A noul's P(yes); a choice's pick and its probabilities; a score's expected level."""
|
| 219 |
+
if isinstance(q, Noul):
|
| 220 |
+
return {"type": "noul", "noul": probs[0]}
|
| 221 |
+
best = max(range(len(probs)), key=probs.__getitem__)
|
| 222 |
+
if isinstance(q, Choice):
|
| 223 |
+
names = list(q.criteria)
|
| 224 |
+
return {"type": "choice", "choice": names[best], "confidence": probs[best],
|
| 225 |
+
"probabilities": dict(zip(names, probs))}
|
| 226 |
+
return {"type": "score", "score": sum(i * p for i, p in enumerate(probs)), "confidence": probs[best],
|
| 227 |
+
"probabilities": {str(i): p for i, p in enumerate(probs)},
|
| 228 |
+
"legend": {str(i): text for i, text in enumerate(q.criteria)}}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# --------------------------------------------------------------------------- #
|
| 232 |
+
# the MLX runner
|
| 233 |
+
# --------------------------------------------------------------------------- #
|
| 234 |
+
|
| 235 |
+
VISION_MAX_PIXELS = 1024 * 1024
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def cap_pixels(image, max_pixels: int = VISION_MAX_PIXELS):
|
| 239 |
+
"""A picture downscaled to at most `max_pixels`, bicubic (as upstream does)."""
|
| 240 |
+
image = image.convert("RGB") if hasattr(image, "convert") else image
|
| 241 |
+
w, h = image.size
|
| 242 |
+
if w * h <= max_pixels:
|
| 243 |
+
return image
|
| 244 |
+
from PIL import Image
|
| 245 |
+
|
| 246 |
+
scale = math.sqrt(max_pixels / (w * h))
|
| 247 |
+
return image.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.BICUBIC)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class SystemOne:
|
| 251 |
+
"""State in, calibrated distribution out, one forward pass — on MLX."""
|
| 252 |
+
|
| 253 |
+
def __init__(self, model_path: str, calibration=None):
|
| 254 |
+
from mlx_vlm import load
|
| 255 |
+
from mlx_vlm.utils import load_image # noqa: F401 (re-exported for callers)
|
| 256 |
+
|
| 257 |
+
self.model, self.processor = load(model_path)
|
| 258 |
+
self.tokenizer = self.processor.tokenizer if hasattr(self.processor, "tokenizer") else self.processor
|
| 259 |
+
self.model_path = model_path
|
| 260 |
+
self.calibration = calibration
|
| 261 |
+
bos = getattr(self.tokenizer, "bos_token", None)
|
| 262 |
+
self.bos = bos if isinstance(bos, str) else ""
|
| 263 |
+
|
| 264 |
+
# ---------------------------------------------------------------- vision
|
| 265 |
+
|
| 266 |
+
def _image_markup(self, n: int) -> str:
|
| 267 |
+
"""What the chat template writes for `n` images at the head of a user turn."""
|
| 268 |
+
msgs = [{"role": "user", "content": [*([{"type": "image"}] * n), {"type": "text", "text": "\x00"}]}]
|
| 269 |
+
text = self.processor.apply_chat_template(msgs, add_generation_prompt=False, tokenize=False)
|
| 270 |
+
head = f"{IM_START}user\n"
|
| 271 |
+
return text[text.index(head) + len(head):text.index("\x00")]
|
| 272 |
+
|
| 273 |
+
# --------------------------------------------------------------- forward
|
| 274 |
+
|
| 275 |
+
def _logz(self, prompt: str, images: Sequence = ()):
|
| 276 |
+
"""Log-softmax at the answer slot for one rendered prompt."""
|
| 277 |
+
import mlx.core as mx
|
| 278 |
+
from mlx_vlm.utils import prepare_inputs
|
| 279 |
+
|
| 280 |
+
pics = [cap_pixels(im) for im in images]
|
| 281 |
+
inputs = prepare_inputs(
|
| 282 |
+
self.processor,
|
| 283 |
+
images=list(pics) or None,
|
| 284 |
+
prompts=[prompt],
|
| 285 |
+
image_token_index=getattr(self.model.config, "image_token_index", None),
|
| 286 |
+
add_special_tokens=False, # the prompt carries its own BOS
|
| 287 |
+
)
|
| 288 |
+
input_ids = inputs["input_ids"]
|
| 289 |
+
pixel_values = inputs.get("pixel_values", None)
|
| 290 |
+
mask = inputs.get("attention_mask", None)
|
| 291 |
+
data_kwargs = {k: v for k, v in inputs.items()
|
| 292 |
+
if k not in ("input_ids", "pixel_values", "attention_mask")}
|
| 293 |
+
output = self.model(input_ids, pixel_values, mask, **data_kwargs)
|
| 294 |
+
logits = output.logits if hasattr(output, "logits") else output
|
| 295 |
+
row = logits[0, -1]
|
| 296 |
+
return row - mx.logsumexp(row, axis=-1), int(input_ids.shape[1])
|
| 297 |
+
|
| 298 |
+
# ------------------------------------------------------------------- api
|
| 299 |
+
|
| 300 |
+
def probabilities(self, state: Any, questions: Sequence, images: Sequence | None = None) -> list[list[float]]:
|
| 301 |
+
"""Each question's distribution over its options (`yes`, `no` for a noul).
|
| 302 |
+
|
| 303 |
+
One forward pass per question: the upstream runner packs several
|
| 304 |
+
questions of one state into a shared trunk; this helper re-reads the
|
| 305 |
+
state per question — same answers, more compute.
|
| 306 |
+
"""
|
| 307 |
+
qs = [as_question(q) for q in questions]
|
| 308 |
+
pics = [cap_pixels(im) for im in (images or ())]
|
| 309 |
+
markup = self._image_markup(len(pics)) if pics else ""
|
| 310 |
+
out = []
|
| 311 |
+
for q in qs:
|
| 312 |
+
logz, _ = self._logz(render(self.tokenizer, state, q, self.bos, markup), pics)
|
| 313 |
+
out.append(readout(self.tokenizer, q, logz, self.calibration))
|
| 314 |
+
return out
|
| 315 |
+
|
| 316 |
+
def system_one(self, state: Any, questions: Mapping[str, Any], images: Sequence | None = None) -> dict:
|
| 317 |
+
"""Named questions over one state, and its pictures if any, in one forward pass each."""
|
| 318 |
+
qs = {n: as_question(q) for n, q in questions.items()}
|
| 319 |
+
probs = self.probabilities(state, list(qs.values()), images)
|
| 320 |
+
return {"answers": {n: answer(q, p) for (n, q), p in zip(qs.items(), probs)},
|
| 321 |
+
"usage": {"input_tokens": 0, "output_tokens": 0}}
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# --------------------------------------------------------------------------- #
|
| 325 |
+
# CLI
|
| 326 |
+
# --------------------------------------------------------------------------- #
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def main(argv=None):
|
| 330 |
+
parser = argparse.ArgumentParser(description="System One decisions with MLX")
|
| 331 |
+
parser.add_argument("--model", required=True, help="MLX model path or Hugging Face ID")
|
| 332 |
+
parser.add_argument("--state", help="Text to evaluate")
|
| 333 |
+
parser.add_argument("--state-file", type=Path, help="UTF-8 text file to evaluate")
|
| 334 |
+
parser.add_argument("--questions", type=json.loads, help="Named questions as JSON")
|
| 335 |
+
parser.add_argument("--questions-file", type=Path, help="JSON file of named questions")
|
| 336 |
+
parser.add_argument("--image", action="append", default=[], help="Image path or URL (repeatable)")
|
| 337 |
+
args = parser.parse_args(argv)
|
| 338 |
+
try:
|
| 339 |
+
state = args.state_file.read_text(encoding="utf-8") if args.state_file is not None else args.state
|
| 340 |
+
questions = (json.loads(args.questions_file.read_text(encoding="utf-8"))
|
| 341 |
+
if args.questions_file is not None else args.questions)
|
| 342 |
+
for name, q in questions.items():
|
| 343 |
+
as_question(q)
|
| 344 |
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
| 345 |
+
parser.error(str(error))
|
| 346 |
+
engine = SystemOne(args.model)
|
| 347 |
+
images = None
|
| 348 |
+
if args.image:
|
| 349 |
+
from mlx_vlm.utils import load_image
|
| 350 |
+
|
| 351 |
+
images = [load_image(p) for p in args.image]
|
| 352 |
+
result = engine.system_one(state, questions, images)
|
| 353 |
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
if __name__ == "__main__":
|
| 357 |
+
main()
|
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": true,
|
| 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 |
+
}
|