Text Classification
Transformers
Safetensors
lfm2
feature-extraction
liquid
lfm2.5
bidirectional
masked-lm
encoder
custom_code
Instructions to use LiquidAI/LFM2.5-Encoder-350M-Prompt-Router with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use LiquidAI/LFM2.5-Encoder-350M-Prompt-Router with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="LiquidAI/LFM2.5-Encoder-350M-Prompt-Router", trust_remote_code=True)# Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("LiquidAI/LFM2.5-Encoder-350M-Prompt-Router", trust_remote_code=True) model = AutoModel.from_pretrained("LiquidAI/LFM2.5-Encoder-350M-Prompt-Router", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update router model card and remote code
Browse filesAdds the drafted model card, LFM Open License file, and remote-code routing class used by the README usage snippet.
- LICENSE +71 -0
- README.md +99 -0
- config.json +2 -2
- modeling_lfm2_bidirectional.py +311 -0
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,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
- de
|
| 5 |
+
- es
|
| 6 |
+
- fr
|
| 7 |
+
- it
|
| 8 |
+
- nl
|
| 9 |
+
- pl
|
| 10 |
+
- pt
|
| 11 |
+
- ar
|
| 12 |
+
- hi
|
| 13 |
+
- ja
|
| 14 |
+
- ru
|
| 15 |
+
- tr
|
| 16 |
+
- vi
|
| 17 |
+
- zh
|
| 18 |
+
tags:
|
| 19 |
+
- liquid
|
| 20 |
+
- lfm2
|
| 21 |
+
- lfm2.5
|
| 22 |
+
- bidirectional
|
| 23 |
+
- masked-lm
|
| 24 |
+
- encoder
|
| 25 |
+
library_name: transformers
|
| 26 |
+
license: other
|
| 27 |
+
license_name: lfm1.0
|
| 28 |
+
license_link: LICENSE
|
| 29 |
+
pipeline_tag: text-classification
|
| 30 |
+
base_model:
|
| 31 |
+
- LiquidAI/LFM2.5-Encoder-350M
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
<div align="center">
|
| 35 |
+
<img
|
| 36 |
+
src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
|
| 37 |
+
alt="Liquid AI"
|
| 38 |
+
style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
|
| 39 |
+
/>
|
| 40 |
+
<div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;">
|
| 41 |
+
<a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
|
| 42 |
+
<a href="https://docs.liquid.ai/lfm/getting-started/welcome"><strong>Docs</strong></a> •
|
| 43 |
+
<a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> •
|
| 44 |
+
<a href="https://discord.com/invite/liquid-ai"><strong>Discord</strong></a>
|
| 45 |
+
</div>
|
| 46 |
+
</div>
|
| 47 |
+
|
| 48 |
+
# LFM2.5-Encoder-350-Prompt-Router
|
| 49 |
+
|
| 50 |
+
A full fine-tune of [LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M) with a zero-shot routing head that scores a prompt against user-defined routing lanes in a single encoder pass.
|
| 51 |
+
|
| 52 |
+
Find more details about our encoders in our [blog post](https://www.liquid.ai/blog/lfm2-5-encoders).
|
| 53 |
+
|
| 54 |
+
> [!NOTE]
|
| 55 |
+
> 💻 **Demos**: Try this fine-tuned model running in a CPU-only Hugging Face space:
|
| 56 |
+
> **[Zero-shot prompt routing](https://huggingface.co/spaces/LiquidAI/prompt-routing)** — define your own routing lanes as free text. The model scores the whole prompt against every lane in one pass.
|
| 57 |
+
|
| 58 |
+
## Usage
|
| 59 |
+
|
| 60 |
+
> ⚠️ Loads custom code via `trust_remote_code=True` (the model wraps a `trust_remote_code` encoder).
|
| 61 |
+
|
| 62 |
+
Install the required packages:
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
pip install torch transformers
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Run zero-shot prompt routing:
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
from transformers import AutoModel, AutoTokenizer
|
| 72 |
+
|
| 73 |
+
model_id = "LiquidAI/LFM2.5-Encoder-350-Prompt-Router"
|
| 74 |
+
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 76 |
+
model = AutoModel.from_pretrained(model_id, trust_remote_code=True).eval()
|
| 77 |
+
|
| 78 |
+
routes = ["Coding", "Sales", "Creative writing", "General knowledge"]
|
| 79 |
+
prompt = "Can you help me debug a failing Python unit test?"
|
| 80 |
+
|
| 81 |
+
print(model.route(prompt, routes, tokenizer=tokenizer))
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
## 📬 Contact
|
| 85 |
+
|
| 86 |
+
- Got questions or want to connect? [Join our Discord community](https://discord.com/invite/liquid-ai)
|
| 87 |
+
- If you are interested in custom solutions with edge deployment, please contact [our sales team](https://www.liquid.ai/contact).
|
| 88 |
+
|
| 89 |
+
## Citation
|
| 90 |
+
|
| 91 |
+
```bibtex
|
| 92 |
+
@article{liquidAI2026Encoders,
|
| 93 |
+
author = {Liquid AI},
|
| 94 |
+
title = {LFM2.5-Encoders: Fast at Long Context, Even on CPU},
|
| 95 |
+
journal = {Liquid AI Blog},
|
| 96 |
+
year = {2026},
|
| 97 |
+
note = {www.liquid.ai/blog/lfm2-5-encoders},
|
| 98 |
+
}
|
| 99 |
+
```
|
config.json
CHANGED
|
@@ -3,8 +3,8 @@
|
|
| 3 |
"Lfm2BidirForSequenceRouting"
|
| 4 |
],
|
| 5 |
"auto_map": {
|
| 6 |
-
"AutoModel": "
|
| 7 |
-
"AutoModelForMaskedLM": "
|
| 8 |
},
|
| 9 |
"block_auto_adjust_ff_dim": true,
|
| 10 |
"block_dim": 1024,
|
|
|
|
| 3 |
"Lfm2BidirForSequenceRouting"
|
| 4 |
],
|
| 5 |
"auto_map": {
|
| 6 |
+
"AutoModel": "modeling_lfm2_bidirectional.Lfm2BidirForSequenceRouting",
|
| 7 |
+
"AutoModelForMaskedLM": "modeling_lfm2_bidirectional.Lfm2BidirectionalForMaskedLM"
|
| 8 |
},
|
| 9 |
"block_auto_adjust_ff_dim": true,
|
| 10 |
"block_dim": 1024,
|
modeling_lfm2_bidirectional.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LFM2 backbone with bidirectional attention + non-causal short-conv.
|
| 2 |
+
|
| 3 |
+
Wired into the HF repo via `auto_map` in config.json so that
|
| 4 |
+
|
| 5 |
+
AutoModel.from_pretrained(repo, trust_remote_code=True)
|
| 6 |
+
AutoModelForMaskedLM.from_pretrained(repo, trust_remote_code=True)
|
| 7 |
+
|
| 8 |
+
both return a model with the encoder-style patches already applied.
|
| 9 |
+
|
| 10 |
+
Supports `attn_implementation` in {"eager", "sdpa", "flash_attention_2"}:
|
| 11 |
+
|
| 12 |
+
eager/sdpa consume a 4D additive pad-only mask and reproduce the exact
|
| 13 |
+
training-time behavior; flash_attention_2 receives the 2D padding mask (or
|
| 14 |
+
None) and runs the kernel non-causally via `Lfm2Attention.is_causal = False`,
|
| 15 |
+
yielding outputs equivalent to the unpadded forward.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 25 |
+
from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
|
| 26 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 27 |
+
from transformers.models.lfm2 import modeling_lfm2 as _lfm2_mod
|
| 28 |
+
from transformers.models.lfm2.configuration_lfm2 import Lfm2Config
|
| 29 |
+
from transformers.models.lfm2.modeling_lfm2 import (
|
| 30 |
+
Lfm2Attention,
|
| 31 |
+
Lfm2Model,
|
| 32 |
+
Lfm2PreTrainedModel,
|
| 33 |
+
Lfm2ShortConv,
|
| 34 |
+
apply_mask_to_padding_states,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _bidirectional_mask(
|
| 39 |
+
config,
|
| 40 |
+
input_embeds: torch.Tensor = None,
|
| 41 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 42 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 43 |
+
past_key_values=None,
|
| 44 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 45 |
+
**kwargs,
|
| 46 |
+
) -> Optional[torch.Tensor]:
|
| 47 |
+
# transformers has renamed the embeds kwarg across versions
|
| 48 |
+
# (input_embeds <-> inputs_embeds); accept either to stay forward-compatible.
|
| 49 |
+
if input_embeds is None:
|
| 50 |
+
input_embeds = kwargs.get("inputs_embeds")
|
| 51 |
+
|
| 52 |
+
if config._attn_implementation == "flash_attention_2":
|
| 53 |
+
# FA2 only uses the 2D padding mask to unpad sequences; causality is
|
| 54 |
+
# controlled by `Lfm2Attention.is_causal` (set to False below).
|
| 55 |
+
if attention_mask is not None and not attention_mask.all():
|
| 56 |
+
return attention_mask
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
device = input_embeds.device
|
| 60 |
+
dtype = input_embeds.dtype
|
| 61 |
+
bsz, q_len = input_embeds.shape[:2]
|
| 62 |
+
past = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 63 |
+
kv_len = past + q_len
|
| 64 |
+
|
| 65 |
+
mask = torch.zeros((bsz, 1, q_len, kv_len), device=device, dtype=dtype)
|
| 66 |
+
if attention_mask is not None:
|
| 67 |
+
cur_len = attention_mask.size(-1)
|
| 68 |
+
key_pad_flags = (attention_mask == 0).to(device=device, dtype=torch.float32)
|
| 69 |
+
pad_vec = torch.zeros((bsz, kv_len), device=device, dtype=torch.float32)
|
| 70 |
+
if cur_len > 0:
|
| 71 |
+
pad_vec[:, past:past + cur_len] = key_pad_flags * -1e9
|
| 72 |
+
mask = mask + pad_vec.to(dtype)[:, None, None, :]
|
| 73 |
+
return mask
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _noncausal_shortconv_forward(
|
| 77 |
+
self,
|
| 78 |
+
hidden_states: torch.Tensor,
|
| 79 |
+
past_key_values=None,
|
| 80 |
+
cache_position=None,
|
| 81 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 82 |
+
**kwargs,
|
| 83 |
+
) -> torch.Tensor:
|
| 84 |
+
x = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 85 |
+
|
| 86 |
+
BCx = self.in_proj(x).transpose(-1, -2)
|
| 87 |
+
B, C, x = BCx.chunk(3, dim=-2)
|
| 88 |
+
Bx = B * x
|
| 89 |
+
|
| 90 |
+
k = self.conv.weight.shape[-1]
|
| 91 |
+
pad = k // 2
|
| 92 |
+
conv_out = F.conv1d(
|
| 93 |
+
Bx, weight=self.conv.weight, bias=self.conv.bias,
|
| 94 |
+
stride=1, padding=pad, dilation=1, groups=Bx.shape[1],
|
| 95 |
+
)
|
| 96 |
+
if conv_out.shape[-1] > Bx.shape[-1]:
|
| 97 |
+
conv_out = conv_out[..., :Bx.shape[-1]]
|
| 98 |
+
elif conv_out.shape[-1] < Bx.shape[-1]:
|
| 99 |
+
conv_out = F.pad(conv_out, (0, Bx.shape[-1] - conv_out.shape[-1]))
|
| 100 |
+
|
| 101 |
+
y = C * conv_out
|
| 102 |
+
y = y.transpose(-1, -2).contiguous()
|
| 103 |
+
return self.out_proj(y)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _shortconv_forward(self, *args, **kwargs):
|
| 107 |
+
return self.slow_forward(*args, **kwargs)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
_PATCHED = False
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _install_patches() -> None:
|
| 114 |
+
global _PATCHED
|
| 115 |
+
if _PATCHED:
|
| 116 |
+
return
|
| 117 |
+
_lfm2_mod.create_causal_mask = _bidirectional_mask
|
| 118 |
+
Lfm2ShortConv.slow_forward = _noncausal_shortconv_forward
|
| 119 |
+
Lfm2ShortConv.forward = _shortconv_forward
|
| 120 |
+
_PATCHED = True
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
_install_patches()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _set_attention_noncausal(model) -> None:
|
| 127 |
+
for module in model.modules():
|
| 128 |
+
if isinstance(module, Lfm2Attention):
|
| 129 |
+
module.is_causal = False
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class Lfm2BidirectionalModel(Lfm2Model):
|
| 133 |
+
"""LFM2 patched for encoder-style use:
|
| 134 |
+
full bidirectional attention + non-causal short-conv."""
|
| 135 |
+
|
| 136 |
+
def __init__(self, config):
|
| 137 |
+
_install_patches()
|
| 138 |
+
super().__init__(config)
|
| 139 |
+
_set_attention_noncausal(self)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Lfm2BidirectionalForMaskedLM(Lfm2PreTrainedModel):
|
| 143 |
+
"""LFM2 bidirectional encoder with a tied masked-LM head."""
|
| 144 |
+
|
| 145 |
+
config_class = Lfm2Config
|
| 146 |
+
base_model_prefix = "lfm2"
|
| 147 |
+
_tied_weights_keys = {"lm_head.weight": "lfm2.embed_tokens.weight"}
|
| 148 |
+
|
| 149 |
+
def __init__(self, config: Lfm2Config):
|
| 150 |
+
_install_patches()
|
| 151 |
+
config = type(config).from_dict({**config.to_dict(), "use_cache": False})
|
| 152 |
+
super().__init__(config)
|
| 153 |
+
self.lfm2 = Lfm2BidirectionalModel(config)
|
| 154 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 155 |
+
self.post_init()
|
| 156 |
+
self.lm_head.weight = self.lfm2.embed_tokens.weight
|
| 157 |
+
|
| 158 |
+
def get_input_embeddings(self):
|
| 159 |
+
return self.lfm2.embed_tokens
|
| 160 |
+
|
| 161 |
+
def set_input_embeddings(self, value):
|
| 162 |
+
self.lfm2.embed_tokens = value
|
| 163 |
+
|
| 164 |
+
def get_output_embeddings(self):
|
| 165 |
+
return self.lm_head
|
| 166 |
+
|
| 167 |
+
def set_output_embeddings(self, new_embeddings):
|
| 168 |
+
self.lm_head = new_embeddings
|
| 169 |
+
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 173 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 174 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 175 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 176 |
+
labels: Optional[torch.LongTensor] = None,
|
| 177 |
+
output_hidden_states: Optional[bool] = None,
|
| 178 |
+
output_attentions: Optional[bool] = None,
|
| 179 |
+
return_dict: Optional[bool] = None,
|
| 180 |
+
**kwargs,
|
| 181 |
+
) -> MaskedLMOutput:
|
| 182 |
+
return_dict = True if return_dict is None else return_dict
|
| 183 |
+
outputs = self.lfm2(
|
| 184 |
+
input_ids=input_ids,
|
| 185 |
+
attention_mask=attention_mask,
|
| 186 |
+
position_ids=position_ids,
|
| 187 |
+
inputs_embeds=inputs_embeds,
|
| 188 |
+
use_cache=False,
|
| 189 |
+
output_attentions=output_attentions,
|
| 190 |
+
output_hidden_states=output_hidden_states,
|
| 191 |
+
return_dict=True,
|
| 192 |
+
)
|
| 193 |
+
hidden = outputs.last_hidden_state
|
| 194 |
+
logits = self.lm_head(hidden)
|
| 195 |
+
|
| 196 |
+
loss = None
|
| 197 |
+
if labels is not None:
|
| 198 |
+
loss = F.cross_entropy(
|
| 199 |
+
logits.view(-1, self.config.vocab_size),
|
| 200 |
+
labels.view(-1),
|
| 201 |
+
ignore_index=-100,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if not return_dict:
|
| 205 |
+
out = (logits,) + outputs[1:]
|
| 206 |
+
return ((loss,) + out) if loss is not None else out
|
| 207 |
+
return MaskedLMOutput(
|
| 208 |
+
loss=loss,
|
| 209 |
+
logits=logits,
|
| 210 |
+
hidden_states=outputs.hidden_states,
|
| 211 |
+
attentions=outputs.attentions,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class Lfm2BidirForSequenceRouting(Lfm2PreTrainedModel):
|
| 216 |
+
"""Zero-shot prompt router built on the bidirectional LFM2 encoder."""
|
| 217 |
+
|
| 218 |
+
config_class = Lfm2Config
|
| 219 |
+
base_model_prefix = "lfm2"
|
| 220 |
+
|
| 221 |
+
def __init__(self, config: Lfm2Config):
|
| 222 |
+
_install_patches()
|
| 223 |
+
config = type(config).from_dict({**config.to_dict(), "use_cache": False})
|
| 224 |
+
super().__init__(config)
|
| 225 |
+
self.lfm2 = Lfm2BidirectionalModel(config)
|
| 226 |
+
proj_dim = getattr(config, "rule_proj_dim", 256)
|
| 227 |
+
self.tok_proj = nn.Linear(config.hidden_size, proj_dim)
|
| 228 |
+
self.rule_proj = nn.Linear(config.hidden_size, proj_dim)
|
| 229 |
+
self.score_bias = nn.Parameter(torch.tensor(0.0))
|
| 230 |
+
self.logit_scale = nn.Parameter(torch.tensor(1.0))
|
| 231 |
+
self.post_init()
|
| 232 |
+
|
| 233 |
+
def get_input_embeddings(self):
|
| 234 |
+
return self.lfm2.embed_tokens
|
| 235 |
+
|
| 236 |
+
def set_input_embeddings(self, value):
|
| 237 |
+
self.lfm2.embed_tokens = value
|
| 238 |
+
|
| 239 |
+
def forward(
|
| 240 |
+
self,
|
| 241 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 242 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 243 |
+
text_pool: Optional[torch.Tensor] = None,
|
| 244 |
+
category_pool: Optional[torch.Tensor] = None,
|
| 245 |
+
**kwargs,
|
| 246 |
+
):
|
| 247 |
+
outputs = self.lfm2(
|
| 248 |
+
input_ids=input_ids,
|
| 249 |
+
attention_mask=attention_mask,
|
| 250 |
+
use_cache=False,
|
| 251 |
+
return_dict=True,
|
| 252 |
+
)
|
| 253 |
+
hidden = outputs.last_hidden_state
|
| 254 |
+
text_rep = torch.bmm(text_pool, hidden).squeeze(1)
|
| 255 |
+
category_rep = torch.bmm(category_pool, hidden)
|
| 256 |
+
query = F.normalize(self.tok_proj(text_rep), dim=-1)
|
| 257 |
+
categories = F.normalize(self.rule_proj(category_rep), dim=-1)
|
| 258 |
+
scale = torch.clamp(self.logit_scale.exp(), max=30.0)
|
| 259 |
+
logits = torch.einsum("bd,brd->br", query, categories) * scale + self.score_bias
|
| 260 |
+
return {"logits": logits}
|
| 261 |
+
|
| 262 |
+
@staticmethod
|
| 263 |
+
def _prefix(routes):
|
| 264 |
+
body = "\n".join(f"- {route}" for route in routes) if routes else "- (none)"
|
| 265 |
+
return f"Categories:\n{body}\n\nText:\n"
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def _category_ranges(routes):
|
| 269 |
+
ranges = []
|
| 270 |
+
pos = len("Categories:\n")
|
| 271 |
+
for route in routes:
|
| 272 |
+
start = pos + 2
|
| 273 |
+
end = start + len(route)
|
| 274 |
+
ranges.append((start, end))
|
| 275 |
+
pos = end + 1
|
| 276 |
+
return ranges
|
| 277 |
+
|
| 278 |
+
@torch.no_grad()
|
| 279 |
+
def route(self, text, routes, tokenizer, threshold=None):
|
| 280 |
+
prefix = self._prefix(routes)
|
| 281 |
+
full_text = prefix + text
|
| 282 |
+
enc = tokenizer(full_text, return_offsets_mapping=True, return_tensors="pt")
|
| 283 |
+
offsets = enc.pop("offset_mapping")[0].tolist()
|
| 284 |
+
enc = {k: v.to(self.device) for k, v in enc.items()}
|
| 285 |
+
|
| 286 |
+
text_start = len(prefix)
|
| 287 |
+
text_idxs = [
|
| 288 |
+
i for i, (start, end) in enumerate(offsets)
|
| 289 |
+
if end > text_start and start != end
|
| 290 |
+
]
|
| 291 |
+
text_pool = torch.zeros(1, 1, len(offsets), device=self.device)
|
| 292 |
+
if text_idxs:
|
| 293 |
+
text_pool[0, 0, text_idxs] = 1 / len(text_idxs)
|
| 294 |
+
|
| 295 |
+
category_pool = torch.zeros(1, len(routes), len(offsets), device=self.device)
|
| 296 |
+
for route_idx, (start, end) in enumerate(self._category_ranges(routes)):
|
| 297 |
+
token_idxs = [
|
| 298 |
+
i for i, (tok_start, tok_end) in enumerate(offsets)
|
| 299 |
+
if tok_start < end and tok_end > start and tok_start != tok_end
|
| 300 |
+
]
|
| 301 |
+
if token_idxs:
|
| 302 |
+
category_pool[0, route_idx, token_idxs] = 1 / len(token_idxs)
|
| 303 |
+
|
| 304 |
+
logits = self(**enc, text_pool=text_pool, category_pool=category_pool)["logits"][0]
|
| 305 |
+
probs = logits.softmax(dim=-1).detach().cpu()
|
| 306 |
+
results = [
|
| 307 |
+
{"route": route, "score": float(prob)}
|
| 308 |
+
for route, prob in zip(routes, probs)
|
| 309 |
+
if threshold is None or prob >= threshold
|
| 310 |
+
]
|
| 311 |
+
return sorted(results, key=lambda item: item["score"], reverse=True)
|