Text Generation
Transformers
Safetensors
GGUF
lfm3
liquid
depth-loop
training-free
custom_code
conversational
Instructions to use vaultpls/LFM3-1.7B-Looped with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use vaultpls/LFM3-1.7B-Looped with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="vaultpls/LFM3-1.7B-Looped", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("vaultpls/LFM3-1.7B-Looped", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("vaultpls/LFM3-1.7B-Looped", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use vaultpls/LFM3-1.7B-Looped with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped:Q8_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped:Q8_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf vaultpls/LFM3-1.7B-Looped:Q8_0
Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Llama new
- LM Studio
- Jan
- vLLM
How to use vaultpls/LFM3-1.7B-Looped with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "vaultpls/LFM3-1.7B-Looped" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- SGLang
How to use vaultpls/LFM3-1.7B-Looped with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "vaultpls/LFM3-1.7B-Looped" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "vaultpls/LFM3-1.7B-Looped" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Ollama
How to use vaultpls/LFM3-1.7B-Looped with Ollama:
ollama run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Unsloth Desktop
- Pi
How to use vaultpls/LFM3-1.7B-Looped with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "vaultpls/LFM3-1.7B-Looped:Q8_0" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use vaultpls/LFM3-1.7B-Looped with Docker Model Runner:
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Lemonade
How to use vaultpls/LFM3-1.7B-Looped with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull vaultpls/LFM3-1.7B-Looped:Q8_0
Run and chat with the model
lemonade run user.LFM3-1.7B-Looped-Q8_0
List all available models
lemonade list
- Hermes Agent
How to use vaultpls/LFM3-1.7B-Looped with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0
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:9931/v1 hermes config set model.default vaultpls/LFM3-1.7B-Looped:Q8_0
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use vaultpls/LFM3-1.7B-Looped with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped:Q8_0
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:9931/v1 \ --custom-model-id "vaultpls/LFM3-1.7B-Looped:Q8_0" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
LFM3-1.7B-Looped: layers 8-11 run twice at half step (training-free depth loop), Q8_0 GGUF + bf16
Browse files- .gitattributes +2 -0
- LICENSE +71 -0
- NOTICE +39 -0
- README.md +122 -2
- REPRODUCE.md +116 -0
- chat_template.jinja +280 -0
- config.json +73 -0
- configuration_lfm3.py +132 -0
- generation_config.json +16 -0
- gguf/LFM3-1.7B-loop-8-11-Q8_0.gguf +3 -0
- lfm3_conv.py +202 -0
- model.safetensors +3 -0
- modeling_lfm3.py +881 -0
- requirements.txt +10 -0
- scripts/check_loop_gguf.py +95 -0
- scripts/compose-loop.yaml +61 -0
- scripts/ens.py +40 -0
- scripts/lmstat.py +48 -0
- scripts/loop_gguf_k.py +204 -0
- scripts/save_loop_hf.py +52 -0
- scripts/tfl.py +552 -0
- tokenizer.json +3 -0
- tokenizer_config.json +64 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ 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 |
+
gguf/LFM3-1.7B-loop-8-11-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
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
|
NOTICE
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NOTICE — modified files and attribution
|
| 2 |
+
========================================
|
| 3 |
+
|
| 4 |
+
This repository is a Derivative Work of LiquidAI/LFM3-1.7B-Base (© Liquid AI, Inc.),
|
| 5 |
+
distributed under the LFM Open License v1.0. A copy of that license is in LICENSE.
|
| 6 |
+
No affiliation with, endorsement by, or support from Liquid AI is claimed.
|
| 7 |
+
|
| 8 |
+
What was changed (LFM Open License v1.0, Section 4(b))
|
| 9 |
+
-----------------------------------------------------
|
| 10 |
+
The following was produced mechanically from the base checkpoint with no training:
|
| 11 |
+
|
| 12 |
+
1. Layers 8, 9, 10, 11 of the 24-layer stack were duplicated once, inserted after layer 11 as
|
| 13 |
+
new layers 12, 13, 14, 15. Total depth 24 -> 28.
|
| 14 |
+
2. For the original layers 8-11 AND their copies 12-15, these two tensors are multiplied by 0.5:
|
| 15 |
+
|
| 16 |
+
blk.{8..15}.post_attention_norm.weight
|
| 17 |
+
blk.{8..15}.post_ffw_norm.weight
|
| 18 |
+
|
| 19 |
+
This damps the residual branch of each pass by half. All other tensors are byte-identical to the
|
| 20 |
+
base model.
|
| 21 |
+
3. In the GGUF, `lfm3.block_count` is 28, and the per-layer arrays
|
| 22 |
+
`lfm3.attention.head_count_kv` and `lfm3.attention.sliding_window_pattern` were extended with the
|
| 23 |
+
copied layers' entries. All blk indices after the insertion point were renumbered.
|
| 24 |
+
|
| 25 |
+
Nothing else was modified: no fine-tuning, no merging, no added or removed parameters other than the
|
| 26 |
+
duplicated window.
|
| 27 |
+
|
| 28 |
+
Redistribution conditions
|
| 29 |
+
-------------------------
|
| 30 |
+
* A copy of the LFM Open License v1.0 must accompany redistribution: see LICENSE.
|
| 31 |
+
* Modified files must carry a prominent notice that they were changed: this file.
|
| 32 |
+
* The base model's attribution and license metadata are preserved in the model card.
|
| 33 |
+
* Commercial use is subject to the revenue threshold in Section 5 of the license.
|
| 34 |
+
|
| 35 |
+
Upstream
|
| 36 |
+
--------
|
| 37 |
+
Base model: https://huggingface.co/LiquidAI/LFM3-1.7B-Base
|
| 38 |
+
License: LFM Open License v1.0
|
| 39 |
+
Citation of the method: arXiv 2605.23872 (training-free depth looping with damped sub-steps)
|
README.md
CHANGED
|
@@ -1,5 +1,125 @@
|
|
| 1 |
---
|
|
|
|
| 2 |
license: other
|
| 3 |
-
license_name:
|
| 4 |
-
license_link: https://huggingface.co/LiquidAI/LFM3-1.7B/blob/main/LICENSE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
library_name: transformers
|
| 3 |
license: other
|
| 4 |
+
license_name: lfm1.0
|
| 5 |
+
license_link: https://huggingface.co/LiquidAI/LFM3-1.7B-Base/blob/main/LICENSE
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
base_model: LiquidAI/LFM3-1.7B-Base
|
| 8 |
+
tags:
|
| 9 |
+
- liquid
|
| 10 |
+
- lfm3
|
| 11 |
+
- depth-loop
|
| 12 |
+
- training-free
|
| 13 |
+
- gguf
|
| 14 |
+
- custom_code
|
| 15 |
+
language:
|
| 16 |
+
- en
|
| 17 |
+
- ar
|
| 18 |
+
- zh
|
| 19 |
+
- fr
|
| 20 |
+
- de
|
| 21 |
+
- it
|
| 22 |
+
- ja
|
| 23 |
+
- ko
|
| 24 |
+
- pt
|
| 25 |
+
- es
|
| 26 |
+
- vi
|
| 27 |
+
- th
|
| 28 |
+
- id
|
| 29 |
+
- hi
|
| 30 |
+
- ru
|
| 31 |
+
- pl
|
| 32 |
---
|
| 33 |
+
|
| 34 |
+
# LFM3-1.7B-Looped (layers 8-11, run twice)
|
| 35 |
+
|
| 36 |
+
LFM3-1.7B-Base with **layers 8–11 executed twice**, each pass contributing **half a residual step**.
|
| 37 |
+
Training-free: no gradients, no new parameters, no data. The result is a plain 28-layer model, so it
|
| 38 |
+
generates with a stock KV cache and runs in llama.cpp.
|
| 39 |
+
|
| 40 |
+
## Model details
|
| 41 |
+
|
| 42 |
+
* Base: [LiquidAI/LFM3-1.7B-Base](https://huggingface.co/LiquidAI/LFM3-1.7B-Base) — 24 layers, hybrid
|
| 43 |
+
shortconv/attention, 2048 hidden, 7680 FFN, sliding-window attention every 4th layer.
|
| 44 |
+
* Modification: layers 8–11 duplicated once (new layers 12–15), and
|
| 45 |
+
`post_attention_norm.weight` / `post_ffw_norm.weight` multiplied by 0.5 on both the originals and
|
| 46 |
+
the copies. All later layers renumbered. `block_count` 24 → 28.
|
| 47 |
+
* Parameters: 1.73B → 1.97B. Q8_0 file 1.84 → 2.10 GB.
|
| 48 |
+
* Nothing else is changed: no fine-tuning, no merging, no calibration data.
|
| 49 |
+
|
| 50 |
+
The loop is the damped fixed point `h ← h + 0.5 · (G(h) − h)` applied twice, where `G` is the
|
| 51 |
+
four-layer block. Damping lives in the post-norms because those are applied to the branch output
|
| 52 |
+
before the residual add, in both the HF code and llama.cpp's `lfm3.cpp`; scaling `o_proj`/`w2`
|
| 53 |
+
instead would be divided out by the following RMSNorm. Verified exact: max|Δlogit| = 0.0 against a
|
| 54 |
+
runtime reference wrapper, 0.5× on every scaled tensor in the GGUF.
|
| 55 |
+
|
| 56 |
+
## Evaluation
|
| 57 |
+
|
| 58 |
+
Same items, both models, paired. Full details and the negative results are in the repository README.
|
| 59 |
+
|
| 60 |
+
| benchmark | base | this model | Δ |
|
| 61 |
+
|---|---|---|---|
|
| 62 |
+
| ARC-Easy 5-shot (n=1000) | 60.8 | 69.2 | +8.4 pp, p=2.4e-9 |
|
| 63 |
+
| ARC-Challenge 5-shot (n=1000) | 30.0 | 34.1 | +4.1 pp |
|
| 64 |
+
| HellaSwag 0-shot (n=10042) | 53.6 | 54.3 | +0.7 pp, p=0.006 |
|
| 65 |
+
| WinoGrande 0-shot (n=1267) | 54.7 | 57.4 | +2.7 pp, p=0.014 |
|
| 66 |
+
| ARC-Easy 0-shot (n=2376) | 38.5 | 41.0 | +2.5 pp, p=0.0001 |
|
| 67 |
+
| ARC-Challenge 0-shot (n=1172) | 26.1 | 27.7 | +1.6 pp, p=0.073 |
|
| 68 |
+
| PIQA 0-shot (n=1838) | 60.3 | 60.6 | +0.3 pp (n.s.) |
|
| 69 |
+
| BoolQ 0-shot (n=3270) | 75.4 | 74.8 | −0.6 pp (n.s.) |
|
| 70 |
+
| wikitext PPL (HF) | 24.73 | 23.62 | −4.5% |
|
| 71 |
+
| wikitext PPL (llama.cpp Q8) | 18.29 | 17.87 | −2.3% |
|
| 72 |
+
|
| 73 |
+
Throughput on an RTX 4070, Q8_0, `-ngl 99`, isolated llama-bench: pp512 18184 → 16699 t/s,
|
| 74 |
+
tg128 160.31 → 142.55 t/s.
|
| 75 |
+
|
| 76 |
+
## Use
|
| 77 |
+
|
| 78 |
+
llama.cpp (needs the LFM3 architecture, master ≥ `1014775c8`):
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
llama-server -m LFM3-1.7B-loop-8-11-Q8_0.gguf --alias lfm3-loop -ngl 99 -fa on -c 131072 --jinja
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
transformers:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 88 |
+
tok = AutoTokenizer.from_pretrained("vaultpls/LFM3-1.7B-Looped", trust_remote_code=True)
|
| 89 |
+
m = AutoModelForCausalLM.from_pretrained("vaultpls/LFM3-1.7B-Looped", trust_remote_code=True, dtype="bfloat16")
|
| 90 |
+
ids = tok("The capital of France is", return_tensors="pt").input_ids
|
| 91 |
+
print(tok.decode(m.generate(ids, max_new_tokens=32, do_sample=False)[0]))
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
The `hf/` folder carries the custom `modeling_lfm3.py`, `configuration_lfm3.py` and `lfm3_conv.py`
|
| 95 |
+
needed by `trust_remote_code`.
|
| 96 |
+
|
| 97 |
+
## Limitations
|
| 98 |
+
|
| 99 |
+
* **Base checkpoint**, not instruction-tuned. With the chat template it emits a thinking trace
|
| 100 |
+
(`reasoning_content`) and returns empty `content` if `max_tokens` is too small. Use
|
| 101 |
+
`/v1/completions` for plain text, or set `chat_template_kwargs: {"enable_thinking": false}`.
|
| 102 |
+
* Gains are configuration-dependent: +8.4 pp on ARC-Easy at 5-shot vs +2.5 pp at 0-shot. The
|
| 103 |
+
canonical 25-shot ARC / 10-shot HellaSwag settings were not run.
|
| 104 |
+
* One model, one window, one architecture family. Late-layer loops degrade the model; don't move the
|
| 105 |
+
window into the last quarter without re-measuring.
|
| 106 |
+
* ~11% slower decode, ~14% larger file.
|
| 107 |
+
* No safety tuning was applied beyond whatever the base model carries.
|
| 108 |
+
|
| 109 |
+
## License
|
| 110 |
+
|
| 111 |
+
LFM Open License v1.0, inherited from the base model — commercial use limited by the revenue
|
| 112 |
+
threshold in Section 5. See `LICENSE`. Modified files are listed in `NOTICE`. Not affiliated with or
|
| 113 |
+
endorsed by Liquid AI; "LFM" is used only to describe the origin of the weights.
|
| 114 |
+
|
| 115 |
+
## Citation
|
| 116 |
+
|
| 117 |
+
```bibtex
|
| 118 |
+
@misc{lfm3_loop_8_11,
|
| 119 |
+
title = {LFM3-1.7B-loop-8-11: a training-free depth loop},
|
| 120 |
+
year = {2026},
|
| 121 |
+
note = {Derived from LiquidAI/LFM3-1.7B-Base by executing layers 8--11 twice at half step},
|
| 122 |
+
}
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
Method inspired by arXiv 2605.23872 (training-free looping / damped sub-steps).
|
REPRODUCE.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproducing the build and the numbers
|
| 2 |
+
|
| 3 |
+
Everything below was run on Linux, Python 3.12, an RTX 4070 (12 GB), torch 2.14.1+cu126,
|
| 4 |
+
transformers 5.23.0.
|
| 5 |
+
|
| 6 |
+
## 0. Environment
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
python -m venv .venv && . .venv/bin/activate
|
| 10 |
+
pip install -r requirements.txt
|
| 11 |
+
export LFM3_BASE=/path/to/LFM3-1.7B-Base # HF snapshot of the base model
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
`scripts/tfl.py` reads `$LFM3_BASE` (or `--base-model`) for the checkpoint. The base snapshot must
|
| 15 |
+
include the custom `modeling_lfm3.py`, `configuration_lfm3.py` and `lfm3_conv.py`.
|
| 16 |
+
|
| 17 |
+
## 1. Build the looped model (HF)
|
| 18 |
+
|
| 19 |
+
```bash
|
| 20 |
+
python scripts/save_loop_hf.py --base "$LFM3_BASE" --out ./LFM3-1.7B-loop-8-11 --window 8,11 --reps 2 --alpha 0.5
|
| 21 |
+
# layers 28 layer_types 28
|
| 22 |
+
# saved ./LFM3-1.7B-loop-8-11 3.96 GB
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## 2. Prove the damping is exact
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python scripts/tfl.py identity --window 8,11 --reps 2
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Expected: `build(reps=1, alpha=1) vs base: max|dlogit| = 0.000e+00`, and for alpha in {1.0, 0.5, 0.25}
|
| 32 |
+
the hook-based reference wrapper and the static model agree to `0.000e+00`. (alpha = 1/3 shows a
|
| 33 |
+
~4e-1 residue; that is bf16 rounding of `post_norm.weight * 1/3`, not a structural difference —
|
| 34 |
+
0.25 and 0.5 are exact because they are powers of two.)
|
| 35 |
+
|
| 36 |
+
## 3. Build the GGUF
|
| 37 |
+
|
| 38 |
+
Needs a base GGUF (e.g. `LFM3-1.7B-Q8_0.gguf`) and a llama.cpp checkout that can at least read the
|
| 39 |
+
file format (conversion does not need GPU support).
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
python scripts/loop_gguf_k.py base.gguf loop.gguf 8 11 2 0.5
|
| 43 |
+
python scripts/check_loop_gguf.py base.gguf loop.gguf 8 11 2 0.5
|
| 44 |
+
# ... max|got - 0.5*base| = 0.00e+00 for all eight tensors
|
| 45 |
+
# copy of blk.8.attn_norm identical: True
|
| 46 |
+
# DAMPING EXACT
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## 4. Evaluate
|
| 50 |
+
|
| 51 |
+
ARC, 5-shot, 1000 items, paired McNemar (this is the harness that produced +8.4 pp):
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --base
|
| 55 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --window 8,11 --alpha 0.5
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
lm-evaluation-harness, six canonical tasks, full sets:
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
lm_eval --model hf \
|
| 62 |
+
--model_args pretrained=$LFM3_BASE,trust_remote_code=True,dtype=bfloat16 \
|
| 63 |
+
--tasks hellaswag,piqa,winogrande,arc_easy,arc_challenge,boolq \
|
| 64 |
+
--batch_size 4 --device cuda:0 --output_path out-lm/base --log_samples
|
| 65 |
+
lm_eval --model hf \
|
| 66 |
+
--model_args pretrained=./LFM3-1.7B-loop-8-11,trust_remote_code=True,dtype=bfloat16 \
|
| 67 |
+
--tasks hellaswag,piqa,winogrande,arc_easy,arc_challenge,boolq \
|
| 68 |
+
--batch_size 4 --device cuda:0 --output_path out-lm/loop --log_samples
|
| 69 |
+
LM_EVAL_ROOT=out-lm python scripts/lmstat.py
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Note: with no `--num_fewshot`, these tasks ran **0-shot** (the harness did not apply the few-shot
|
| 73 |
+
defaults from the task configs). With `--num_fewshot 5`, arc_easy scores 60.4 for the base model,
|
| 74 |
+
matching the 60.8 from `tfl.py`; batch size 1 and 4 give identical results (40.2 vs 40.4 at 0-shot,
|
| 75 |
+
60.4 both at 5-shot), so padded batching does not distort this model.
|
| 76 |
+
|
| 77 |
+
Perplexity:
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
python scripts/tfl.py ppl --stream --n-pll 20 --base
|
| 81 |
+
python scripts/tfl.py ppl --stream --n-pll 20 --window 8,11 --alpha 0.5
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Speed (isolated — do not benchmark while a server holds the GPU, you will measure contention):
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
llama-bench -m base.gguf -p 512 -n 128 -ngl 99 -r 3
|
| 88 |
+
llama-bench -m loop.gguf -p 512 -n 128 -ngl 99 -r 3
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## 5. Serve
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
llama-server -m loop.gguf --alias lfm3-loop -ngl 99 -fa on -c 131072 --jinja
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
or with the container definition used here: `docker compose -f scripts/compose-loop.yaml up -d`
|
| 98 |
+
(the compose file expects the model at `/models/LFM3-1.7B-loop-8-11-Q8_0.gguf`).
|
| 99 |
+
|
| 100 |
+
Two serving gotchas found the hard way:
|
| 101 |
+
|
| 102 |
+
* `--repeat-penalty` costs ~5% decode (135 → 128.6 t/s measured); leave it to the client.
|
| 103 |
+
* An old llama.cpp build cost 2× prefill (7.7k vs 14.8k t/s at 3.2k tokens) even though decode looked
|
| 104 |
+
normal. Use a build that reports LFM3 support.
|
| 105 |
+
|
| 106 |
+
## 6. Rebuild the negative results (optional)
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
# more passes, gain schedules, extra windows
|
| 110 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --window 8,11 --reps 3
|
| 111 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --window 8,11 --gains 0.5,1.0
|
| 112 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --multi "8,11,2,0.5;16,19,2,0.5"
|
| 113 |
+
# residual scaling (the artefact): ARC up, PPL destroyed
|
| 114 |
+
python scripts/tfl.py arc --arc-n 1000 --shots 5 --window 8,11 --alpha 0.5 --postscale 0.8
|
| 115 |
+
python scripts/tfl.py ppl --stream --n-pll 20 --window 8,11 --alpha 0.5 --postscale 0.8
|
| 116 |
+
```
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{- bos_token -}}
|
| 2 |
+
{%- set preserve_thinking = preserve_thinking | default(false) -%}
|
| 3 |
+
{%- set enable_thinking = enable_thinking | default(true) -%}
|
| 4 |
+
|
| 5 |
+
{%- macro render_value(v) -%}
|
| 6 |
+
{%- if v is string -%}
|
| 7 |
+
{{- v -}}
|
| 8 |
+
{%- elif v is boolean -%}
|
| 9 |
+
{{- "true" if v else "false" -}}
|
| 10 |
+
{%- elif v is none -%}
|
| 11 |
+
{{- "null" -}}
|
| 12 |
+
{%- elif v is mapping or (v is sequence and v is not string) -%}
|
| 13 |
+
{{- v | tojson -}}
|
| 14 |
+
{%- else -%}
|
| 15 |
+
{{- v -}}
|
| 16 |
+
{%- endif -%}
|
| 17 |
+
{%- endmacro -%}
|
| 18 |
+
|
| 19 |
+
{%- macro parse_content(content) -%}
|
| 20 |
+
{%- if content is string -%}
|
| 21 |
+
{{- content -}}
|
| 22 |
+
{%- elif content is mapping and content.get("type") == "image" -%}
|
| 23 |
+
{{- "<|vision_start|><|image|><|vision_end|>" -}}
|
| 24 |
+
{%- elif content is mapping and content.get("type") == "video" -%}
|
| 25 |
+
{{- "<|vision_start|><|video|><|vision_end|>" -}}
|
| 26 |
+
{%- elif content is mapping and content.get("type") == "text" -%}
|
| 27 |
+
{{- (content.get("text") or "") | string -}}
|
| 28 |
+
{%- elif content is mapping -%}
|
| 29 |
+
{{- content | tojson -}}
|
| 30 |
+
{%- elif content is iterable -%}
|
| 31 |
+
{%- set _ns = namespace(result="") -%}
|
| 32 |
+
{%- for item in content -%}
|
| 33 |
+
{%- if item is string -%}
|
| 34 |
+
{%- set _ns.result = _ns.result + item -%}
|
| 35 |
+
{%- elif item is mapping and item.get("type") == "image" -%}
|
| 36 |
+
{%- set _ns.result = _ns.result + "<|vision_start|><|image|><|vision_end|>" -%}
|
| 37 |
+
{%- elif item is mapping and item.get("type") == "video" -%}
|
| 38 |
+
{%- set _ns.result = _ns.result + "<|vision_start|><|video|><|vision_end|>" -%}
|
| 39 |
+
{%- elif item is mapping and item.get("type") == "text" -%}
|
| 40 |
+
{%- set _ns.result = _ns.result + ((item.get("text") or "") | string) -%}
|
| 41 |
+
{%- else -%}
|
| 42 |
+
{%- set _ns.result = _ns.result + (item | tojson) -%}
|
| 43 |
+
{%- endif -%}
|
| 44 |
+
{%- endfor -%}
|
| 45 |
+
{{- _ns.result -}}
|
| 46 |
+
{%- elif content is not none -%}
|
| 47 |
+
{{- content | tojson -}}
|
| 48 |
+
{%- endif -%}
|
| 49 |
+
{%- endmacro -%}
|
| 50 |
+
|
| 51 |
+
{%- macro render_tool_calls(tool_calls) -%}
|
| 52 |
+
{%- for tool_call in tool_calls -%}
|
| 53 |
+
{%- if not loop.first -%}{{- "\n\n" -}}{%- endif -%}
|
| 54 |
+
{%- set func = tool_call["function"] if "function" in tool_call else tool_call -%}
|
| 55 |
+
{%- set func_args = func.get("arguments") -%}
|
| 56 |
+
{%- if func_args is string and (func_args | trim) not in ["", "{}", "null"] -%}
|
| 57 |
+
{{- raise_exception("Tool call arguments must be a mapping, got a JSON-encoded string: parse arguments with json.loads() before applying the chat template") -}}
|
| 58 |
+
{%- endif -%}
|
| 59 |
+
{{- "<tool_call>\n<function=" + func["name"] + ">\n" -}}
|
| 60 |
+
{%- if func_args is mapping -%}
|
| 61 |
+
{%- for arg_name, arg_value in func_args.items() -%}
|
| 62 |
+
{{- "<parameter=" + arg_name + ">\n" + render_value(arg_value) + "\n</parameter>\n" -}}
|
| 63 |
+
{%- endfor -%}
|
| 64 |
+
{%- endif -%}
|
| 65 |
+
{{- "</function>\n</tool_call>" -}}
|
| 66 |
+
{%- endfor -%}
|
| 67 |
+
{%- endmacro -%}
|
| 68 |
+
|
| 69 |
+
{%- macro tool_to_json(tool) -%}
|
| 70 |
+
{%- set fn = tool.function if tool.function is defined else tool -%}
|
| 71 |
+
{%- set ns_t = namespace(first=true) -%}
|
| 72 |
+
{{- "{" -}}
|
| 73 |
+
{%- for k, v in fn.items() -%}
|
| 74 |
+
{%- if k != "defer_loading" -%}
|
| 75 |
+
{%- if not ns_t.first -%}{{- ", " -}}{%- endif -%}
|
| 76 |
+
{%- set ns_t.first = false -%}
|
| 77 |
+
{{- k | tojson -}}{{- ": " -}}{{- v | tojson -}}
|
| 78 |
+
{%- endif -%}
|
| 79 |
+
{%- endfor -%}
|
| 80 |
+
{{- "}" -}}
|
| 81 |
+
{%- endmacro -%}
|
| 82 |
+
|
| 83 |
+
{%- macro is_tool_reference(item) -%}
|
| 84 |
+
{{- "1" if item is mapping and item.get("type") == "tool_reference" else "" -}}
|
| 85 |
+
{%- endmacro -%}
|
| 86 |
+
|
| 87 |
+
{%- macro referenced_tool_to_json(name) -%}
|
| 88 |
+
{%- set _ns = namespace(found=none) -%}
|
| 89 |
+
{%- for tool in tools or [] -%}
|
| 90 |
+
{%- set fn = tool.function if tool.function is defined else tool -%}
|
| 91 |
+
{%- if fn.name == name -%}
|
| 92 |
+
{%- set _ns.found = fn -%}
|
| 93 |
+
{%- endif -%}
|
| 94 |
+
{%- endfor -%}
|
| 95 |
+
{%- if _ns.found is none -%}
|
| 96 |
+
{{- raise_exception("Tool reference '" + name | string + "' not found in available tools. Every tool referenced by a tool_reference must be in `tools` on every request.") -}}
|
| 97 |
+
{%- endif -%}
|
| 98 |
+
{{- tool_to_json(_ns.found) -}}
|
| 99 |
+
{%- endmacro -%}
|
| 100 |
+
|
| 101 |
+
{%- macro render_tool_response(content) -%}
|
| 102 |
+
{%- if content is string and "<tool_response>" in content -%}
|
| 103 |
+
{{- content -}}
|
| 104 |
+
{%- else -%}
|
| 105 |
+
{{- "<tool_response>\n" -}}
|
| 106 |
+
{%- if content is string -%}
|
| 107 |
+
{{- content -}}
|
| 108 |
+
{%- elif content is mapping -%}
|
| 109 |
+
{{- parse_content(content) -}}
|
| 110 |
+
{%- elif content is iterable -%}
|
| 111 |
+
{%- for item in content -%}
|
| 112 |
+
{%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
|
| 113 |
+
{%- if is_tool_reference(item) -%}
|
| 114 |
+
{%- if loop.first or not is_tool_reference(loop.previtem) -%}
|
| 115 |
+
{{- "<additional_tools>\n" -}}
|
| 116 |
+
{%- endif -%}
|
| 117 |
+
{{- referenced_tool_to_json(item.name) -}}
|
| 118 |
+
{%- if loop.last or not is_tool_reference(loop.nextitem) -%}
|
| 119 |
+
{{- "\n</additional_tools>" -}}
|
| 120 |
+
{%- endif -%}
|
| 121 |
+
{%- elif item is mapping and item.result is defined and item.result is mapping and item.result.tools is defined -%}
|
| 122 |
+
{{- "<additional_tools>\n" -}}
|
| 123 |
+
{%- set _tl = item.result.tools -%}
|
| 124 |
+
{%- if _tl is string -%}
|
| 125 |
+
{{- _tl -}}
|
| 126 |
+
{%- elif _tl is mapping -%}
|
| 127 |
+
{{- tool_to_json(_tl) -}}
|
| 128 |
+
{%- else -%}
|
| 129 |
+
{%- for t in _tl -%}
|
| 130 |
+
{%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
|
| 131 |
+
{{- tool_to_json(t) -}}
|
| 132 |
+
{%- endfor -%}
|
| 133 |
+
{%- endif -%}
|
| 134 |
+
{{- "\n</additional_tools>" -}}
|
| 135 |
+
{%- else -%}
|
| 136 |
+
{{- parse_content(item) -}}
|
| 137 |
+
{%- endif -%}
|
| 138 |
+
{%- endfor -%}
|
| 139 |
+
{%- elif content is not none -%}
|
| 140 |
+
{{- content | tojson -}}
|
| 141 |
+
{%- endif -%}
|
| 142 |
+
{{- "\n</tool_response>" -}}
|
| 143 |
+
{%- endif -%}
|
| 144 |
+
{%- endmacro -%}
|
| 145 |
+
|
| 146 |
+
{%- set ns = namespace(system_prompt="", last_user_index=-1) -%}
|
| 147 |
+
{%- if messages and messages[0]["role"] == "system" -%}
|
| 148 |
+
{%- if messages[0].get("content") -%}
|
| 149 |
+
{%- set ns.system_prompt = parse_content(messages[0]["content"]) -%}
|
| 150 |
+
{%- endif -%}
|
| 151 |
+
{%- set messages = messages[1:] -%}
|
| 152 |
+
{%- endif -%}
|
| 153 |
+
{%- if tools -%}
|
| 154 |
+
{%- set tools_ns = namespace(lines=[]) -%}
|
| 155 |
+
{%- for tool in tools -%}
|
| 156 |
+
{%- set fn = tool.function if tool.function is defined else tool -%}
|
| 157 |
+
{%- set _dyn = (fn.defer_loading is defined and fn.defer_loading) or (tool.defer_loading is defined and tool.defer_loading) -%}
|
| 158 |
+
{%- if not _dyn -%}
|
| 159 |
+
{%- set tools_ns.lines = tools_ns.lines + [tool_to_json(fn)] -%}
|
| 160 |
+
{%- endif -%}
|
| 161 |
+
{%- endfor -%}
|
| 162 |
+
{%- if tools_ns.lines -%}
|
| 163 |
+
{%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "<tools>\n" + (tools_ns.lines | join("\n")) + "\n</tools>" -%}
|
| 164 |
+
{%- endif -%}
|
| 165 |
+
{%- endif -%}
|
| 166 |
+
{%- if ns.system_prompt -%}
|
| 167 |
+
{{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
|
| 168 |
+
{%- endif -%}
|
| 169 |
+
{%- for message in messages -%}
|
| 170 |
+
{%- if message["role"] == "user" -%}
|
| 171 |
+
{%- set ns.last_user_index = loop.index0 -%}
|
| 172 |
+
{%- endif -%}
|
| 173 |
+
{%- endfor -%}
|
| 174 |
+
{%- set carry = namespace(pending=[]) -%}
|
| 175 |
+
{%- for message in messages -%}
|
| 176 |
+
{%- set _next = messages[loop.index0 + 1] if not loop.last else none -%}
|
| 177 |
+
{%- set _merge = message.role == "tool" and not message.get("additional_tools")
|
| 178 |
+
and _next is not none and _next.role == "tool" and not _next.get("additional_tools")
|
| 179 |
+
and message.get("tool_call_id") and _next.get("tool_call_id") == message.get("tool_call_id") -%}
|
| 180 |
+
{%- set _items = [] -%}
|
| 181 |
+
{%- if message.role == "tool" and not message.get("additional_tools") -%}
|
| 182 |
+
{%- set _c = message.get("content") -%}
|
| 183 |
+
{%- if _c is string -%}
|
| 184 |
+
{%- set _items = [{"type": "text", "text": _c}] if _c else [] -%}
|
| 185 |
+
{%- elif _c is mapping -%}
|
| 186 |
+
{%- set _items = [_c] -%}
|
| 187 |
+
{%- elif _c is iterable -%}
|
| 188 |
+
{%- set _items = _c | list -%}
|
| 189 |
+
{%- elif _c is not none -%}
|
| 190 |
+
{%- set _items = [_c] -%}
|
| 191 |
+
{%- endif -%}
|
| 192 |
+
{%- endif -%}
|
| 193 |
+
{%- if _merge -%}
|
| 194 |
+
{%- set carry.pending = carry.pending + _items -%}
|
| 195 |
+
{%- else -%}
|
| 196 |
+
{{- "<|im_start|>" + message.role + "\n" -}}
|
| 197 |
+
{%- if message.role == "assistant" -%}
|
| 198 |
+
{%- generation -%}
|
| 199 |
+
{%- set thinking = message.thinking if message.thinking is defined else message.reasoning if message.reasoning is defined else message.reasoning_content -%}
|
| 200 |
+
{%- set keep_thinking = preserve_thinking or loop.index0 > ns.last_user_index -%}
|
| 201 |
+
{%- if thinking is defined and keep_thinking -%}
|
| 202 |
+
{{- "<think>" + (thinking or "") + "</think>" -}}
|
| 203 |
+
{%- elif keep_thinking and "</think>" not in (message.get("content") if message.get("content") is string else "") -%}
|
| 204 |
+
{{- "<think></think>" -}}
|
| 205 |
+
{%- endif -%}
|
| 206 |
+
{%- set _cfm_tag = "CONTINUE_FINAL_MESSAGE_TAG " -%}
|
| 207 |
+
{%- set _has_cfm = false -%}
|
| 208 |
+
{%- set content = "" -%}
|
| 209 |
+
{%- if message.get("content") -%}
|
| 210 |
+
{%- set content = parse_content(message.content) -%}
|
| 211 |
+
{%- endif -%}
|
| 212 |
+
{%- if not keep_thinking -%}
|
| 213 |
+
{%- if "</think>" in content -%}
|
| 214 |
+
{%- set content = content.split("</think>")[-1] | trim -%}
|
| 215 |
+
{%- endif -%}
|
| 216 |
+
{%- set content = "<think></think>" + content -%}
|
| 217 |
+
{%- endif -%}
|
| 218 |
+
{%- if content.endswith(_cfm_tag) -%}
|
| 219 |
+
{%- set _has_cfm = true -%}
|
| 220 |
+
{%- set _trunc_len = (content | length) - (_cfm_tag | length) -%}
|
| 221 |
+
{%- set content = content[:_trunc_len] -%}
|
| 222 |
+
{%- endif -%}
|
| 223 |
+
{{- content -}}
|
| 224 |
+
{%- if message.tool_calls -%}
|
| 225 |
+
{{- render_tool_calls(message.tool_calls) -}}
|
| 226 |
+
{%- endif -%}
|
| 227 |
+
{%- if _has_cfm -%}
|
| 228 |
+
{{- _cfm_tag -}}
|
| 229 |
+
{%- endif -%}
|
| 230 |
+
{{- "<|im_end|>\n" -}}
|
| 231 |
+
{%- endgeneration -%}
|
| 232 |
+
{%- elif message.role == "tool" -%}
|
| 233 |
+
{%- if message.get("additional_tools") -%}
|
| 234 |
+
{%- set _at = message["additional_tools"] -%}
|
| 235 |
+
{%- if _at is mapping or (_at is sequence and _at is not string) -%}
|
| 236 |
+
{%- set _src = _at -%}
|
| 237 |
+
{%- else -%}
|
| 238 |
+
{%- set _src = message.get("content") -%}
|
| 239 |
+
{%- endif -%}
|
| 240 |
+
{%- if _src is string and "<tool_response>" in _src -%}
|
| 241 |
+
{{- _src -}}
|
| 242 |
+
{%- elif _src is string and "<additional_tools>" in _src -%}
|
| 243 |
+
{{- "<tool_response>\n" + _src + "\n</tool_response>" -}}
|
| 244 |
+
{%- elif _src -%}
|
| 245 |
+
{{- "<tool_response>\n<additional_tools>\n" -}}
|
| 246 |
+
{%- if _src is string -%}
|
| 247 |
+
{{- _src -}}
|
| 248 |
+
{%- elif _src is mapping -%}
|
| 249 |
+
{{- tool_to_json(_src) -}}
|
| 250 |
+
{%- else -%}
|
| 251 |
+
{%- for t in _src -%}
|
| 252 |
+
{%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
|
| 253 |
+
{{- tool_to_json(t) -}}
|
| 254 |
+
{%- endfor -%}
|
| 255 |
+
{%- endif -%}
|
| 256 |
+
{{- "\n</additional_tools>\n</tool_response>" -}}
|
| 257 |
+
{%- endif -%}
|
| 258 |
+
{%- elif carry.pending -%}
|
| 259 |
+
{{- render_tool_response(carry.pending + _items) -}}
|
| 260 |
+
{%- set carry.pending = [] -%}
|
| 261 |
+
{%- else -%}
|
| 262 |
+
{{- render_tool_response("" if message.get("content") is none else message.get("content")) -}}
|
| 263 |
+
{%- endif -%}
|
| 264 |
+
{{- "<|im_end|>\n" -}}
|
| 265 |
+
{%- else %}
|
| 266 |
+
{%- if message.get("content") -%}
|
| 267 |
+
{{- parse_content(message["content"]) -}}
|
| 268 |
+
{%- endif -%}
|
| 269 |
+
{{- "<|im_end|>\n" -}}
|
| 270 |
+
{%- endif %}
|
| 271 |
+
{%- endif -%}
|
| 272 |
+
{%- endfor -%}
|
| 273 |
+
{%- if add_generation_prompt -%}
|
| 274 |
+
{{- "<|im_start|>assistant\n" -}}
|
| 275 |
+
{%- if enable_thinking -%}
|
| 276 |
+
{{- "<think>" -}}
|
| 277 |
+
{%- else -%}
|
| 278 |
+
{{- "<think></think>" -}}
|
| 279 |
+
{%- endif -%}
|
| 280 |
+
{%- endif -%}
|
config.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Lfm3ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_lfm3.Lfm3Config",
|
| 7 |
+
"AutoModel": "modeling_lfm3.Lfm3Model",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_lfm3.Lfm3ForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 124894,
|
| 11 |
+
"conv_L_cache": 7,
|
| 12 |
+
"conv_bias": false,
|
| 13 |
+
"dtype": "bfloat16",
|
| 14 |
+
"eos_token_id": 124900,
|
| 15 |
+
"head_dim": 128,
|
| 16 |
+
"hidden_size": 2048,
|
| 17 |
+
"initializer_range": 0.02,
|
| 18 |
+
"intermediate_size": 7680,
|
| 19 |
+
"layer_types": [
|
| 20 |
+
"conv",
|
| 21 |
+
"conv",
|
| 22 |
+
"full_attention",
|
| 23 |
+
"conv",
|
| 24 |
+
"sliding_attention",
|
| 25 |
+
"conv",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"conv",
|
| 28 |
+
"sliding_attention",
|
| 29 |
+
"conv",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"conv",
|
| 32 |
+
"sliding_attention",
|
| 33 |
+
"conv",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"conv",
|
| 36 |
+
"sliding_attention",
|
| 37 |
+
"conv",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"conv",
|
| 40 |
+
"sliding_attention",
|
| 41 |
+
"conv",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"conv",
|
| 44 |
+
"sliding_attention",
|
| 45 |
+
"conv",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"conv"
|
| 48 |
+
],
|
| 49 |
+
"max_position_embeddings": 262144,
|
| 50 |
+
"model_type": "lfm3",
|
| 51 |
+
"norm_eps": 1e-05,
|
| 52 |
+
"num_attention_heads": 16,
|
| 53 |
+
"num_hidden_layers": 28,
|
| 54 |
+
"num_key_value_heads": 4,
|
| 55 |
+
"pad_token_id": 124893,
|
| 56 |
+
"rope_parameters": {
|
| 57 |
+
"full_attention": {
|
| 58 |
+
"partial_rotary_factor": 0.5,
|
| 59 |
+
"rope_theta": 1000000.0,
|
| 60 |
+
"rope_type": "default"
|
| 61 |
+
},
|
| 62 |
+
"sliding_attention": {
|
| 63 |
+
"rope_theta": 10000,
|
| 64 |
+
"rope_type": "default"
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
"sliding_window": 256,
|
| 68 |
+
"tie_word_embeddings": true,
|
| 69 |
+
"transformers_version": "5.23.0",
|
| 70 |
+
"use_cache": true,
|
| 71 |
+
"use_sandwich_norm": true,
|
| 72 |
+
"vocab_size": 128000
|
| 73 |
+
}
|
configuration_lfm3.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from huggingface_hub.dataclasses import strict
|
| 15 |
+
|
| 16 |
+
from transformers.configuration_utils import PreTrainedConfig
|
| 17 |
+
from transformers.utils import auto_docstring
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@auto_docstring(checkpoint="LiquidAI/LFM3-1.7B-Preview")
|
| 21 |
+
@strict
|
| 22 |
+
class Lfm3Config(PreTrainedConfig):
|
| 23 |
+
r"""
|
| 24 |
+
rope_parameters (`dict[str, RopeParameters]`, *optional*):
|
| 25 |
+
RoPE parameters keyed by attention layer type, for example `{"full_attention": {"rope_type": "default",
|
| 26 |
+
"rope_theta": 1000000.0, "partial_rotary_factor": 0.5}, "sliding_attention": {"rope_type": "default",
|
| 27 |
+
"rope_theta": 10000.0}}`. `conv` layers do not use RoPE and have no entry. Full-attention layers rotate the
|
| 28 |
+
first `partial_rotary_factor * head_dim` dimensions and leave the rest unrotated.
|
| 29 |
+
conv_bias (`bool`, *optional*, defaults to `False`):
|
| 30 |
+
Whether to use bias in the conv layers.
|
| 31 |
+
conv_L_cache (`int`, *optional*, defaults to 7):
|
| 32 |
+
L_cache dim in the conv layers.
|
| 33 |
+
layer_types (`list[str]`, *optional*):
|
| 34 |
+
Per-layer operator type, each one of `"full_attention"`, `"sliding_attention"` or `"conv"`. Defaults to the
|
| 35 |
+
LFM3 pattern of a full-attention layer every fourth layer starting from the third, a sliding-attention layer
|
| 36 |
+
in between, and gated short convolutions elsewhere.
|
| 37 |
+
sliding_window (`int`, *optional*, defaults to 256):
|
| 38 |
+
Sliding-window size of the `sliding_attention` layers.
|
| 39 |
+
use_sandwich_norm (`bool`, *optional*, defaults to `True`):
|
| 40 |
+
Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream.
|
| 41 |
+
|
| 42 |
+
```python
|
| 43 |
+
>>> from transformers import Lfm3Model, Lfm3Config
|
| 44 |
+
|
| 45 |
+
>>> # Initializing a LFM3 model
|
| 46 |
+
>>> configuration = Lfm3Config()
|
| 47 |
+
|
| 48 |
+
>>> # Initializing a model from the LFM3-1.7B style configuration
|
| 49 |
+
>>> model = Lfm3Model(configuration)
|
| 50 |
+
|
| 51 |
+
>>> # Accessing the model configuration
|
| 52 |
+
>>> configuration = model.config
|
| 53 |
+
```
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
model_type = "lfm3"
|
| 57 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 58 |
+
default_theta = 1000000.0
|
| 59 |
+
|
| 60 |
+
vocab_size: int = 128_000
|
| 61 |
+
hidden_size: int = 2048
|
| 62 |
+
intermediate_size: int = 7680
|
| 63 |
+
num_hidden_layers: int = 24
|
| 64 |
+
num_attention_heads: int = 16
|
| 65 |
+
num_key_value_heads: int = 4
|
| 66 |
+
max_position_embeddings: int = 128_000
|
| 67 |
+
initializer_range: float = 0.02
|
| 68 |
+
norm_eps: float = 0.00001
|
| 69 |
+
use_cache: bool = True
|
| 70 |
+
pad_token_id: int | None = 124_893
|
| 71 |
+
bos_token_id: int | None = 124_894
|
| 72 |
+
eos_token_id: int | list[int] | None = 124_900
|
| 73 |
+
tie_word_embeddings: bool = True
|
| 74 |
+
rope_parameters: dict | None = None
|
| 75 |
+
conv_bias: bool = False
|
| 76 |
+
conv_L_cache: int = 7
|
| 77 |
+
layer_types: list[str] | None = None
|
| 78 |
+
_attention_layer_types = ("full_attention", "sliding_attention")
|
| 79 |
+
head_dim: int | None = None
|
| 80 |
+
sliding_window: int | None = 256
|
| 81 |
+
use_sandwich_norm: bool = True
|
| 82 |
+
|
| 83 |
+
def __post_init__(self, **kwargs):
|
| 84 |
+
if self.head_dim is None:
|
| 85 |
+
self.head_dim = self.hidden_size // self.num_attention_heads
|
| 86 |
+
if self.rope_parameters is None:
|
| 87 |
+
self.rope_parameters = {
|
| 88 |
+
"full_attention": {"rope_type": "default", "rope_theta": 1_000_000.0, "partial_rotary_factor": 0.5},
|
| 89 |
+
"sliding_attention": {"rope_type": "default", "rope_theta": 10_000.0},
|
| 90 |
+
}
|
| 91 |
+
if self.layer_types is None:
|
| 92 |
+
self.layer_types = [
|
| 93 |
+
"full_attention" if i % 4 == 2 else "sliding_attention" if i % 4 == 0 and i > 0 else "conv"
|
| 94 |
+
for i in range(self.num_hidden_layers)
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
self.tie_word_embeddings = kwargs.pop("tie_embedding", self.tie_word_embeddings)
|
| 98 |
+
super().__post_init__(**kwargs)
|
| 99 |
+
|
| 100 |
+
def validate_architecture(self):
|
| 101 |
+
"""Part of ``@strict``-powered validation."""
|
| 102 |
+
if len(self.layer_types) != self.num_hidden_layers:
|
| 103 |
+
raise ValueError(
|
| 104 |
+
f"`layer_types` has {len(self.layer_types)} entries but `num_hidden_layers` is {self.num_hidden_layers}."
|
| 105 |
+
)
|
| 106 |
+
allowed_layer_types = (*self._attention_layer_types, "conv")
|
| 107 |
+
invalid_layer_types = [layer_type for layer_type in self.layer_types if layer_type not in allowed_layer_types]
|
| 108 |
+
if invalid_layer_types:
|
| 109 |
+
raise ValueError(f"`layer_types` entries must be one of {allowed_layer_types}; got {invalid_layer_types}.")
|
| 110 |
+
if "sliding_attention" in self.layer_types and self.sliding_window is None:
|
| 111 |
+
raise ValueError("`layer_types` has `sliding_attention` layers but `sliding_window` is None.")
|
| 112 |
+
missing_rope = [
|
| 113 |
+
layer_type
|
| 114 |
+
for layer_type in self._attention_layer_types
|
| 115 |
+
if layer_type in self.layer_types and layer_type not in self.rope_parameters
|
| 116 |
+
]
|
| 117 |
+
if missing_rope:
|
| 118 |
+
raise ValueError(f"`rope_parameters` has no entry for the {missing_rope} layers in `layer_types`.")
|
| 119 |
+
for layer_type, rope_params in self.rope_parameters.items():
|
| 120 |
+
if not isinstance(rope_params, dict):
|
| 121 |
+
continue
|
| 122 |
+
if (
|
| 123 |
+
rope_params.get("rope_type", "default") in ("dynamic", "longrope")
|
| 124 |
+
and rope_params.get("partial_rotary_factor", 1.0) < 1
|
| 125 |
+
):
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"`{rope_params['rope_type']}` RoPE recomputes its frequencies during the forward pass over the "
|
| 128 |
+
f"rotated dimension only and cannot keep LFM3's partial rotation on `{layer_type}` layers."
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
__all__ = ["Lfm3Config"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 124894,
|
| 4 |
+
"do_sample": true,
|
| 5 |
+
"eos_token_id": [
|
| 6 |
+
124900
|
| 7 |
+
],
|
| 8 |
+
"output_attentions": false,
|
| 9 |
+
"output_hidden_states": false,
|
| 10 |
+
"pad_token_id": 124893,
|
| 11 |
+
"repetition_penalty": 1.1,
|
| 12 |
+
"temperature": 0.1,
|
| 13 |
+
"top_k": 50,
|
| 14 |
+
"transformers_version": "5.23.0",
|
| 15 |
+
"use_cache": true
|
| 16 |
+
}
|
gguf/LFM3-1.7B-loop-8-11-Q8_0.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b5b7783b12548603f914ffca98573937f71eae58da4f44150cc2a050fcab1953
|
| 3 |
+
size 2105032704
|
lfm3_conv.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Inference kernels for LFM3's width-7 depthwise convolution."""
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from transformers.utils import is_triton_available
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if is_triton_available():
|
| 22 |
+
import triton
|
| 23 |
+
import triton.language as tl
|
| 24 |
+
|
| 25 |
+
# the length and strides are runtime arguments, or every prompt length would compile its own kernel
|
| 26 |
+
@triton.jit(do_not_specialize=["T", "X0", "X1", "X2", "S0", "S1", "ST"])
|
| 27 |
+
def _prefill(
|
| 28 |
+
X,
|
| 29 |
+
W,
|
| 30 |
+
BIAS,
|
| 31 |
+
SEQ,
|
| 32 |
+
Y,
|
| 33 |
+
T,
|
| 34 |
+
D: tl.constexpr,
|
| 35 |
+
X0,
|
| 36 |
+
X1,
|
| 37 |
+
X2,
|
| 38 |
+
S0,
|
| 39 |
+
S1,
|
| 40 |
+
ST,
|
| 41 |
+
HAS_BIAS: tl.constexpr,
|
| 42 |
+
PACKED: tl.constexpr,
|
| 43 |
+
BLOCK: tl.constexpr,
|
| 44 |
+
):
|
| 45 |
+
# int64 offsets: batch * channels * length can exceed 2**31 elements
|
| 46 |
+
b, d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
|
| 47 |
+
t = tl.program_id(2).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
|
| 48 |
+
acc = tl.full((BLOCK,), 0, tl.float32)
|
| 49 |
+
if PACKED:
|
| 50 |
+
doc = tl.load(SEQ + b * S0 + (t - T + ST) * S1, (t < T) & (t >= T - ST), other=-1)
|
| 51 |
+
for k in tl.static_range(7):
|
| 52 |
+
pos = t + k - 6
|
| 53 |
+
valid = (t < T) & (pos >= 0)
|
| 54 |
+
if PACKED:
|
| 55 |
+
prev = tl.load(SEQ + b * S0 + (pos - T + ST) * S1, valid & (pos >= T - ST), other=-1)
|
| 56 |
+
valid = valid & (doc == prev)
|
| 57 |
+
x = tl.load(X + b * X0 + d * X1 + pos * X2, valid, other=0).to(tl.float32)
|
| 58 |
+
w = tl.load(W + d * 7 + k).to(tl.float32)
|
| 59 |
+
acc += x * w
|
| 60 |
+
if HAS_BIAS:
|
| 61 |
+
acc += tl.load(BIAS + d).to(tl.float32)
|
| 62 |
+
tl.store(Y + (b * D + d) * T + t, acc, t < T)
|
| 63 |
+
|
| 64 |
+
@triton.jit
|
| 65 |
+
def _decode(
|
| 66 |
+
X,
|
| 67 |
+
W,
|
| 68 |
+
BIAS,
|
| 69 |
+
STATE,
|
| 70 |
+
Y,
|
| 71 |
+
D: tl.constexpr,
|
| 72 |
+
K: tl.constexpr,
|
| 73 |
+
X0: tl.constexpr,
|
| 74 |
+
X1: tl.constexpr,
|
| 75 |
+
S0: tl.constexpr,
|
| 76 |
+
S1: tl.constexpr,
|
| 77 |
+
S2: tl.constexpr,
|
| 78 |
+
HAS_BIAS: tl.constexpr,
|
| 79 |
+
BLOCK: tl.constexpr,
|
| 80 |
+
):
|
| 81 |
+
b = tl.program_id(0).to(tl.int64)
|
| 82 |
+
d = tl.program_id(1).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
|
| 83 |
+
k = tl.arange(0, 8)
|
| 84 |
+
# Load the complete state before writing the shifted window.
|
| 85 |
+
old = tl.load(STATE + b * S0 + d[:, None] * S1 + k[None, :] * S2, (d[:, None] < D) & (k[None, :] < K), other=0)
|
| 86 |
+
x = tl.load(X + b * X0 + d * X1, d < D, other=0)
|
| 87 |
+
shifted = tl.gather(old, tl.broadcast_to(tl.minimum(k + 1, 7)[None, :], (BLOCK, 8)), 1)
|
| 88 |
+
shifted = tl.where(k[None, :] == K - 1, x[:, None], shifted)
|
| 89 |
+
# A cache may store either K=6 previous inputs or K=7 including the oldest discarded input.
|
| 90 |
+
positions = k + K - 6
|
| 91 |
+
values = tl.gather(old, tl.broadcast_to(tl.minimum(positions, 7)[None, :], (BLOCK, 8)), 1)
|
| 92 |
+
values = tl.where(k[None, :] == 6, x[:, None], values)
|
| 93 |
+
weights = tl.load(W + d[:, None] * 7 + k[None, :], (d[:, None] < D) & (k[None, :] < 7), other=0)
|
| 94 |
+
acc = tl.sum(values.to(tl.float32) * weights.to(tl.float32), 1)
|
| 95 |
+
if HAS_BIAS:
|
| 96 |
+
acc += tl.load(BIAS + d, d < D, other=0).to(tl.float32)
|
| 97 |
+
tl.store(STATE + b * S0 + d[:, None] * S1 + k[None, :] * S2, shifted, (d[:, None] < D) & (k[None, :] < K))
|
| 98 |
+
tl.store(Y + b * D + d, acc, d < D)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def can_use_lfm3_conv(hidden_states, weight):
|
| 102 |
+
return (
|
| 103 |
+
is_triton_available()
|
| 104 |
+
and hasattr(tl, "gather") # the decode kernel needs Triton >= 3.3
|
| 105 |
+
and hidden_states.is_cuda
|
| 106 |
+
and not torch.is_grad_enabled()
|
| 107 |
+
and hidden_states.dtype == weight.dtype
|
| 108 |
+
and hidden_states.dtype in (torch.float16, torch.bfloat16, torch.float32)
|
| 109 |
+
and weight.shape[-1] == 7
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def lfm3_causal_conv1d(hidden_states, weight, bias=None, seq_idx=None):
|
| 114 |
+
batch, channels, length = hidden_states.shape
|
| 115 |
+
# the kernels index every tensor by the batch and channel of `hidden_states` and cannot bound the others
|
| 116 |
+
if weight.shape != (channels, 7) or (bias is not None and bias.shape != (channels,)):
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"`weight` must have shape ({channels}, 7) and `bias` ({channels},), got {tuple(weight.shape)}"
|
| 119 |
+
)
|
| 120 |
+
if seq_idx is not None and (
|
| 121 |
+
seq_idx.ndim != 2 or seq_idx.shape[0] not in (1, batch) or seq_idx.dtype not in (torch.int32, torch.int64)
|
| 122 |
+
):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"`seq_idx` must be an int32 or int64 tensor of shape (1, length) or ({batch}, length), got "
|
| 125 |
+
f"{seq_idx.dtype} {tuple(seq_idx.shape)}"
|
| 126 |
+
)
|
| 127 |
+
if any(t is not None and t.device != hidden_states.device for t in (weight, bias, seq_idx)):
|
| 128 |
+
raise ValueError(
|
| 129 |
+
f"`weight`, `bias` and `seq_idx` must be on the device of `hidden_states` ({hidden_states.device})"
|
| 130 |
+
)
|
| 131 |
+
output = torch.empty_like(hidden_states, memory_format=torch.contiguous_format)
|
| 132 |
+
# Triton launches on the current device; the model may live on another one (`device_map`, `.to("cuda:1")`).
|
| 133 |
+
with torch.cuda.device(hidden_states.device):
|
| 134 |
+
_prefill[(batch, channels, triton.cdiv(length, 128))](
|
| 135 |
+
hidden_states,
|
| 136 |
+
# the kernels index `bias` and `weight` densely
|
| 137 |
+
weight.contiguous(),
|
| 138 |
+
bias.contiguous() if bias is not None else None,
|
| 139 |
+
seq_idx,
|
| 140 |
+
output,
|
| 141 |
+
length,
|
| 142 |
+
channels,
|
| 143 |
+
*hidden_states.stride(),
|
| 144 |
+
*(
|
| 145 |
+
(0 if seq_idx.shape[0] == 1 else seq_idx.stride(0), seq_idx.stride(1))
|
| 146 |
+
if seq_idx is not None
|
| 147 |
+
else (0, 0)
|
| 148 |
+
),
|
| 149 |
+
seq_idx.shape[-1] if seq_idx is not None else 0,
|
| 150 |
+
bias is not None,
|
| 151 |
+
seq_idx is not None,
|
| 152 |
+
128,
|
| 153 |
+
enable_fp_fusion=False,
|
| 154 |
+
)
|
| 155 |
+
return output
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def lfm3_causal_conv1d_update(hidden_states, conv_state, weight, bias=None):
|
| 159 |
+
batch, channels, length = hidden_states.shape
|
| 160 |
+
# the kernel addresses one position per row and bounds nothing by the other tensors' shapes
|
| 161 |
+
if length != 1:
|
| 162 |
+
raise ValueError(f"`hidden_states` must hold one position per row, got {tuple(hidden_states.shape)}")
|
| 163 |
+
# the 8-wide tile holds a 6- or 7-wide state (see `positions` in `_decode`)
|
| 164 |
+
if (
|
| 165 |
+
conv_state.ndim != 3
|
| 166 |
+
or conv_state.shape[:2] != (batch, channels)
|
| 167 |
+
or conv_state.shape[-1] not in (6, 7)
|
| 168 |
+
or weight.shape != (channels, 7)
|
| 169 |
+
):
|
| 170 |
+
raise ValueError(
|
| 171 |
+
f"`conv_state` must have shape ({batch}, {channels}, 6 or 7) and `weight` ({channels}, 7), got "
|
| 172 |
+
f"{tuple(conv_state.shape)} and {tuple(weight.shape)}"
|
| 173 |
+
)
|
| 174 |
+
if bias is not None and bias.shape != (channels,):
|
| 175 |
+
raise ValueError(f"`bias` must have shape ({channels},), got {tuple(bias.shape)}")
|
| 176 |
+
# the kernel writes the state in place: rows or channels sharing memory (an `expand`ed cache) would race
|
| 177 |
+
extent = 0
|
| 178 |
+
for stride, size in sorted(zip(conv_state.stride(), conv_state.shape)):
|
| 179 |
+
if size > 1 and stride <= extent:
|
| 180 |
+
raise ValueError(f"`conv_state` must not overlap itself, got strides {conv_state.stride()}")
|
| 181 |
+
extent += stride * (size - 1)
|
| 182 |
+
if any(t is not None and t.device != hidden_states.device for t in (conv_state, weight, bias)):
|
| 183 |
+
raise ValueError(
|
| 184 |
+
f"`conv_state`, `weight` and `bias` must be on the device of `hidden_states` ({hidden_states.device})"
|
| 185 |
+
)
|
| 186 |
+
output = torch.empty_like(hidden_states, memory_format=torch.contiguous_format)
|
| 187 |
+
with torch.cuda.device(hidden_states.device):
|
| 188 |
+
_decode[(batch, triton.cdiv(channels, 32))](
|
| 189 |
+
hidden_states,
|
| 190 |
+
weight.contiguous(),
|
| 191 |
+
bias.contiguous() if bias is not None else None,
|
| 192 |
+
conv_state,
|
| 193 |
+
output,
|
| 194 |
+
channels,
|
| 195 |
+
conv_state.shape[-1],
|
| 196 |
+
*hidden_states.stride()[:2],
|
| 197 |
+
*conv_state.stride(),
|
| 198 |
+
bias is not None,
|
| 199 |
+
32,
|
| 200 |
+
enable_fp_fusion=False,
|
| 201 |
+
)
|
| 202 |
+
return output
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eedf275204676448852a4ba6bf0c0f6f12e2d1cd0de5aadb247757d45e39c616
|
| 3 |
+
size 3944435160
|
modeling_lfm3.py
ADDED
|
@@ -0,0 +1,881 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import copy
|
| 15 |
+
from collections.abc import Callable
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from torch import nn
|
| 20 |
+
|
| 21 |
+
from transformers import initialization as init
|
| 22 |
+
from transformers.activations import ACT2FN
|
| 23 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 24 |
+
from transformers.configuration_utils import PreTrainedConfig
|
| 25 |
+
from transformers.generation import GenerationMixin
|
| 26 |
+
from transformers.integrations import (
|
| 27 |
+
use_kernel_forward_from_hub,
|
| 28 |
+
use_kernel_func_from_hub_with_fallback,
|
| 29 |
+
use_kernelized_func,
|
| 30 |
+
)
|
| 31 |
+
from transformers.integrations.accelerate import force_accelerate_hooks
|
| 32 |
+
from transformers.masking_utils import (
|
| 33 |
+
create_causal_mask,
|
| 34 |
+
create_recurrent_attention_mask,
|
| 35 |
+
create_sliding_window_causal_mask,
|
| 36 |
+
)
|
| 37 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 38 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 39 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 40 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 41 |
+
from transformers.processing_utils import Unpack
|
| 42 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
|
| 43 |
+
from transformers.utils.generic import merge_with_config_defaults
|
| 44 |
+
from transformers.utils.import_utils import is_tracing
|
| 45 |
+
from transformers.utils.output_capturing import capture_outputs
|
| 46 |
+
|
| 47 |
+
from .configuration_lfm3 import Lfm3Config
|
| 48 |
+
from .lfm3_conv import can_use_lfm3_conv, lfm3_causal_conv1d, lfm3_causal_conv1d_update
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 52 |
+
class Lfm3RMSNorm(nn.Module):
|
| 53 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 54 |
+
"""
|
| 55 |
+
Lfm3RMSNorm is equivalent to T5LayerNorm
|
| 56 |
+
"""
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 59 |
+
self.variance_epsilon = eps
|
| 60 |
+
|
| 61 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 62 |
+
input_dtype = hidden_states.dtype
|
| 63 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 64 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 65 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 66 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 67 |
+
|
| 68 |
+
def extra_repr(self):
|
| 69 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class Lfm3RotaryEmbedding(nn.Module):
|
| 73 |
+
"""
|
| 74 |
+
Rotary embedding per attention layer type, like Gemma 3; `conv` layers register no buffers. Partial RoPE keeps the
|
| 75 |
+
frequency progression of the full head dimension and zeroes the tail instead of shrinking the rotated dimension.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, config: Lfm3Config, device=None):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 81 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 82 |
+
self.config = config
|
| 83 |
+
self.layer_types = sorted(set(config.layer_types) & set(config.rope_parameters))
|
| 84 |
+
self.rope_type = {}
|
| 85 |
+
for layer_type in self.layer_types:
|
| 86 |
+
rope_params = self.config.rope_parameters[layer_type]
|
| 87 |
+
self.rope_type[layer_type] = rope_params["rope_type"]
|
| 88 |
+
curr_inv_freq, curr_attention_scaling = self.compute_rope_parameters(config, device, layer_type=layer_type)
|
| 89 |
+
setattr(self, f"{layer_type}_inv_freq", nn.Buffer(curr_inv_freq, persistent=False))
|
| 90 |
+
setattr(self, f"{layer_type}_original_inv_freq", nn.Buffer(curr_inv_freq.clone(), persistent=False))
|
| 91 |
+
setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def compute_default_rope_parameters(
|
| 95 |
+
config: Lfm3Config, device=None, layer_type: str | None = None, **kwargs
|
| 96 |
+
) -> tuple[torch.Tensor, float]:
|
| 97 |
+
"""
|
| 98 |
+
Inverse frequencies of the default RoPE with LFM3's zero-tail partial rotation: the first
|
| 99 |
+
`partial_rotary_factor * head_dim // 2` frequencies follow the progression of the full head dimension and the
|
| 100 |
+
rest are zero, leaving those dimensions unrotated.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
Tuple of (`torch.Tensor`, `float`): the inverse frequencies and the attention scaling factor (always 1).
|
| 104 |
+
"""
|
| 105 |
+
base = config.rope_parameters[layer_type]["rope_theta"]
|
| 106 |
+
partial_rotary_factor = config.rope_parameters[layer_type].get("partial_rotary_factor", 1.0)
|
| 107 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 108 |
+
rope_angles = int(partial_rotary_factor * dim) // 2
|
| 109 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, 2 * rope_angles, 2, dtype=torch.float) / dim))
|
| 110 |
+
inv_freq = torch.cat((inv_freq, torch.zeros(dim // 2 - rope_angles, dtype=torch.float)))
|
| 111 |
+
return inv_freq.to(device), 1.0
|
| 112 |
+
|
| 113 |
+
@torch.no_grad()
|
| 114 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 115 |
+
def forward(self, x, position_ids, layer_type):
|
| 116 |
+
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
| 117 |
+
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
|
| 118 |
+
|
| 119 |
+
freqs = position_ids[..., None].float() * inv_freq.to(device=x.device, dtype=torch.float)
|
| 120 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 121 |
+
cos = emb.cos() * attention_scaling
|
| 122 |
+
sin = emb.sin() * attention_scaling
|
| 123 |
+
|
| 124 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
def compute_rope_parameters(
|
| 128 |
+
cls, config: Lfm3Config, device=None, layer_type: str | None = None
|
| 129 |
+
) -> tuple[torch.Tensor, float]:
|
| 130 |
+
"""Inverse frequencies of any RoPE type in the zero-tail layout: scaled types are evaluated over the full head
|
| 131 |
+
dimension and truncated to the rotated prefix."""
|
| 132 |
+
rope_params = config.rope_parameters[layer_type]
|
| 133 |
+
if rope_params["rope_type"] == "default":
|
| 134 |
+
return cls.compute_default_rope_parameters(config, device, layer_type=layer_type)
|
| 135 |
+
full_config = copy.copy(config)
|
| 136 |
+
full_config.rope_parameters = {
|
| 137 |
+
**config.rope_parameters,
|
| 138 |
+
layer_type: {**rope_params, "partial_rotary_factor": 1.0},
|
| 139 |
+
}
|
| 140 |
+
inv_freq, attention_factor = ROPE_INIT_FUNCTIONS[rope_params["rope_type"]](
|
| 141 |
+
full_config, device, layer_type=layer_type
|
| 142 |
+
)
|
| 143 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 144 |
+
rope_angles = int(rope_params.get("partial_rotary_factor", 1.0) * dim) // 2
|
| 145 |
+
inv_freq = torch.cat((inv_freq[:rope_angles], inv_freq.new_zeros(dim // 2 - rope_angles)))
|
| 146 |
+
return inv_freq, attention_factor
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Lfm3MLP(nn.Module):
|
| 150 |
+
def __init__(self, config: Lfm3Config):
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.w1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 153 |
+
self.w3 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 154 |
+
self.w2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 155 |
+
|
| 156 |
+
def forward(self, x):
|
| 157 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def rotate_half(x):
|
| 161 |
+
"""Rotates half the hidden dims of the input."""
|
| 162 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 163 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 164 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 168 |
+
"""
|
| 169 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 170 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 171 |
+
"""
|
| 172 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 173 |
+
if n_rep == 1:
|
| 174 |
+
return hidden_states
|
| 175 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 176 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def eager_attention_forward(
|
| 180 |
+
module: nn.Module,
|
| 181 |
+
query: torch.Tensor,
|
| 182 |
+
key: torch.Tensor,
|
| 183 |
+
value: torch.Tensor,
|
| 184 |
+
attention_mask: torch.Tensor | None,
|
| 185 |
+
scaling: float,
|
| 186 |
+
dropout: float = 0.0,
|
| 187 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 188 |
+
):
|
| 189 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 190 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 191 |
+
|
| 192 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 193 |
+
if attention_mask is not None:
|
| 194 |
+
attn_weights = attn_weights + attention_mask
|
| 195 |
+
|
| 196 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 197 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 198 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 199 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 200 |
+
|
| 201 |
+
return attn_output, attn_weights
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 205 |
+
"""Applies RoPE to the query and key tensors in float32, like the reference implementation."""
|
| 206 |
+
cos = cos.unsqueeze(unsqueeze_dim).float()
|
| 207 |
+
sin = sin.unsqueeze(unsqueeze_dim).float()
|
| 208 |
+
q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
|
| 209 |
+
k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
|
| 210 |
+
return q_embed.to(q.dtype), k_embed.to(k.dtype)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class Lfm3Attention(nn.Module):
|
| 214 |
+
"""Llama attention with QK RMSNorm, a sigmoid output gate per head, a sliding window on `sliding_attention`
|
| 215 |
+
layers and RoPE in float32."""
|
| 216 |
+
|
| 217 |
+
def __init__(self, config: Lfm3Config, layer_idx: int):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.config = config
|
| 220 |
+
self.layer_idx = layer_idx
|
| 221 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 222 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 223 |
+
self.scaling = self.head_dim**-0.5
|
| 224 |
+
self.is_causal = True
|
| 225 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 226 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 227 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 228 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 229 |
+
self.q_norm = Lfm3RMSNorm(self.head_dim, eps=config.norm_eps)
|
| 230 |
+
self.k_norm = Lfm3RMSNorm(self.head_dim, eps=config.norm_eps)
|
| 231 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.num_attention_heads, bias=False)
|
| 232 |
+
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
|
| 233 |
+
|
| 234 |
+
def forward(
|
| 235 |
+
self,
|
| 236 |
+
hidden_states: torch.Tensor,
|
| 237 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 238 |
+
attention_mask: torch.Tensor | None,
|
| 239 |
+
past_key_values: Cache | None = None,
|
| 240 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 241 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 242 |
+
input_shape = hidden_states.shape[:-1]
|
| 243 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 244 |
+
|
| 245 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
|
| 246 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
|
| 247 |
+
value_states = self.v_proj(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 248 |
+
|
| 249 |
+
cos, sin = position_embeddings
|
| 250 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 251 |
+
|
| 252 |
+
if past_key_values is not None:
|
| 253 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 254 |
+
|
| 255 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 256 |
+
self.config._attn_implementation, eager_attention_forward
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
attn_output, attn_weights = attention_interface(
|
| 260 |
+
self,
|
| 261 |
+
query_states,
|
| 262 |
+
key_states,
|
| 263 |
+
value_states,
|
| 264 |
+
attention_mask,
|
| 265 |
+
dropout=0.0,
|
| 266 |
+
scaling=self.scaling,
|
| 267 |
+
sliding_window=self.sliding_window,
|
| 268 |
+
**kwargs,
|
| 269 |
+
)
|
| 270 |
+
gate = torch.sigmoid(self.gate_proj(hidden_states)).unsqueeze(-1)
|
| 271 |
+
attn_output = (attn_output * gate).reshape(*input_shape, -1).contiguous()
|
| 272 |
+
attn_output = self.o_proj(attn_output)
|
| 273 |
+
return attn_output, attn_weights
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def apply_mask_to_padding_states(hidden_states, attention_mask):
|
| 277 |
+
"""
|
| 278 |
+
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 279 |
+
"""
|
| 280 |
+
# NOTE: attention mask is a 2D boolean tensor
|
| 281 |
+
if attention_mask is not None:
|
| 282 |
+
dtype = hidden_states.dtype
|
| 283 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 284 |
+
|
| 285 |
+
return hidden_states
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@use_kernel_func_from_hub_with_fallback("causal_conv1d_update", "causal_conv1d")
|
| 289 |
+
def causal_conv1d_update(
|
| 290 |
+
hidden_states: torch.Tensor,
|
| 291 |
+
conv_state: torch.Tensor,
|
| 292 |
+
weight: nn.Parameter,
|
| 293 |
+
bias: nn.Parameter | None = None,
|
| 294 |
+
activation: str | None = None,
|
| 295 |
+
):
|
| 296 |
+
_, hidden_size, seq_len = hidden_states.shape
|
| 297 |
+
state_len = conv_state.shape[-1]
|
| 298 |
+
|
| 299 |
+
hidden_states_new = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype)
|
| 300 |
+
conv_state.copy_(hidden_states_new[:, :, -state_len:])
|
| 301 |
+
out = F.conv1d(hidden_states_new, weight.unsqueeze(1), bias, padding=0, groups=hidden_size)
|
| 302 |
+
out = out[:, :, -seq_len:]
|
| 303 |
+
if activation is not None:
|
| 304 |
+
out = ACT2FN[activation](out)
|
| 305 |
+
return out.to(hidden_states.dtype)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@use_kernel_func_from_hub_with_fallback("causal_conv1d_fn", "causal_conv1d")
|
| 309 |
+
def causal_conv1d_fn(
|
| 310 |
+
hidden_states: torch.Tensor,
|
| 311 |
+
weight: nn.Parameter,
|
| 312 |
+
bias: nn.Parameter | None = None,
|
| 313 |
+
activation: str | None = None,
|
| 314 |
+
**kwargs,
|
| 315 |
+
):
|
| 316 |
+
_, hidden_size, seq_len = hidden_states.shape
|
| 317 |
+
padding = weight.shape[-1] - 1
|
| 318 |
+
|
| 319 |
+
out = F.conv1d(
|
| 320 |
+
hidden_states.to(weight.dtype),
|
| 321 |
+
weight=weight.unsqueeze(1),
|
| 322 |
+
bias=bias,
|
| 323 |
+
padding=padding,
|
| 324 |
+
groups=hidden_size,
|
| 325 |
+
)[:, :, :seq_len]
|
| 326 |
+
if activation is not None:
|
| 327 |
+
out = ACT2FN[activation](out)
|
| 328 |
+
return out.to(hidden_states.dtype)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
@use_kernelized_func([causal_conv1d_update, causal_conv1d_fn])
|
| 332 |
+
class Lfm3ShortConv(nn.Module):
|
| 333 |
+
"""LFM2 gated short convolution with packed-document boundaries (`seq_idx`), the padding mask re-applied after a
|
| 334 |
+
biased `in_proj`, and width-7 Triton inference kernels with a PyTorch fallback."""
|
| 335 |
+
|
| 336 |
+
def __init__(
|
| 337 |
+
self,
|
| 338 |
+
config: Lfm3Config,
|
| 339 |
+
layer_idx: int,
|
| 340 |
+
):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.config = config
|
| 343 |
+
self.layer_idx = layer_idx
|
| 344 |
+
self.conv_kernel_size = config.conv_L_cache
|
| 345 |
+
self.bias = config.conv_bias
|
| 346 |
+
|
| 347 |
+
self.conv = nn.Conv1d(
|
| 348 |
+
in_channels=config.hidden_size,
|
| 349 |
+
out_channels=config.hidden_size,
|
| 350 |
+
kernel_size=self.conv_kernel_size,
|
| 351 |
+
groups=config.hidden_size,
|
| 352 |
+
bias=self.bias,
|
| 353 |
+
padding=self.conv_kernel_size - 1,
|
| 354 |
+
)
|
| 355 |
+
self.in_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=self.bias)
|
| 356 |
+
self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=self.bias)
|
| 357 |
+
|
| 358 |
+
self.layer_type = config.layer_types[layer_idx]
|
| 359 |
+
|
| 360 |
+
@force_accelerate_hooks("conv")
|
| 361 |
+
def forward(
|
| 362 |
+
self,
|
| 363 |
+
hidden_states: torch.Tensor,
|
| 364 |
+
past_key_values: Cache | None = None,
|
| 365 |
+
attention_mask: torch.Tensor | None = None,
|
| 366 |
+
seq_idx: torch.IntTensor | None = None,
|
| 367 |
+
):
|
| 368 |
+
seq_len = hidden_states.shape[1]
|
| 369 |
+
|
| 370 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 371 |
+
BCx = self.in_proj(hidden_states).transpose(-1, -2)
|
| 372 |
+
B, C, x = BCx.chunk(3, dim=-2)
|
| 373 |
+
hidden_states = B * x
|
| 374 |
+
if attention_mask is not None:
|
| 375 |
+
# with `conv_bias` the projection makes the padded positions non-zero again
|
| 376 |
+
hidden_states = hidden_states * attention_mask[:, None, :].to(hidden_states.dtype)
|
| 377 |
+
|
| 378 |
+
use_precomputed_states = past_key_values is not None and past_key_values.has_previous_state(self.layer_idx)
|
| 379 |
+
use_kernels = 2 <= self.conv_kernel_size <= 4
|
| 380 |
+
use_wide_kernel = can_use_lfm3_conv(hidden_states, self.conv.weight)
|
| 381 |
+
|
| 382 |
+
if use_precomputed_states and seq_len == 1 and not past_key_values.layers[self.layer_idx].record_past:
|
| 383 |
+
conv_state = past_key_values.layers[self.layer_idx].conv_states[0]
|
| 384 |
+
if use_wide_kernel and conv_state.shape[-1] in (6, 7):
|
| 385 |
+
hidden_states = lfm3_causal_conv1d_update(
|
| 386 |
+
hidden_states, conv_state, self.conv.weight.squeeze(1), self.conv.bias
|
| 387 |
+
)
|
| 388 |
+
elif use_kernels:
|
| 389 |
+
hidden_states = causal_conv1d_update(
|
| 390 |
+
hidden_states, conv_state, self.conv.weight.squeeze(1), self.conv.bias
|
| 391 |
+
)
|
| 392 |
+
else:
|
| 393 |
+
hidden_states = torch.cat([conv_state, hidden_states], dim=-1)
|
| 394 |
+
conv_state.copy_(hidden_states[:, :, -conv_state.shape[-1] :])
|
| 395 |
+
hidden_states = self._conv(hidden_states)[:, :, -seq_len:]
|
| 396 |
+
else:
|
| 397 |
+
if past_key_values is not None and seq_idx is not None:
|
| 398 |
+
# `seq_idx` is only set on an empty cache, and the decode steps read the cached window without it:
|
| 399 |
+
# only the last document (after any positional left padding) may enter the window
|
| 400 |
+
last_document = (seq_idx == seq_idx[:, -1:])[:, None].to(hidden_states.dtype)
|
| 401 |
+
past_key_values.update_conv_state(
|
| 402 |
+
hidden_states * last_document, self.layer_idx, conv_kernel_size=self.conv_kernel_size
|
| 403 |
+
)
|
| 404 |
+
elif past_key_values is not None:
|
| 405 |
+
hidden_states = past_key_values.update_conv_state(
|
| 406 |
+
hidden_states, self.layer_idx, conv_kernel_size=self.conv_kernel_size
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
if use_wide_kernel:
|
| 410 |
+
hidden_states = lfm3_causal_conv1d(hidden_states, self.conv.weight.squeeze(1), self.conv.bias, seq_idx)
|
| 411 |
+
elif seq_idx is not None:
|
| 412 |
+
hidden_states = self._segmented_conv(hidden_states, seq_idx)
|
| 413 |
+
elif use_kernels:
|
| 414 |
+
hidden_states = causal_conv1d_fn(hidden_states, self.conv.weight.squeeze(1), self.conv.bias)
|
| 415 |
+
else:
|
| 416 |
+
hidden_states = self._conv(hidden_states)
|
| 417 |
+
|
| 418 |
+
# Drop the additional previous states
|
| 419 |
+
if past_key_values is not None:
|
| 420 |
+
hidden_states = hidden_states[:, :, -seq_len:]
|
| 421 |
+
|
| 422 |
+
y = C * hidden_states
|
| 423 |
+
y = y.transpose(-1, -2).contiguous()
|
| 424 |
+
y = self.out_proj(y)
|
| 425 |
+
return y
|
| 426 |
+
|
| 427 |
+
def _conv(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 428 |
+
"""Causal depthwise conv in torch: the `causal_conv1d` kernels only accept widths 2 to 4."""
|
| 429 |
+
conv_out = self.conv(hidden_states.to(self.conv.weight.dtype))[..., : hidden_states.shape[-1]]
|
| 430 |
+
return conv_out.to(hidden_states.dtype)
|
| 431 |
+
|
| 432 |
+
def _segmented_conv(self, hidden_states: torch.Tensor, seq_idx: torch.Tensor) -> torch.Tensor:
|
| 433 |
+
"""Causal depthwise conv that only reads positions sharing the current token's document index."""
|
| 434 |
+
kernel_size = self.conv_kernel_size
|
| 435 |
+
seq_idx = F.pad(seq_idx, (hidden_states.shape[-1] - seq_idx.shape[-1] + kernel_size - 1, 0), value=-1)
|
| 436 |
+
windows = F.pad(hidden_states, (kernel_size - 1, 0)).unfold(-1, kernel_size, 1)
|
| 437 |
+
seq_idx_windows = seq_idx.unfold(-1, kernel_size, 1)
|
| 438 |
+
same_document = (seq_idx_windows == seq_idx_windows[..., -1:]).unsqueeze(1)
|
| 439 |
+
conv_out = torch.einsum("bdtk,dk->bdt", windows * same_document.to(windows.dtype), self.conv.weight.squeeze(1))
|
| 440 |
+
if self.bias:
|
| 441 |
+
conv_out = conv_out + self.conv.bias[None, :, None]
|
| 442 |
+
return conv_out.to(hidden_states.dtype)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class Lfm3DecoderLayer(GradientCheckpointingLayer):
|
| 446 |
+
def __init__(self, config: Lfm3Config, layer_idx: int):
|
| 447 |
+
super().__init__()
|
| 448 |
+
self.is_attention_layer = config.layer_types[layer_idx] in config._attention_layer_types
|
| 449 |
+
self.use_sandwich_norm = config.use_sandwich_norm
|
| 450 |
+
|
| 451 |
+
if self.is_attention_layer:
|
| 452 |
+
self.self_attn = Lfm3Attention(config, layer_idx)
|
| 453 |
+
else:
|
| 454 |
+
self.conv = Lfm3ShortConv(config, layer_idx)
|
| 455 |
+
self.feed_forward = Lfm3MLP(config)
|
| 456 |
+
self.operator_norm = Lfm3RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 457 |
+
self.ffn_norm = Lfm3RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 458 |
+
if self.use_sandwich_norm:
|
| 459 |
+
self.post_operator_norm = Lfm3RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 460 |
+
self.post_ffn_norm = Lfm3RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 461 |
+
|
| 462 |
+
def forward(
|
| 463 |
+
self,
|
| 464 |
+
hidden_states: torch.Tensor,
|
| 465 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 466 |
+
attention_mask: torch.Tensor | None = None,
|
| 467 |
+
position_ids: torch.LongTensor | None = None,
|
| 468 |
+
past_key_values: Cache | None = None,
|
| 469 |
+
seq_idx: torch.IntTensor | None = None,
|
| 470 |
+
**kwargs,
|
| 471 |
+
) -> torch.Tensor:
|
| 472 |
+
residual = hidden_states
|
| 473 |
+
if self.is_attention_layer:
|
| 474 |
+
hidden_states, _ = self.self_attn(
|
| 475 |
+
hidden_states=self.operator_norm(hidden_states),
|
| 476 |
+
position_embeddings=position_embeddings,
|
| 477 |
+
attention_mask=attention_mask,
|
| 478 |
+
position_ids=position_ids,
|
| 479 |
+
past_key_values=past_key_values,
|
| 480 |
+
**kwargs,
|
| 481 |
+
)
|
| 482 |
+
else:
|
| 483 |
+
hidden_states = self.conv(
|
| 484 |
+
hidden_states=self.operator_norm(hidden_states),
|
| 485 |
+
past_key_values=past_key_values,
|
| 486 |
+
attention_mask=attention_mask,
|
| 487 |
+
seq_idx=seq_idx,
|
| 488 |
+
)
|
| 489 |
+
if self.use_sandwich_norm:
|
| 490 |
+
hidden_states = self.post_operator_norm(hidden_states)
|
| 491 |
+
hidden_states = hidden_states + residual
|
| 492 |
+
|
| 493 |
+
ffn_out = self.feed_forward(self.ffn_norm(hidden_states))
|
| 494 |
+
if self.use_sandwich_norm:
|
| 495 |
+
ffn_out = self.post_ffn_norm(ffn_out)
|
| 496 |
+
hidden_states = hidden_states + ffn_out
|
| 497 |
+
|
| 498 |
+
return hidden_states
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def create_masks_by_layer_type(
|
| 502 |
+
config: PreTrainedConfig,
|
| 503 |
+
inputs_embeds: torch.Tensor,
|
| 504 |
+
attention_mask: torch.Tensor | None,
|
| 505 |
+
past_key_values: Cache | None,
|
| 506 |
+
position_ids: torch.Tensor | None = None,
|
| 507 |
+
) -> dict:
|
| 508 |
+
"""The cache sizes each mask from the layer it is asked about, and the generic mask utilities ask about the first
|
| 509 |
+
non-sliding layer, which for a leading `conv` layer redirects to the first attention layer of any type: name the
|
| 510 |
+
first layer of each mask's own type instead."""
|
| 511 |
+
config = config.get_text_config()
|
| 512 |
+
mask_kwargs = {
|
| 513 |
+
"config": config,
|
| 514 |
+
"inputs_embeds": inputs_embeds,
|
| 515 |
+
"attention_mask": attention_mask,
|
| 516 |
+
"past_key_values": past_key_values,
|
| 517 |
+
"position_ids": position_ids,
|
| 518 |
+
}
|
| 519 |
+
layer_types, causal_mask_mapping = config.layer_types, {}
|
| 520 |
+
if "full_attention" in layer_types:
|
| 521 |
+
layer_idx = layer_types.index("full_attention")
|
| 522 |
+
causal_mask_mapping["full_attention"] = create_causal_mask(**mask_kwargs, layer_idx=layer_idx)
|
| 523 |
+
if "sliding_attention" in layer_types:
|
| 524 |
+
layer_idx = layer_types.index("sliding_attention")
|
| 525 |
+
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(
|
| 526 |
+
**mask_kwargs, layer_idx=layer_idx
|
| 527 |
+
)
|
| 528 |
+
if "conv" in layer_types:
|
| 529 |
+
causal_mask_mapping["conv"] = create_recurrent_attention_mask(**mask_kwargs)
|
| 530 |
+
return causal_mask_mapping
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@auto_docstring
|
| 534 |
+
class Lfm3PreTrainedModel(PreTrainedModel):
|
| 535 |
+
config: Lfm3Config
|
| 536 |
+
base_model_prefix = "model"
|
| 537 |
+
supports_gradient_checkpointing = True
|
| 538 |
+
_no_split_modules = ["Lfm3DecoderLayer"]
|
| 539 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 540 |
+
_supports_flash_attn = True
|
| 541 |
+
_supports_sdpa = True
|
| 542 |
+
_supports_flex_attn = True
|
| 543 |
+
|
| 544 |
+
_can_compile_fullgraph = True
|
| 545 |
+
_supports_attention_backend = True
|
| 546 |
+
_can_record_outputs = {
|
| 547 |
+
"hidden_states": Lfm3DecoderLayer,
|
| 548 |
+
"attentions": Lfm3Attention,
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
@torch.no_grad()
|
| 552 |
+
def _init_weights(self, module):
|
| 553 |
+
super()._init_weights(module)
|
| 554 |
+
if isinstance(module, Lfm3RotaryEmbedding):
|
| 555 |
+
for layer_type in module.layer_types:
|
| 556 |
+
curr_inv_freq, _ = module.compute_rope_parameters(module.config, layer_type=layer_type)
|
| 557 |
+
init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
|
| 558 |
+
init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
|
| 559 |
+
|
| 560 |
+
@staticmethod
|
| 561 |
+
def create_masks_for_generate(
|
| 562 |
+
config: PreTrainedConfig,
|
| 563 |
+
inputs_embeds: torch.Tensor,
|
| 564 |
+
attention_mask: torch.Tensor | None,
|
| 565 |
+
past_key_values: Cache | None,
|
| 566 |
+
position_ids: torch.Tensor | None = None,
|
| 567 |
+
**kwargs,
|
| 568 |
+
) -> dict:
|
| 569 |
+
return create_masks_by_layer_type(config, inputs_embeds, attention_mask, past_key_values, position_ids)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def packed_under_padding(position_ids: torch.Tensor, padding_mask: torch.Tensor, filled) -> torch.Tensor:
|
| 573 |
+
"""Padding repeats position 0, so packing is a restart between two kept tokens, or a kept position 0 on a filled
|
| 574 |
+
cache whose row holds a kept token; attention under a padding mask cannot isolate it."""
|
| 575 |
+
restarts = torch.diff(position_ids, prepend=position_ids[:, :1] - 1, dim=-1) != 1
|
| 576 |
+
valid = padding_mask[:, -restarts.shape[-1] :].bool()
|
| 577 |
+
packed = restarts[:, 1:] & valid[:, 1:] & valid[:, :-1]
|
| 578 |
+
if filled:
|
| 579 |
+
# a row whose cached tokens are all padding (chunked prefill of a left-padded batch) has no document to pack
|
| 580 |
+
# against; a mask covering only the chunk keeps the strict rule
|
| 581 |
+
cached = padding_mask[:, : padding_mask.shape[-1] - restarts.shape[-1]]
|
| 582 |
+
cached_valid = cached.bool().any(-1, keepdim=True) if cached.shape[-1] else torch.ones_like(valid[:, :1])
|
| 583 |
+
packed = packed | (valid[:, :1] & (position_ids[:, :1] == 0) & cached_valid)
|
| 584 |
+
return packed
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
@auto_docstring
|
| 588 |
+
class Lfm3Model(Lfm3PreTrainedModel):
|
| 589 |
+
"""LFM2 model with sliding-attention layers as a third layer type: the mask and the rotary embedding are built per
|
| 590 |
+
layer type, and packed documents (`position_ids` restarting) reset the short-conv window through `seq_idx`."""
|
| 591 |
+
|
| 592 |
+
def __init__(self, config: Lfm3Config):
|
| 593 |
+
super().__init__(config)
|
| 594 |
+
self.padding_idx = config.pad_token_id
|
| 595 |
+
self.vocab_size = config.vocab_size
|
| 596 |
+
|
| 597 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 598 |
+
self.layers = nn.ModuleList(
|
| 599 |
+
[Lfm3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 600 |
+
)
|
| 601 |
+
self.rotary_emb = Lfm3RotaryEmbedding(config=config)
|
| 602 |
+
self.gradient_checkpointing = False
|
| 603 |
+
self.embedding_norm = Lfm3RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 604 |
+
|
| 605 |
+
# Initialize weights and apply final processing
|
| 606 |
+
self.post_init()
|
| 607 |
+
|
| 608 |
+
@merge_with_config_defaults
|
| 609 |
+
@capture_outputs
|
| 610 |
+
@auto_docstring
|
| 611 |
+
def forward(
|
| 612 |
+
self,
|
| 613 |
+
input_ids: torch.LongTensor | None = None,
|
| 614 |
+
attention_mask: torch.Tensor | None = None,
|
| 615 |
+
position_ids: torch.LongTensor | None = None,
|
| 616 |
+
past_key_values: Cache | None = None,
|
| 617 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 618 |
+
use_cache: bool | None = None,
|
| 619 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 620 |
+
) -> BaseModelOutputWithPast:
|
| 621 |
+
r"""
|
| 622 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)` or `dict`, *optional*):
|
| 623 |
+
Mask to avoid performing attention on padding token indices (1 keeps a token, 0 masks it), or the mask
|
| 624 |
+
dict of `create_masks_for_generate`. A mask dict is used as given: `generate` refuses packed
|
| 625 |
+
`position_ids` before its prefill.
|
| 626 |
+
"""
|
| 627 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 628 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 629 |
+
# `seq_idx` is a shared kwarg (`DataCollatorWithFlattening(return_seq_idx=True)`, read by Lfm2); LFM3 derives
|
| 630 |
+
# the documents from the restarting `position_ids` that come with it
|
| 631 |
+
if kwargs.pop("seq_idx", None) is not None and position_ids is None:
|
| 632 |
+
raise ValueError("Pass packed documents as `position_ids` restarting at 0; LFM3 does not read `seq_idx`")
|
| 633 |
+
|
| 634 |
+
if inputs_embeds is None:
|
| 635 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 636 |
+
|
| 637 |
+
if use_cache and past_key_values is None:
|
| 638 |
+
past_key_values = DynamicCache(config=self.config)
|
| 639 |
+
filled = past_key_values is not None and (
|
| 640 |
+
past_key_values.get_seq_length() > 0
|
| 641 |
+
if any(t != "conv" for t in self.config.layer_types)
|
| 642 |
+
else past_key_values.has_previous_state()
|
| 643 |
+
)
|
| 644 |
+
packed_cache = getattr(past_key_values, "lfm3_packed", None)
|
| 645 |
+
if isinstance(packed_cache, torch.Tensor) or packed_cache:
|
| 646 |
+
# Reset layers have no history to mix. Ordinary caches carry a Python `False` and skip this, so the decode
|
| 647 |
+
# steps do no tensor work here; only a compiled packed prefill leaves a tensor flag, and `filled` stays
|
| 648 |
+
# tensor-valued for static caches.
|
| 649 |
+
packed_message = (
|
| 650 |
+
"A cache filled by a packed-document forward cannot be continued: its attention spans the documents"
|
| 651 |
+
)
|
| 652 |
+
packed_cache = packed_cache & filled if isinstance(packed_cache, torch.Tensor) else filled
|
| 653 |
+
if isinstance(packed_cache, torch.Tensor):
|
| 654 |
+
torch_compilable_check(~packed_cache, packed_message)
|
| 655 |
+
if not is_tracing(packed_cache):
|
| 656 |
+
past_key_values.lfm3_packed = bool(packed_cache)
|
| 657 |
+
elif packed_cache:
|
| 658 |
+
raise ValueError(packed_message)
|
| 659 |
+
else:
|
| 660 |
+
past_key_values.lfm3_packed = False
|
| 661 |
+
|
| 662 |
+
# The mask utilities detect packing only with `attention_mask=None`, so a multi-token forward with explicit
|
| 663 |
+
# positions drops the all-ones mask tokenizers emit (a data-dependent check, hence not when traced).
|
| 664 |
+
explicit_positions = position_ids is not None and inputs_embeds.shape[1] > 1
|
| 665 |
+
if (
|
| 666 |
+
explicit_positions
|
| 667 |
+
and isinstance(attention_mask, torch.Tensor)
|
| 668 |
+
and attention_mask.ndim == 2
|
| 669 |
+
and not is_tracing(position_ids)
|
| 670 |
+
and bool(attention_mask.all())
|
| 671 |
+
):
|
| 672 |
+
attention_mask = None
|
| 673 |
+
seq_idx = None
|
| 674 |
+
if position_ids is None:
|
| 675 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 676 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 677 |
+
position_ids = position_ids.unsqueeze(0)
|
| 678 |
+
elif explicit_positions and not isinstance(attention_mask, dict):
|
| 679 |
+
# a mask dict comes from `generate`, which refused packing before its prefill
|
| 680 |
+
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:
|
| 681 |
+
# data-dependent: a traced forward skips it (`generate` refuses packing eagerly before its prefill)
|
| 682 |
+
if not is_tracing(position_ids):
|
| 683 |
+
torch_compilable_check(
|
| 684 |
+
~packed_under_padding(position_ids, attention_mask, filled),
|
| 685 |
+
"Packed documents (`position_ids` restarting) cannot be combined with an attention mask: "
|
| 686 |
+
"attention would not isolate the documents. Pass `attention_mask=None` without a static cache.",
|
| 687 |
+
)
|
| 688 |
+
else:
|
| 689 |
+
restarts = torch.diff(position_ids, prepend=position_ids[:, :1] - 1, dim=-1) != 1
|
| 690 |
+
document_ids = restarts.cumsum(-1)
|
| 691 |
+
if is_tracing(position_ids) or bool((document_ids[..., -1] > 0).any()):
|
| 692 |
+
seq_idx = document_ids.to(torch.int32)
|
| 693 |
+
# Packed documents are prefilled in one forward on an empty cache (cached tokens would join the first
|
| 694 |
+
# document), and their cache is never continued
|
| 695 |
+
if filled:
|
| 696 |
+
torch_compilable_check(
|
| 697 |
+
(~restarts[:, 1:]).all() & (position_ids[:, 0] != 0).all(),
|
| 698 |
+
"Packed documents must be prefilled in one forward; the cache already holds tokens",
|
| 699 |
+
)
|
| 700 |
+
# Ordinary continuation must retain the convolution window from the cached document.
|
| 701 |
+
seq_idx = None
|
| 702 |
+
if attention_mask is None:
|
| 703 |
+
# without a mask only the cacheless packed-sequence mask isolates repeated zero positions (left
|
| 704 |
+
# padding): a cache-sized mask and every later decode step would attend them, so they count too
|
| 705 |
+
packed = (document_ids[..., -1] > 0).any()
|
| 706 |
+
else:
|
| 707 |
+
# a prepared 4D mask is the caller's and carries the padding (repeated zero positions), but may
|
| 708 |
+
# or may not isolate documents, so the cache records the packing and is never continued
|
| 709 |
+
steps = torch.diff(position_ids, dim=-1)
|
| 710 |
+
packed = ((steps != 1) & ~((steps == 0) & (position_ids[:, :-1] == 0))).any()
|
| 711 |
+
if past_key_values is not None:
|
| 712 |
+
# resolved here, where the prefill already syncs, so the decode steps carry a Python flag: no
|
| 713 |
+
# per-step host sync, data-dependent op or CUDA-graph output on the cache
|
| 714 |
+
past_key_values.lfm3_packed = packed if is_tracing(position_ids) else bool(packed)
|
| 715 |
+
|
| 716 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 717 |
+
mask_kwargs = {
|
| 718 |
+
"config": self.config,
|
| 719 |
+
"inputs_embeds": inputs_embeds,
|
| 720 |
+
"attention_mask": attention_mask,
|
| 721 |
+
"past_key_values": past_key_values,
|
| 722 |
+
"position_ids": position_ids,
|
| 723 |
+
}
|
| 724 |
+
# The mask utilities only isolate packed documents without a cache, and an empty cache adds nothing.
|
| 725 |
+
layer_types = self.config.layer_types
|
| 726 |
+
if seq_idx is not None and past_key_values is not None:
|
| 727 |
+
attention_layer = next((i for i, t in enumerate(layer_types) if t != "conv"), None)
|
| 728 |
+
if attention_layer is not None and past_key_values.get_seq_length(attention_layer) == 0:
|
| 729 |
+
if past_key_values.is_compileable:
|
| 730 |
+
# static layers always return their full length, so the masks are sized by the cache, which
|
| 731 |
+
# isolates neither documents nor positional-only left padding
|
| 732 |
+
torch_compilable_check(
|
| 733 |
+
~packed,
|
| 734 |
+
"Packed documents, or left padding without an attention mask, cannot be prefilled into a "
|
| 735 |
+
"static cache: its masks are sized by the cache. Pass the padding as `attention_mask`, or "
|
| 736 |
+
"use a `DynamicCache` for packed documents",
|
| 737 |
+
)
|
| 738 |
+
else:
|
| 739 |
+
mask_kwargs["past_key_values"] = None
|
| 740 |
+
causal_mask_mapping = create_masks_by_layer_type(**mask_kwargs)
|
| 741 |
+
|
| 742 |
+
hidden_states = inputs_embeds
|
| 743 |
+
position_embeddings = {
|
| 744 |
+
layer_type: self.rotary_emb(hidden_states, position_ids=position_ids, layer_type=layer_type)
|
| 745 |
+
for layer_type in self.rotary_emb.layer_types
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
| 749 |
+
layer_type = self.config.layer_types[i]
|
| 750 |
+
hidden_states = decoder_layer(
|
| 751 |
+
hidden_states,
|
| 752 |
+
attention_mask=causal_mask_mapping[layer_type],
|
| 753 |
+
position_embeddings=position_embeddings.get(layer_type),
|
| 754 |
+
position_ids=position_ids,
|
| 755 |
+
past_key_values=past_key_values,
|
| 756 |
+
seq_idx=seq_idx,
|
| 757 |
+
**kwargs,
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
hidden_states = self.embedding_norm(hidden_states)
|
| 761 |
+
|
| 762 |
+
return BaseModelOutputWithPast(
|
| 763 |
+
last_hidden_state=hidden_states,
|
| 764 |
+
past_key_values=past_key_values,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def reject_packed_generation(config: PreTrainedConfig, input_ids, generation_config, model_kwargs, is_first_iteration):
|
| 769 |
+
"""`generate` decodes from the cache its prefill fills, and no mask it builds isolates packed documents
|
| 770 |
+
(`position_ids` restarting): the prompt is refused before the prefill, one forward or every chunk, writes to it."""
|
| 771 |
+
position_ids, attention_mask = model_kwargs.get("position_ids"), model_kwargs.get("attention_mask")
|
| 772 |
+
cache = model_kwargs.get("past_key_values")
|
| 773 |
+
if cache is None or position_ids is None or position_ids.ndim != 2:
|
| 774 |
+
return
|
| 775 |
+
if attention_mask is not None and attention_mask.ndim != 2:
|
| 776 |
+
return
|
| 777 |
+
has_attention = any(t != "conv" for t in config.get_text_config().layer_types)
|
| 778 |
+
filled = bool(cache.get_seq_length() > 0 if has_attention else cache.has_previous_state())
|
| 779 |
+
inputs_embeds = model_kwargs.get("inputs_embeds") if is_first_iteration else None
|
| 780 |
+
length = input_ids.shape[1] if inputs_embeds is None else inputs_embeds.shape[1]
|
| 781 |
+
if generation_config.prefill_chunk_size is not None:
|
| 782 |
+
# the chunks run from the start of the prompt
|
| 783 |
+
position_ids = position_ids[:, :length]
|
| 784 |
+
else:
|
| 785 |
+
if filled and has_attention:
|
| 786 |
+
# the slice `_prefill` feeds: a prompt that spans the cache is cut to its uncached part
|
| 787 |
+
mask_length = getattr(generation_config, "_mask_length", -1)
|
| 788 |
+
if attention_mask is not None:
|
| 789 |
+
mask_length = attention_mask.shape[1]
|
| 790 |
+
if inputs_embeds is not None or mask_length == length:
|
| 791 |
+
length -= int(cache.get_seq_length())
|
| 792 |
+
position_ids = position_ids[:, position_ids.shape[1] - length :]
|
| 793 |
+
if attention_mask is None:
|
| 794 |
+
attention_mask = torch.ones_like(position_ids)
|
| 795 |
+
if bool(packed_under_padding(position_ids, attention_mask, filled).any()):
|
| 796 |
+
raise ValueError(
|
| 797 |
+
"`generate` cannot decode packed documents (`position_ids` restarting, or starting at 0 on a cache that "
|
| 798 |
+
"holds tokens): attention would span them. Generate each document in its own row of a left-padded batch."
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
@auto_docstring
|
| 803 |
+
class Lfm3ForCausalLM(Lfm3PreTrainedModel, GenerationMixin):
|
| 804 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 805 |
+
_tp_plan = {"lm_head": "colwise_gather_output"}
|
| 806 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 807 |
+
_fsdp_plan = {"lm_head": "keep_full_weight"}
|
| 808 |
+
|
| 809 |
+
def __init__(self, config):
|
| 810 |
+
super().__init__(config)
|
| 811 |
+
self.model = Lfm3Model(config)
|
| 812 |
+
self.vocab_size = config.vocab_size
|
| 813 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 814 |
+
|
| 815 |
+
# Initialize weights and apply final processing
|
| 816 |
+
self.post_init()
|
| 817 |
+
|
| 818 |
+
@can_return_tuple
|
| 819 |
+
@auto_docstring
|
| 820 |
+
def forward(
|
| 821 |
+
self,
|
| 822 |
+
input_ids: torch.LongTensor | None = None,
|
| 823 |
+
attention_mask: torch.Tensor | None = None,
|
| 824 |
+
position_ids: torch.LongTensor | None = None,
|
| 825 |
+
past_key_values: Cache | None = None,
|
| 826 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 827 |
+
labels: torch.LongTensor | None = None,
|
| 828 |
+
use_cache: bool | None = None,
|
| 829 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 830 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 831 |
+
) -> CausalLMOutputWithPast:
|
| 832 |
+
r"""
|
| 833 |
+
Example:
|
| 834 |
+
|
| 835 |
+
```python
|
| 836 |
+
>>> from transformers import AutoTokenizer, Lfm3ForCausalLM
|
| 837 |
+
|
| 838 |
+
>>> model = Lfm3ForCausalLM.from_pretrained("LiquidAI/LFM3-1.7B-Preview")
|
| 839 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("LiquidAI/LFM3-1.7B-Preview")
|
| 840 |
+
|
| 841 |
+
>>> inputs = tokenizer.apply_chat_template(
|
| 842 |
+
... [{"role": "user", "content": "What is C. elegans?"}], add_generation_prompt=True, return_tensors="pt"
|
| 843 |
+
... )
|
| 844 |
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=64)
|
| 845 |
+
>>> tokenizer.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
|
| 846 |
+
```"""
|
| 847 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 848 |
+
input_ids=input_ids,
|
| 849 |
+
attention_mask=attention_mask,
|
| 850 |
+
position_ids=position_ids,
|
| 851 |
+
past_key_values=past_key_values,
|
| 852 |
+
inputs_embeds=inputs_embeds,
|
| 853 |
+
use_cache=use_cache,
|
| 854 |
+
**kwargs,
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
hidden_states = outputs.last_hidden_state
|
| 858 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 859 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 860 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 861 |
+
|
| 862 |
+
loss = None
|
| 863 |
+
if labels is not None:
|
| 864 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 865 |
+
|
| 866 |
+
return CausalLMOutputWithPast(
|
| 867 |
+
loss=loss,
|
| 868 |
+
logits=logits,
|
| 869 |
+
past_key_values=outputs.past_key_values,
|
| 870 |
+
hidden_states=outputs.hidden_states,
|
| 871 |
+
attentions=outputs.attentions,
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
def _prefill(self, input_ids, generation_config, model_kwargs, is_first_iteration=True):
|
| 875 |
+
# every prefill passes here once before its first forward: a check per chunk would leave the earlier chunks
|
| 876 |
+
# in the cache, and a dynamic cache would only refuse packing at the first decode step
|
| 877 |
+
reject_packed_generation(self.config, input_ids, generation_config, model_kwargs, is_first_iteration)
|
| 878 |
+
return super()._prefill(input_ids, generation_config, model_kwargs, is_first_iteration=is_first_iteration)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
__all__ = ["Lfm3ForCausalLM", "Lfm3Model", "Lfm3PreTrainedModel"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tested with these versions (Python 3.12, CUDA 12.6 wheels)
|
| 2 |
+
torch>=2.6
|
| 3 |
+
transformers>=5.20
|
| 4 |
+
datasets>=4.0
|
| 5 |
+
accelerate>=1.10
|
| 6 |
+
safetensors>=0.5
|
| 7 |
+
huggingface_hub>=0.34
|
| 8 |
+
numpy>=2.0
|
| 9 |
+
# evaluation only
|
| 10 |
+
lm-eval==0.4.13
|
scripts/check_loop_gguf.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Verify a looped GGUF: metadata arrays extended correctly + sandwich-norm scaling exact.
|
| 3 |
+
|
| 4 |
+
usage: check_loop_gguf.py BASE.gguf LOOP.gguf A B [REPS] [ALPHA]
|
| 5 |
+
"""
|
| 6 |
+
import os, struct, sys
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def read(p):
|
| 13 |
+
f = open(p, 'rb')
|
| 14 |
+
assert f.read(4) == b'GGUF'
|
| 15 |
+
f.read(4)
|
| 16 |
+
nt, nkv = struct.unpack('<QQ', f.read(16))
|
| 17 |
+
|
| 18 |
+
def s():
|
| 19 |
+
n = struct.unpack('<Q', f.read(8))[0]
|
| 20 |
+
return f.read(n).decode('utf-8', 'replace')
|
| 21 |
+
|
| 22 |
+
def val(t):
|
| 23 |
+
if t == 8:
|
| 24 |
+
return s()
|
| 25 |
+
if t == 9:
|
| 26 |
+
et = struct.unpack('<I', f.read(4))[0]
|
| 27 |
+
n = struct.unpack('<Q', f.read(8))[0]
|
| 28 |
+
out = []
|
| 29 |
+
for _ in range(n):
|
| 30 |
+
if et == 8: out.append(s())
|
| 31 |
+
elif et == 7: out.append(struct.unpack('<?', f.read(1))[0])
|
| 32 |
+
elif et == 6: out.append(struct.unpack('<f', f.read(4))[0])
|
| 33 |
+
elif et == 5: out.append(struct.unpack('<i', f.read(4))[0])
|
| 34 |
+
elif et == 4: out.append(struct.unpack('<I', f.read(4))[0])
|
| 35 |
+
elif et == 10: out.append(struct.unpack('<Q', f.read(8))[0])
|
| 36 |
+
else: raise ValueError(et)
|
| 37 |
+
return out
|
| 38 |
+
fmt = {0: '<B', 1: '<b', 2: '<H', 3: '<h', 4: '<I', 5: '<i', 6: '<f', 7: '<?', 10: '<Q', 11: '<q', 12: '<d'}[t]
|
| 39 |
+
return struct.unpack(fmt, f.read(SZ[t]))[0]
|
| 40 |
+
|
| 41 |
+
kv = {}
|
| 42 |
+
for _ in range(nkv):
|
| 43 |
+
k = s()
|
| 44 |
+
t = struct.unpack('<I', f.read(4))[0]
|
| 45 |
+
kv[k] = val(t)
|
| 46 |
+
T = {}
|
| 47 |
+
for _ in range(nt):
|
| 48 |
+
name = s()
|
| 49 |
+
nd = struct.unpack('<I', f.read(4))[0]
|
| 50 |
+
dims = [struct.unpack('<Q', f.read(8))[0] for _ in range(nd)]
|
| 51 |
+
tt = struct.unpack('<I', f.read(4))[0]
|
| 52 |
+
off = struct.unpack('<Q', f.read(8))[0]
|
| 53 |
+
T[name] = (tt, dims, off)
|
| 54 |
+
start = (f.tell() + 31) // 32 * 32
|
| 55 |
+
return f, start, T, kv
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def raw(f, s, T, name):
|
| 59 |
+
tt, dims, off = T[name]
|
| 60 |
+
k = int(np.prod(dims))
|
| 61 |
+
f.seek(s + off)
|
| 62 |
+
assert tt == 0, f"{name} is not f32"
|
| 63 |
+
return np.frombuffer(f.read(k * 4), dtype=np.float32).copy()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
base_p, loop_p = sys.argv[1], sys.argv[2]
|
| 68 |
+
A, B = int(sys.argv[3]), int(sys.argv[4])
|
| 69 |
+
REPS = int(sys.argv[5]) if len(sys.argv) > 5 else 2
|
| 70 |
+
ALPHA = float(sys.argv[6]) if len(sys.argv) > 6 else 1.0 / REPS
|
| 71 |
+
fA, sA, TA, kvA = read(base_p)
|
| 72 |
+
fB, sB, TB, kvB = read(loop_p)
|
| 73 |
+
W = B - A + 1
|
| 74 |
+
NEW = (REPS - 1) * W
|
| 75 |
+
nb = kvA['lfm3.block_count']
|
| 76 |
+
nl = kvB['lfm3.block_count']
|
| 77 |
+
print(f"block_count {nb} -> {nl} (expected {nb + NEW}) {'OK' if nl == nb + NEW else 'MISMATCH'}")
|
| 78 |
+
for key in ('lfm3.attention.head_count_kv', 'lfm3.attention.sliding_window_pattern'):
|
| 79 |
+
want = list(kvA[key][:B + 1]) + [kvA[key][i] for _ in range(REPS - 1) for i in range(A, B + 1)] + list(kvA[key][B + 1:])
|
| 80 |
+
got = list(kvB[key])
|
| 81 |
+
print(f"{key}: {'OK' if got == want else 'MISMATCH'} (len {len(got)})")
|
| 82 |
+
bad = 0
|
| 83 |
+
for i in range(A, B + 1):
|
| 84 |
+
for nm in ('post_attention_norm.weight', 'post_ffw_norm.weight'):
|
| 85 |
+
a = raw(fA, sA, TA, f'blk.{i}.{nm}')
|
| 86 |
+
for rep in range(REPS):
|
| 87 |
+
dst = i + rep * W
|
| 88 |
+
d = np.abs(raw(fB, sB, TB, f'blk.{dst}.{nm}') - a * np.float32(ALPHA)).max()
|
| 89 |
+
bad += int(d != 0)
|
| 90 |
+
print(f"blk.{i}.{nm} -> blk.{dst}: max|got - {ALPHA}*base| = {d:.2e}")
|
| 91 |
+
# untouched tensor must be byte-identical in the copy
|
| 92 |
+
a = raw(fA, sA, TA, f'blk.{A}.attn_norm.weight')
|
| 93 |
+
b = raw(fB, sB, TB, f'blk.{A + W}.attn_norm.weight')
|
| 94 |
+
print(f"copy of blk.{A}.attn_norm identical: {np.array_equal(a, b)}")
|
| 95 |
+
print("DAMPING EXACT" if bad == 0 else f"{bad} SCALE MISMATCHES")
|
scripts/compose-loop.yaml
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
# ── LFM3-1.7B with a training-free depth loop (arXiv 2605.23872) ──
|
| 3 |
+
# Window [8-11] executed twice, each application contributing half a residual
|
| 4 |
+
# step (damped Euler, K=2). Baked as a plain 28-layer GGUF: the window's
|
| 5 |
+
# post_attention_norm / post_ffw_norm weights are scaled by 0.5 in both the
|
| 6 |
+
# original layers and the copies, which is exact (both HF and llama.cpp apply
|
| 7 |
+
# them as RMSNorm on the branch output, before the residual add).
|
| 8 |
+
#
|
| 9 |
+
# Build the file with:
|
| 10 |
+
# python3 scripts/loop_gguf_k.py base.gguf \
|
| 11 |
+
# loop.gguf 8 11 2 0.5
|
| 12 |
+
# python3 scripts/check_loop_gguf.py base.gguf \
|
| 13 |
+
# loop.gguf 8 11 2 0.5
|
| 14 |
+
#
|
| 15 |
+
# Measured (RTX 4070, Q8_0, -ngl 99): pp512 18184 -> 16699 t/s, tg128
|
| 16 |
+
# 160.3 -> 142.6 t/s (-8.2% / -11.1%), params 1.73B -> 1.97B.
|
| 17 |
+
# ARC-Easy 5-shot 1000q: 60.8% -> 69.2%. GSM8K 80q: 67.5% -> 61.3% (n.s.).
|
| 18 |
+
lfm3-1.7b-loop:
|
| 19 |
+
# build this image as described in REPRODUCE.md (llama.cpp master >= 1014775c8 + CUDA runtime)
|
| 20 |
+
image: lfm3-llama:master-1014775c8
|
| 21 |
+
container_name: lfm3-1.7b-loop
|
| 22 |
+
restart: unless-stopped
|
| 23 |
+
ports:
|
| 24 |
+
- "8080:8080"
|
| 25 |
+
volumes:
|
| 26 |
+
- ./models:/models:ro
|
| 27 |
+
entrypoint:
|
| 28 |
+
- /opt/llama/llama-server
|
| 29 |
+
- -m
|
| 30 |
+
- /models/LFM3-1.7B-loop-8-11-Q8_0.gguf
|
| 31 |
+
- --alias
|
| 32 |
+
- lfm3-1.7b-loop
|
| 33 |
+
- --jinja
|
| 34 |
+
- -ngl
|
| 35 |
+
- "99"
|
| 36 |
+
- -fa
|
| 37 |
+
- "on"
|
| 38 |
+
- --parallel
|
| 39 |
+
- "${LFM3_NP:-8}"
|
| 40 |
+
- --kv-unified
|
| 41 |
+
- --temp
|
| 42 |
+
- "0.1"
|
| 43 |
+
- --top-k
|
| 44 |
+
- "50"
|
| 45 |
+
# NOTE: no --repeat-penalty here: it costs ~5% decode (135 -> 128.6 t/s measured)
|
| 46 |
+
# and agents send their own sampling params anyway.
|
| 47 |
+
- --metrics
|
| 48 |
+
command:
|
| 49 |
+
- --host
|
| 50 |
+
- 0.0.0.0
|
| 51 |
+
- --port
|
| 52 |
+
- "8080"
|
| 53 |
+
- -c
|
| 54 |
+
- "${LFM3_CTX:-262144}"
|
| 55 |
+
deploy:
|
| 56 |
+
resources:
|
| 57 |
+
reservations:
|
| 58 |
+
devices:
|
| 59 |
+
- driver: nvidia
|
| 60 |
+
count: all
|
| 61 |
+
capabilities: [gpu]
|
scripts/ens.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Logit-ensemble of two ARC runs (same items, same options): accuracy as a function of
|
| 3 |
+
the mixing weight on model A, plus paired stats against each endpoint."""
|
| 4 |
+
import json, math, sys
|
| 5 |
+
|
| 6 |
+
def load(p):
|
| 7 |
+
d = json.load(open(p))
|
| 8 |
+
if isinstance(d, list): # legacy format: per-item correctness only
|
| 9 |
+
raise SystemExit(f"{p} has no per-option logprobs; rerun with --dump-lp")
|
| 10 |
+
return d
|
| 11 |
+
|
| 12 |
+
def acc(lp, gold):
|
| 13 |
+
return sum(int(max(range(len(s)), key=lambda j: s[j]) == g) for s, g in zip(lp, gold)) / len(gold)
|
| 14 |
+
|
| 15 |
+
def mcnemar(a, b):
|
| 16 |
+
n01 = sum(1 for x, y in zip(a, b) if x and not y)
|
| 17 |
+
n10 = sum(1 for x, y in zip(a, b) if not x and y)
|
| 18 |
+
m = n01 + n10
|
| 19 |
+
p = min(1.0, 2 * sum(math.comb(m, i) for i in range(0, min(n01, n10) + 1)) / 2 ** m) if m else 1.0
|
| 20 |
+
return n01, n10, p
|
| 21 |
+
|
| 22 |
+
A = load(sys.argv[1]); B = load(sys.argv[2])
|
| 23 |
+
lab_a = sys.argv[3] if len(sys.argv) > 3 else "A"
|
| 24 |
+
lab_b = sys.argv[4] if len(sys.argv) > 4 else "B"
|
| 25 |
+
assert A["gold"] == B["gold"] and len(A["lp"]) == len(B["lp"]), "different item sets"
|
| 26 |
+
gold = A["gold"]
|
| 27 |
+
print(f"{'w(' + lab_a + ')':>16} acc vs {lab_a:<14} vs {lab_b}")
|
| 28 |
+
best = None
|
| 29 |
+
for w in [0, 0.1, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1.0]:
|
| 30 |
+
mix = [[w * x + (1 - w) * y for x, y in zip(sa, sb)] for sa, sb in zip(A["lp"], B["lp"])]
|
| 31 |
+
per = [int(max(range(len(s)), key=lambda j: s[j]) == g) for s, g in zip(mix, gold)]
|
| 32 |
+
a_per = [int(max(range(len(s)), key=lambda j: s[j]) == g) for s, g in zip(A["lp"], gold)]
|
| 33 |
+
b_per = [int(max(range(len(s)), key=lambda j: s[j]) == g) for s, g in zip(B["lp"], gold)]
|
| 34 |
+
n01, n10, p = mcnemar(b_per, per)
|
| 35 |
+
n01b, n10b, pb = mcnemar(a_per, per)
|
| 36 |
+
print(f"{w:16.2f} {sum(per)/len(per)*100:5.1f}% {sum(per)/len(per)*100 - sum(a_per)/len(a_per)*100:+5.1f}pp (p={pb:.3f}) "
|
| 37 |
+
f"{sum(per)/len(per)*100 - sum(b_per)/len(b_per)*100:+5.1f}pp (p={p:.3f})")
|
| 38 |
+
if best is None or sum(per) > best[1]:
|
| 39 |
+
best = (w, sum(per), p)
|
| 40 |
+
print(f"best w({lab_a})={best[0]} acc={best[1]/len(gold)*100:.1f}% p_vs_B={best[2]:.3f}")
|
scripts/lmstat.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Paired analysis of lm-eval sample files: base vs loop, per task.
|
| 3 |
+
|
| 4 |
+
lm-eval writes one jsonl per task with `filtered_resps` (one loglikelihood per choice)
|
| 5 |
+
and `target` (gold index). Correctness = argmax(choice scores) == target.
|
| 6 |
+
Prints accuracy for both models and an exact McNemar (binomial) p-value.
|
| 7 |
+
"""
|
| 8 |
+
import glob, json, math, os, sys
|
| 9 |
+
|
| 10 |
+
ROOT = os.environ.get("LM_EVAL_ROOT", "out-lm")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load(tag, task):
|
| 14 |
+
files = sorted(glob.glob(os.path.join(ROOT, tag, "**", f"samples_{task}_*.jsonl"), recursive=True))
|
| 15 |
+
if not files:
|
| 16 |
+
files = sorted(glob.glob(os.path.join(ROOT, tag, "**", f"*{task}*.jsonl"), recursive=True))
|
| 17 |
+
if not files:
|
| 18 |
+
return None
|
| 19 |
+
rows = []
|
| 20 |
+
for line in open(files[-1]):
|
| 21 |
+
d = json.loads(line)
|
| 22 |
+
v = d.get("acc_norm", d.get("acc"))
|
| 23 |
+
if v is None:
|
| 24 |
+
continue
|
| 25 |
+
rows.append(int(v))
|
| 26 |
+
return rows
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def mcnemar(a, b):
|
| 30 |
+
n01 = sum(1 for x, y in zip(a, b) if x and not y)
|
| 31 |
+
n10 = sum(1 for x, y in zip(a, b) if not x and y)
|
| 32 |
+
m = n01 + n10
|
| 33 |
+
p = min(1.0, 2 * sum(math.comb(m, i) for i in range(0, min(n01, n10) + 1)) / 2 ** m) if m else 1.0
|
| 34 |
+
return n01, n10, p
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
TASKS = sys.argv[1:] or ["hellaswag", "piqa", "winogrande", "arc_easy", "arc_challenge", "boolq"]
|
| 38 |
+
print(f"{'task':16s} {'n':>6s} {'base':>7s} {'loop':>7s} {'delta':>8s} {'disc':>9s} p")
|
| 39 |
+
for t in TASKS:
|
| 40 |
+
a, b = load("base", t), load("loop", t)
|
| 41 |
+
if not a or not b:
|
| 42 |
+
print(f"{t:16s} missing samples (base={bool(a)}, loop={bool(b)})")
|
| 43 |
+
continue
|
| 44 |
+
n = min(len(a), len(b))
|
| 45 |
+
a, b = a[:n], b[:n]
|
| 46 |
+
ab, bb = sum(a) / n, sum(b) / n
|
| 47 |
+
n01, n10, p = mcnemar(a, b)
|
| 48 |
+
print(f"{t:16s} {n:6d} {ab*100:6.1f}% {bb*100:6.1f}% {(bb-ab)*100:+7.1f}pp {n01:4d}/{n10:<4d} {p:.4f}")
|
scripts/loop_gguf_k.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Training-free loop, GGUF edition: repeat a mid-stack window `REPS` times with
|
| 3 |
+
each application damped by `ALPHA` (default 1/REPS), physically duplicating the
|
| 4 |
+
window's tensors.
|
| 5 |
+
|
| 6 |
+
The damping lives in the sandwich norms (`post_attention_norm`, `post_ffw_norm`):
|
| 7 |
+
both HF and llama.cpp apply them as RMSNorm on the branch output before the
|
| 8 |
+
residual add, so scaling those f32 vectors scales that application's residual
|
| 9 |
+
step by exactly ALPHA.
|
| 10 |
+
|
| 11 |
+
usage: loop_gguf_k.py SRC.gguf DST.gguf A B REPS [ALPHA]
|
| 12 |
+
"""
|
| 13 |
+
import os, struct, sys
|
| 14 |
+
from collections import OrderedDict
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
SRC = sys.argv[1]
|
| 18 |
+
DST = sys.argv[2]
|
| 19 |
+
A, B = int(sys.argv[3]), int(sys.argv[4])
|
| 20 |
+
REPS = int(sys.argv[5]) if len(sys.argv) > 5 else 2
|
| 21 |
+
ALPHA = float(sys.argv[6]) if len(sys.argv) > 6 else 1.0 / REPS
|
| 22 |
+
|
| 23 |
+
T = {0: '<B', 1: '<b', 2: '<H', 3: '<h', 4: '<I', 5: '<i', 6: '<f', 7: '<?', 10: '<Q', 11: '<q', 12: '<d'}
|
| 24 |
+
SZ = {'<B': 1, '<b': 1, '<H': 2, '<h': 2, '<I': 4, '<i': 4, '<f': 4, '<?': 1, '<Q': 8, '<q': 8, '<d': 8}
|
| 25 |
+
PER_LAYER = ('lfm3.attention.head_count_kv', 'lfm3.attention.sliding_window_pattern')
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class R:
|
| 29 |
+
def __init__(self, f): self.f = f
|
| 30 |
+
def raw(self, n):
|
| 31 |
+
b = self.f.read(n)
|
| 32 |
+
if len(b) != n: raise EOFError(f"want {n} got {len(b)}")
|
| 33 |
+
return b
|
| 34 |
+
def u32(self): return struct.unpack('<I', self.raw(4))[0]
|
| 35 |
+
def u64(self): return struct.unpack('<Q', self.raw(8))[0]
|
| 36 |
+
def s(self):
|
| 37 |
+
n = self.u64(); return self.raw(n)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
f = open(SRC, 'rb'); r = R(f)
|
| 41 |
+
assert r.raw(4) == b'GGUF'
|
| 42 |
+
ver = r.u32(); n_tensors = r.u64(); n_kv = r.u64()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def read_kv(r):
|
| 46 |
+
key = r.s().decode(); t = r.u32(); et0 = None
|
| 47 |
+
if t == 8:
|
| 48 |
+
val = r.s()
|
| 49 |
+
elif t == 9:
|
| 50 |
+
et = r.u32(); n = r.u64(); et0 = et; vals = []
|
| 51 |
+
for _ in range(n):
|
| 52 |
+
if et == 8: vals.append(r.s())
|
| 53 |
+
elif et == 4: vals.append(struct.unpack('<I', r.raw(4))[0])
|
| 54 |
+
elif et == 5: vals.append(struct.unpack('<i', r.raw(4))[0])
|
| 55 |
+
elif et == 6: vals.append(struct.unpack('<f', r.raw(4))[0])
|
| 56 |
+
elif et == 10: vals.append(struct.unpack('<Q', r.raw(8))[0])
|
| 57 |
+
elif et == 7: vals.append(struct.unpack('<?', r.raw(1))[0])
|
| 58 |
+
else: raise ValueError(f"array elem type {et}")
|
| 59 |
+
val = vals
|
| 60 |
+
else:
|
| 61 |
+
val = struct.unpack(T[t], r.raw(SZ[T[t]]))[0]
|
| 62 |
+
return key, t, val, et0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
kvs = [read_kv(r) for _ in range(n_kv)]
|
| 66 |
+
kvmap = {k: (t, v) for k, t, v, _e in kvs}
|
| 67 |
+
n_layer = kvmap['lfm3.block_count'][1]
|
| 68 |
+
alignment = kvmap.get('general.alignment', (6, 32))[1]
|
| 69 |
+
assert 0 <= A <= B < n_layer
|
| 70 |
+
W = B - A + 1
|
| 71 |
+
NEW = (REPS - 1) * W
|
| 72 |
+
|
| 73 |
+
tensors = []
|
| 74 |
+
for _ in range(n_tensors):
|
| 75 |
+
name = r.s().decode(); nd = r.u32()
|
| 76 |
+
dims = [struct.unpack('<Q', r.raw(8))[0] for _ in range(nd)]
|
| 77 |
+
tt = r.u32(); off = r.u64()
|
| 78 |
+
tensors.append([name, dims, tt, off])
|
| 79 |
+
|
| 80 |
+
data_start = (f.tell() + alignment - 1) // alignment * alignment
|
| 81 |
+
data_len = os.path.getsize(SRC) - data_start
|
| 82 |
+
order = sorted(range(len(tensors)), key=lambda i: tensors[i][3])
|
| 83 |
+
nbytes = {}
|
| 84 |
+
for j, i in enumerate(order):
|
| 85 |
+
nxt = tensors[order[j + 1]][3] if j + 1 < len(order) else data_len
|
| 86 |
+
nbytes[i] = nxt - tensors[i][3]
|
| 87 |
+
|
| 88 |
+
# ---- output tensor order: non-block tensors, layers 0..B, window copies, rest
|
| 89 |
+
src_idx, out_names, scale = [], [], []
|
| 90 |
+
for i, (name, dims, tt, off) in enumerate(tensors):
|
| 91 |
+
if not name.startswith('blk.'):
|
| 92 |
+
src_idx.append(i); out_names.append(name); scale.append(1.0)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def layer_tensors(il):
|
| 96 |
+
return [j for j, t in enumerate(tensors) if t[0].startswith(f'blk.{il}.')]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def shifted(name, k):
|
| 100 |
+
p = name.split('.')
|
| 101 |
+
if p[0] == 'blk': p[1] = str(int(p[1]) + k)
|
| 102 |
+
return '.'.join(p)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def is_norm(name):
|
| 106 |
+
return name.endswith('post_attention_norm.weight') or name.endswith('post_ffw_norm.weight')
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
for il in range(n_layer):
|
| 110 |
+
for j in layer_tensors(il):
|
| 111 |
+
nm = tensors[j][0]
|
| 112 |
+
src_idx.append(j)
|
| 113 |
+
out_names.append(nm if il <= B else shifted(nm, NEW))
|
| 114 |
+
# damp the original window applications too
|
| 115 |
+
scale.append(ALPHA if (A <= il <= B and is_norm(nm)) else 1.0)
|
| 116 |
+
if il == B:
|
| 117 |
+
for rep in range(REPS - 1):
|
| 118 |
+
for lay in range(A, B + 1):
|
| 119 |
+
for j in layer_tensors(lay):
|
| 120 |
+
nm = tensors[j][0]
|
| 121 |
+
src_idx.append(j); out_names.append(shifted(nm, NEW))
|
| 122 |
+
scale.append(ALPHA if is_norm(nm) else 1.0)
|
| 123 |
+
|
| 124 |
+
assert len(src_idx) == len(out_names) == len(scale)
|
| 125 |
+
|
| 126 |
+
new_kvs = []
|
| 127 |
+
for k, t, v, et0 in kvs:
|
| 128 |
+
if k == 'lfm3.block_count':
|
| 129 |
+
new_kvs.append((k, t, n_layer + NEW, et0))
|
| 130 |
+
elif k in PER_LAYER:
|
| 131 |
+
assert len(v) == n_layer, (k, len(v), n_layer)
|
| 132 |
+
nv = list(v[:B + 1]) + [v[i] for _ in range(REPS - 1) for i in range(A, B + 1)] + list(v[B + 1:])
|
| 133 |
+
assert len(nv) == n_layer + NEW, (k, len(nv))
|
| 134 |
+
new_kvs.append((k, t, nv, et0))
|
| 135 |
+
else:
|
| 136 |
+
new_kvs.append((k, t, v, et0))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def enc_s(s):
|
| 140 |
+
b = s.encode() if isinstance(s, str) else s
|
| 141 |
+
return struct.pack('<Q', len(b)) + b
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def enc_kv(k, t, v, et0):
|
| 145 |
+
out = enc_s(k) + struct.pack('<I', t)
|
| 146 |
+
if t == 8:
|
| 147 |
+
out += enc_s(v)
|
| 148 |
+
elif t == 9:
|
| 149 |
+
et = et0 if et0 is not None else 8
|
| 150 |
+
out += struct.pack('<I', et) + struct.pack('<Q', len(v))
|
| 151 |
+
for x in v:
|
| 152 |
+
if et == 8: out += enc_s(x)
|
| 153 |
+
elif et == 4: out += struct.pack('<I', int(x))
|
| 154 |
+
elif et == 5: out += struct.pack('<i', int(x))
|
| 155 |
+
elif et == 6: out += struct.pack('<f', x)
|
| 156 |
+
elif et == 10: out += struct.pack('<Q', int(x))
|
| 157 |
+
elif et == 7: out += struct.pack('<?', bool(x))
|
| 158 |
+
else:
|
| 159 |
+
out += struct.pack(T[t], v)
|
| 160 |
+
return out
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
new_off, cur = [], 0
|
| 164 |
+
for j, si in enumerate(src_idx):
|
| 165 |
+
cur = (cur + alignment - 1) // alignment * alignment
|
| 166 |
+
new_off.append(cur)
|
| 167 |
+
cur += nbytes[si]
|
| 168 |
+
|
| 169 |
+
hdr = bytearray(b'GGUF' + struct.pack('<I', ver))
|
| 170 |
+
hdr += struct.pack('<Q', len(src_idx)) + struct.pack('<Q', len(new_kvs))
|
| 171 |
+
for k, t, v, et0 in new_kvs:
|
| 172 |
+
hdr += enc_kv(k, t, v, et0)
|
| 173 |
+
for j, si in enumerate(src_idx):
|
| 174 |
+
nm, dm, tt, o2 = tensors[si]
|
| 175 |
+
hdr += enc_s(out_names[j]) + struct.pack('<I', len(dm))
|
| 176 |
+
for d in dm:
|
| 177 |
+
hdr += struct.pack('<Q', d)
|
| 178 |
+
hdr += struct.pack('<I', tt) + struct.pack('<Q', new_off[j])
|
| 179 |
+
pad = (-len(hdr)) % alignment
|
| 180 |
+
|
| 181 |
+
print(f"layers {n_layer} -> {n_layer + NEW} window [{A}-{B}] x{REPS} alpha={ALPHA:.4f}")
|
| 182 |
+
print(f"tensors {n_tensors} -> {len(src_idx)} data {data_len/1e9:.3f} -> {cur/1e9:.3f} GB")
|
| 183 |
+
|
| 184 |
+
with open(DST, 'wb') as o:
|
| 185 |
+
o.write(hdr); o.write(b'\x00' * pad)
|
| 186 |
+
base = o.tell()
|
| 187 |
+
assert (base + new_off[0]) % alignment == 0
|
| 188 |
+
for j, si in enumerate(src_idx):
|
| 189 |
+
want = base + new_off[j]
|
| 190 |
+
assert o.tell() <= want
|
| 191 |
+
o.write(b'\x00' * (want - o.tell()))
|
| 192 |
+
f.seek(data_start + tensors[si][3])
|
| 193 |
+
if scale[j] != 1.0:
|
| 194 |
+
tt = tensors[si][2]
|
| 195 |
+
assert tt == 0, f"damped tensor {out_names[j]} is type {tt}, expected f32"
|
| 196 |
+
buf = np.frombuffer(f.read(nbytes[si]), dtype=np.float32) * np.float32(scale[j])
|
| 197 |
+
o.write(buf.astype(np.float32).tobytes())
|
| 198 |
+
else:
|
| 199 |
+
left = nbytes[si]
|
| 200 |
+
while left:
|
| 201 |
+
chunk = f.read(min(left, 32 << 20))
|
| 202 |
+
if not chunk: raise EOFError
|
| 203 |
+
o.write(chunk); left -= len(chunk)
|
| 204 |
+
print("wrote", DST, os.path.getsize(DST), "bytes")
|
scripts/save_loop_hf.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Save the training-free looped LFM3 (default: window [8,11] x2, alpha=0.5) as a plain
|
| 3 |
+
HF checkpoint, so it loads with trust_remote_code and scores in lm-evaluation-harness.
|
| 4 |
+
|
| 5 |
+
python save_loop_hf.py --base LiquidAI/LFM3-1.7B-Base --out ./LFM3-1.7B-loop-8-11
|
| 6 |
+
"""
|
| 7 |
+
import argparse, os, shutil, sys
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 11 |
+
import tfl
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
ap = argparse.ArgumentParser()
|
| 16 |
+
ap.add_argument("--base", default=os.environ.get("LFM3_BASE", "LiquidAI/LFM3-1.7B-Base"))
|
| 17 |
+
ap.add_argument("--out", required=True)
|
| 18 |
+
ap.add_argument("--window", default="8,11")
|
| 19 |
+
ap.add_argument("--reps", type=int, default=2)
|
| 20 |
+
ap.add_argument("--alpha", type=float, default=0.5)
|
| 21 |
+
ap.add_argument("--device", default="cpu", help="cpu (default) or cuda")
|
| 22 |
+
args = ap.parse_args()
|
| 23 |
+
|
| 24 |
+
def load_here(path=None, dtype=torch.bfloat16):
|
| 25 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 26 |
+
tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
|
| 27 |
+
m = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
args.base, trust_remote_code=True, dtype=dtype,
|
| 29 |
+
attn_implementation="sdpa", device_map={"": args.device})
|
| 30 |
+
return m, tok
|
| 31 |
+
|
| 32 |
+
tfl.load = load_here
|
| 33 |
+
a, b = [int(x) for x in args.window.split(",")]
|
| 34 |
+
m, tok = tfl.build((a, b), reps=args.reps, alpha=args.alpha)
|
| 35 |
+
print(f"layers {m.config.num_hidden_layers} layer_types {len(m.config.layer_types)}")
|
| 36 |
+
os.makedirs(args.out, exist_ok=True)
|
| 37 |
+
m.save_pretrained(args.out, safe_serialization=True)
|
| 38 |
+
tok.save_pretrained(args.out)
|
| 39 |
+
# trust_remote_code checkpoints need their code files alongside the weights
|
| 40 |
+
if os.path.isdir(str(args.base)):
|
| 41 |
+
for f in ("modeling_lfm3.py", "configuration_lfm3.py", "lfm3_conv.py", "chat_template.jinja"):
|
| 42 |
+
src = os.path.join(args.base, f)
|
| 43 |
+
if os.path.exists(src):
|
| 44 |
+
shutil.copy(src, os.path.join(args.out, f))
|
| 45 |
+
else:
|
| 46 |
+
print("note: --base is a hub id; copy the custom modeling files from it into", args.out)
|
| 47 |
+
total = sum(os.path.getsize(os.path.join(args.out, f)) for f in os.listdir(args.out))
|
| 48 |
+
print(f"saved {args.out} {total/1e9:.2f} GB")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
scripts/tfl.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Training-free looped LFM3: repeat a mid-stack window with damped residual steps.
|
| 3 |
+
|
| 4 |
+
Implements the "run x layers K times, 1/K of a step per pass" wrapper from
|
| 5 |
+
arXiv 2605.23872 (training-free looped transformers) as a *static* graph:
|
| 6 |
+
the window is physically duplicated and every application's residual output is
|
| 7 |
+
damped by alpha, so the result is a plain deeper HF model that supports
|
| 8 |
+
generate()/KV-cache with no runtime wrapper.
|
| 9 |
+
|
| 10 |
+
Why the damping goes in the sandwich norms
|
| 11 |
+
------------------------------------------
|
| 12 |
+
Each LFM3 layer is h' = h + post_op_norm(op(pre_norm(h))) + post_ffn_norm(ffn(...)).
|
| 13 |
+
Scaling o_proj/out_proj/w2 does NOT damp the branch: the post-norm is RMSNorm, which
|
| 14 |
+
divides out the scale. Scaling `post_operator_norm.weight` / `post_ffn_norm.weight`
|
| 15 |
+
by alpha scales the branch output by exactly alpha, which is the step damping.
|
| 16 |
+
|
| 17 |
+
alpha=1/reps, reps=2 -> damped Euler K=2: x <- x + 1/2 (g(x) - x), twice
|
| 18 |
+
alpha=1.0, reps=2 -> naive loop (control: paper says this degrades)
|
| 19 |
+
alpha=0.75, reps=1 -> static equivalent of the paper's K=2 RK beta=0.5
|
| 20 |
+
|
| 21 |
+
Subcommands: identity | ppl | grid | bake | gsm8k
|
| 22 |
+
"""
|
| 23 |
+
import argparse, copy, json, math, os, re, sys, time
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
|
| 27 |
+
BASE = os.environ.get("LFM3_BASE", "base-model")
|
| 28 |
+
DATA = os.environ.get("LFM3_DATA", "data")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load(path=None, dtype=torch.bfloat16):
|
| 32 |
+
path = path or BASE
|
| 33 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 34 |
+
tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
| 35 |
+
m = AutoModelForCausalLM.from_pretrained(
|
| 36 |
+
path, trust_remote_code=True, dtype=dtype, attn_implementation="sdpa", device_map={"": 0})
|
| 37 |
+
return m, tok
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _damp(layer, alpha):
|
| 41 |
+
if alpha == 1.0:
|
| 42 |
+
return
|
| 43 |
+
with torch.no_grad():
|
| 44 |
+
layer.post_operator_norm.weight.mul_(alpha)
|
| 45 |
+
layer.post_ffn_norm.weight.mul_(alpha)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def scale_q(m, beta):
|
| 49 |
+
"""Multiply every attention query projection by beta = global attention temperature."""
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
for lay in m.model.layers:
|
| 52 |
+
if not hasattr(lay, "self_attn"):
|
| 53 |
+
continue # LFM3 alternates: conv layers have no attention
|
| 54 |
+
q = lay.self_attn.q_proj
|
| 55 |
+
q.weight.mul_(beta)
|
| 56 |
+
if getattr(q, "bias", None) is not None:
|
| 57 |
+
q.bias.mul_(beta)
|
| 58 |
+
return m
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def scale_all_post(m, gamma):
|
| 62 |
+
"""Scale every layer's residual branch output by gamma (global residual gain)."""
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
for lay in m.model.layers:
|
| 65 |
+
lay.post_operator_norm.weight.mul_(gamma)
|
| 66 |
+
lay.post_ffn_norm.weight.mul_(gamma)
|
| 67 |
+
return m
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def conv_loop(m, a, b, alpha=0.5):
|
| 71 |
+
"""Repeat ONLY the shortconv sublayer inside [a,b], damped alpha per pass.
|
| 72 |
+
Attention layers in the window are left untouched (LFM3 alternates conv/attn)."""
|
| 73 |
+
n = 0
|
| 74 |
+
for lay in m.model.layers[a:b + 1]:
|
| 75 |
+
if hasattr(lay, "self_attn"):
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
def make(layer, al=alpha):
|
| 79 |
+
def fwd(hidden_states, position_embeddings=None, attention_mask=None,
|
| 80 |
+
position_ids=None, past_key_values=None, seq_idx=None, **kw):
|
| 81 |
+
res = hidden_states
|
| 82 |
+
h = layer.conv(layer.operator_norm(res), past_key_values=past_key_values,
|
| 83 |
+
attention_mask=attention_mask, seq_idx=seq_idx)
|
| 84 |
+
h = layer.post_operator_norm(h)
|
| 85 |
+
mid = res + al * h
|
| 86 |
+
h2 = layer.conv(layer.operator_norm(mid), past_key_values=past_key_values,
|
| 87 |
+
attention_mask=attention_mask, seq_idx=seq_idx)
|
| 88 |
+
h2 = layer.post_operator_norm(h2)
|
| 89 |
+
out = mid + al * h2
|
| 90 |
+
f = layer.feed_forward(layer.ffn_norm(out))
|
| 91 |
+
f = layer.post_ffn_norm(f)
|
| 92 |
+
return out + f
|
| 93 |
+
return fwd
|
| 94 |
+
|
| 95 |
+
lay.forward = make(lay)
|
| 96 |
+
n += 1
|
| 97 |
+
print(f"conv_loop: patched {n} conv sublayers in [{a},{b}] alpha={alpha}", flush=True)
|
| 98 |
+
return m
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def build_multi(ops):
|
| 102 |
+
"""Several loop windows in one model. ops: list of (a, b, reps, alpha), applied from
|
| 103 |
+
the highest start index down so that earlier indices stay valid while later ones shift.
|
| 104 |
+
Disjoint windows compose; overlapping ones are not checked."""
|
| 105 |
+
m, tok = load()
|
| 106 |
+
inner = m.model
|
| 107 |
+
n0 = len(inner.layers)
|
| 108 |
+
for a, b, reps, alpha in sorted(ops, key=lambda o: -o[0]):
|
| 109 |
+
types = list(inner.config.layer_types)
|
| 110 |
+
chunk = list(inner.layers[a:b + 1])
|
| 111 |
+
for lay in chunk:
|
| 112 |
+
_damp(lay, alpha)
|
| 113 |
+
new = []
|
| 114 |
+
for r in range(reps - 1):
|
| 115 |
+
for j, lay in enumerate(chunk):
|
| 116 |
+
new.append(copy.deepcopy(lay))
|
| 117 |
+
inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:]))
|
| 118 |
+
inner.config.layer_types = (types[:b + 1]
|
| 119 |
+
+ [types[a + j] for _ in range(reps - 1) for j in range(len(chunk))]
|
| 120 |
+
+ types[b + 1:])
|
| 121 |
+
assert len(inner.layers) == len(inner.config.layer_types)
|
| 122 |
+
inner.config.num_hidden_layers = len(inner.layers)
|
| 123 |
+
m.config.num_hidden_layers = inner.config.num_hidden_layers
|
| 124 |
+
m.config.layer_types = inner.config.layer_types
|
| 125 |
+
for pos, lay in enumerate(inner.layers):
|
| 126 |
+
if hasattr(lay, "self_attn"):
|
| 127 |
+
lay.self_attn.layer_idx = pos
|
| 128 |
+
if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"):
|
| 129 |
+
lay.conv.layer_idx = pos
|
| 130 |
+
m.eval()
|
| 131 |
+
return m, tok
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def build(window=(10, 13), reps=2, alpha=None, gains=None):
|
| 135 |
+
"""Return a plain HF model: window [a,b] executed `reps` times, each application
|
| 136 |
+
damped by `alpha` (default 1/reps = K equal sub-steps of the same total update).
|
| 137 |
+
`gains` overrides per-application damping, e.g. [0.5, 1.0] = RK2 midpoint."""
|
| 138 |
+
if gains is not None:
|
| 139 |
+
reps = len(gains)
|
| 140 |
+
alpha = (1.0 / reps) if alpha is None else float(alpha)
|
| 141 |
+
if gains is None:
|
| 142 |
+
gains = [alpha] * reps
|
| 143 |
+
assert len(gains) == reps
|
| 144 |
+
m, tok = load()
|
| 145 |
+
inner = m.model
|
| 146 |
+
a, b = window
|
| 147 |
+
chunk = list(inner.layers[a:b + 1])
|
| 148 |
+
types = list(inner.config.layer_types)
|
| 149 |
+
n0 = len(inner.layers)
|
| 150 |
+
|
| 151 |
+
# damp every application, including the original window
|
| 152 |
+
for lay in chunk:
|
| 153 |
+
_damp(lay, gains[0])
|
| 154 |
+
|
| 155 |
+
new, new_types = [], []
|
| 156 |
+
for r in range(reps - 1):
|
| 157 |
+
for j, lay in enumerate(chunk):
|
| 158 |
+
c = copy.deepcopy(lay)
|
| 159 |
+
if gains[r + 1] != gains[0]:
|
| 160 |
+
# copy carries the first pass's scale; rescale to this pass's gain
|
| 161 |
+
with torch.no_grad():
|
| 162 |
+
c.post_operator_norm.weight.mul_(gains[r + 1] / gains[0])
|
| 163 |
+
c.post_ffn_norm.weight.mul_(gains[r + 1] / gains[0])
|
| 164 |
+
new.append(c)
|
| 165 |
+
new_types.append(types[a + j])
|
| 166 |
+
|
| 167 |
+
inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:]))
|
| 168 |
+
inner.config.layer_types = types[:b + 1] + new_types + types[b + 1:]
|
| 169 |
+
inner.config.num_hidden_layers = n0 + len(new)
|
| 170 |
+
m.config.num_hidden_layers = inner.config.num_hidden_layers
|
| 171 |
+
m.config.layer_types = inner.config.layer_types
|
| 172 |
+
# layer_idx must equal the layer's POSITION: the KV cache and the per-layer
|
| 173 |
+
# metadata arrays are indexed by it, so a mid-stack insertion shifts every
|
| 174 |
+
# later layer and every copy must take its own slot.
|
| 175 |
+
for pos, lay in enumerate(inner.layers):
|
| 176 |
+
if hasattr(lay, "self_attn"):
|
| 177 |
+
lay.self_attn.layer_idx = pos
|
| 178 |
+
if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"):
|
| 179 |
+
lay.conv.layer_idx = pos
|
| 180 |
+
m.eval()
|
| 181 |
+
return m, tok
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# ---------------------------------------------------------------- reference wrapper
|
| 185 |
+
class RefLoop:
|
| 186 |
+
"""Independent implementation of the same math without duplicating weights:
|
| 187 |
+
scale the two sandwich-norm outputs, then run the window `reps` times."""
|
| 188 |
+
|
| 189 |
+
def __init__(self, model, window, reps, alpha):
|
| 190 |
+
self.model, self.reps, self.alpha = model, reps, alpha
|
| 191 |
+
self.a, self.b = window
|
| 192 |
+
self.handles = []
|
| 193 |
+
for i in range(self.a, self.b + 1):
|
| 194 |
+
lay = model.model.layers[i]
|
| 195 |
+
for mod in (lay.post_operator_norm, lay.post_ffn_norm):
|
| 196 |
+
self.handles.append(mod.register_forward_hook(self._hook))
|
| 197 |
+
|
| 198 |
+
def _hook(self, module, args, out):
|
| 199 |
+
return out * self.alpha
|
| 200 |
+
|
| 201 |
+
def run(self, model_layer_loop):
|
| 202 |
+
return model_layer_loop(self.reps)
|
| 203 |
+
|
| 204 |
+
def remove(self):
|
| 205 |
+
for h in self.handles:
|
| 206 |
+
h.remove()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@torch.no_grad()
|
| 210 |
+
def ref_forward(model, ids, window, reps, alpha):
|
| 211 |
+
"""Compose pre-loop layers, then the window x reps, then post-loop layers."""
|
| 212 |
+
inner = model.model
|
| 213 |
+
a, b = window
|
| 214 |
+
ref = RefLoop(model, window, reps, alpha)
|
| 215 |
+
h = inner.embed_tokens(ids)
|
| 216 |
+
pos = torch.arange(ids.shape[1], device=ids.device).unsqueeze(0)
|
| 217 |
+
pe = {t: inner.rotary_emb(h, position_ids=pos, layer_type=t) for t in inner.rotary_emb.layer_types}
|
| 218 |
+
modeling = sys.modules[inner.__class__.__module__]
|
| 219 |
+
cm = modeling.create_masks_by_layer_type(config=inner.config, inputs_embeds=h, attention_mask=None,
|
| 220 |
+
past_key_values=None, position_ids=pos)
|
| 221 |
+
def run(i):
|
| 222 |
+
nonlocal h
|
| 223 |
+
lt = inner.config.layer_types[i]
|
| 224 |
+
h = inner.layers[i](h, attention_mask=cm[lt], position_embeddings=pe.get(lt),
|
| 225 |
+
position_ids=pos, past_key_values=None, seq_idx=None)
|
| 226 |
+
for i in range(a):
|
| 227 |
+
run(i)
|
| 228 |
+
for _ in range(reps):
|
| 229 |
+
for i in range(a, b + 1):
|
| 230 |
+
run(i)
|
| 231 |
+
for i in range(b + 1, len(inner.layers)):
|
| 232 |
+
run(i)
|
| 233 |
+
ref.remove()
|
| 234 |
+
return inner.embedding_norm(h)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ---------------------------------------------------------------- data / metrics
|
| 238 |
+
class TextDS(torch.utils.data.Dataset):
|
| 239 |
+
def __init__(self, path, tok, ctx, max_windows=None):
|
| 240 |
+
ids = []
|
| 241 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 242 |
+
buf = []
|
| 243 |
+
for line in f:
|
| 244 |
+
line = line.strip()
|
| 245 |
+
if not line:
|
| 246 |
+
continue
|
| 247 |
+
buf.append(line)
|
| 248 |
+
if len(buf) >= 64:
|
| 249 |
+
ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"])
|
| 250 |
+
buf = []
|
| 251 |
+
if max_windows and len(ids) >= max_windows * ctx:
|
| 252 |
+
break
|
| 253 |
+
if buf:
|
| 254 |
+
ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"])
|
| 255 |
+
self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)]
|
| 256 |
+
if max_windows:
|
| 257 |
+
self.windows = self.windows[:max_windows]
|
| 258 |
+
|
| 259 |
+
def __len__(self):
|
| 260 |
+
return len(self.windows)
|
| 261 |
+
|
| 262 |
+
def __getitem__(self, i):
|
| 263 |
+
w = self.windows[i]
|
| 264 |
+
return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class StreamDS(torch.utils.data.Dataset):
|
| 268 |
+
"""Whole-file tokenisation (single stream), the way llama-perplexity reads it.
|
| 269 |
+
TextDS's 64-line joining inflates PPL and is not comparable across models."""
|
| 270 |
+
|
| 271 |
+
def __init__(self, path, tok, ctx, n=None, max_windows=None):
|
| 272 |
+
n = n or max_windows
|
| 273 |
+
ids = tok(open(path, "r", encoding="utf-8", errors="ignore").read(), add_special_tokens=False)["input_ids"]
|
| 274 |
+
self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)][:n]
|
| 275 |
+
|
| 276 |
+
def __len__(self):
|
| 277 |
+
return len(self.windows)
|
| 278 |
+
|
| 279 |
+
def __getitem__(self, i):
|
| 280 |
+
w = self.windows[i]
|
| 281 |
+
return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)}
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@torch.no_grad()
|
| 285 |
+
def ppl(model, ds, n_batches=16, bs=2):
|
| 286 |
+
model.eval()
|
| 287 |
+
dl = torch.utils.data.DataLoader(ds, batch_size=bs, shuffle=False)
|
| 288 |
+
tot, cnt = 0.0, 0
|
| 289 |
+
for i, b in enumerate(dl):
|
| 290 |
+
if i >= n_batches:
|
| 291 |
+
break
|
| 292 |
+
ids = b["input_ids"].cuda()
|
| 293 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 294 |
+
out = model(input_ids=ids, labels=ids)
|
| 295 |
+
tot += out.loss.float().item() * ids.numel()
|
| 296 |
+
cnt += ids.numel()
|
| 297 |
+
return math.exp(tot / cnt)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def gsm8k_rows(n=100):
|
| 301 |
+
rows, txt = [], open(os.path.join(DATA, "gsm8k-test.txt")).read()
|
| 302 |
+
for block in txt.split("\n\n"):
|
| 303 |
+
mm = re.search(r"Question: (.*?)\nAnswer: (.*)", block, re.S)
|
| 304 |
+
if not mm:
|
| 305 |
+
continue
|
| 306 |
+
gold = re.search(r"####\s*([\-\d\.,]+)", mm.group(2))
|
| 307 |
+
if gold:
|
| 308 |
+
rows.append((mm.group(1).strip(), gold.group(1).replace(",", "").strip()))
|
| 309 |
+
if len(rows) >= n:
|
| 310 |
+
break
|
| 311 |
+
return rows
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def last_number(s):
|
| 315 |
+
nums = re.findall(r"-?\d[\d,]*\.?\d*", s.replace("$", ""))
|
| 316 |
+
return nums[-1].replace(",", "").rstrip(".") if nums else None
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@torch.no_grad()
|
| 320 |
+
def run_gsm8k(model, tok, rows, max_new=512):
|
| 321 |
+
ok = 0
|
| 322 |
+
for q, gold in rows:
|
| 323 |
+
msgs = [{"role": "user", "content": q + "\nAnswer with the final number on its own line."}]
|
| 324 |
+
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 325 |
+
ids = tok(text, return_tensors="pt").input_ids.cuda()
|
| 326 |
+
out = model.generate(ids, max_new_tokens=max_new, do_sample=False, temperature=None,
|
| 327 |
+
top_p=None, top_k=None, pad_token_id=tok.pad_token_id or tok.eos_token_id)
|
| 328 |
+
pred = last_number(tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True))
|
| 329 |
+
ok += pred is not None and abs(float(pred) - float(gold)) < 0.01
|
| 330 |
+
return ok / len(rows)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def arc_rows(config="ARC-Easy", n=500, shots=0):
|
| 334 |
+
from datasets import load_dataset
|
| 335 |
+
d = load_dataset("allenai/ai2_arc", config, split="test")
|
| 336 |
+
pre = ""
|
| 337 |
+
if shots:
|
| 338 |
+
tr = load_dataset("allenai/ai2_arc", config, split="train")
|
| 339 |
+
for r in tr.select(range(min(shots, len(tr)))):
|
| 340 |
+
ans = r["choices"]["text"][r["choices"]["label"].index(r["answerKey"])]
|
| 341 |
+
pre += f"Question: {r['question']}\nAnswer: {ans}\n\n"
|
| 342 |
+
rows = []
|
| 343 |
+
for r in d:
|
| 344 |
+
lab, txt = r["choices"]["label"], r["choices"]["text"]
|
| 345 |
+
if r["answerKey"] not in lab:
|
| 346 |
+
continue
|
| 347 |
+
rows.append((r["question"], lab, txt, lab.index(r["answerKey"])))
|
| 348 |
+
if len(rows) >= n:
|
| 349 |
+
break
|
| 350 |
+
return rows, pre
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@torch.no_grad()
|
| 354 |
+
def run_arc(model, tok, rows, pre="", score="mean", dump=False):
|
| 355 |
+
"""ARC multiple-choice, base-LM style: score each choice *text* as the continuation
|
| 356 |
+
of "Question: ...\\nAnswer:" and take the argmax of the (optionally length-normalised)
|
| 357 |
+
log-probability."""
|
| 358 |
+
per, alls = [], []
|
| 359 |
+
for q, lab, txt, gold in rows:
|
| 360 |
+
pid = tok(pre + "Question: " + q + "\nAnswer:", return_tensors="pt").input_ids.cuda()
|
| 361 |
+
scores = []
|
| 362 |
+
for t in txt:
|
| 363 |
+
cid = tok(" " + t, add_special_tokens=False, return_tensors="pt").input_ids.cuda()
|
| 364 |
+
out = model(input_ids=torch.cat([pid, cid], dim=1), use_cache=False)
|
| 365 |
+
lp = torch.log_softmax(out.logits[0, pid.shape[1] - 1:pid.shape[1] - 1 + cid.shape[1]].float(), -1)
|
| 366 |
+
s = lp[range(cid.shape[1]), cid[0]]
|
| 367 |
+
scores.append(s.mean().item() if score == "mean" else s.sum().item())
|
| 368 |
+
del out
|
| 369 |
+
per.append(int(max(range(len(txt)), key=lambda i: scores[i]) == gold))
|
| 370 |
+
alls.append(scores)
|
| 371 |
+
return (per, alls) if dump else per
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def main():
|
| 375 |
+
ap = argparse.ArgumentParser()
|
| 376 |
+
ap.add_argument("cmd", choices=["identity", "ppl", "grid", "gsm8k", "bake", "arc", "sweep"])
|
| 377 |
+
ap.add_argument("--window", default="10,13")
|
| 378 |
+
ap.add_argument("--base", action="store_true", help="evaluate the unmodified checkpoint")
|
| 379 |
+
ap.add_argument("--reps", type=int, default=2)
|
| 380 |
+
ap.add_argument("--alpha", type=float, default=None)
|
| 381 |
+
ap.add_argument("--n-pll", type=int, default=16)
|
| 382 |
+
ap.add_argument("--gsm", type=int, default=80)
|
| 383 |
+
ap.add_argument("--arc-config", default="ARC-Easy")
|
| 384 |
+
ap.add_argument("--arc-n", type=int, default=400)
|
| 385 |
+
ap.add_argument("--shots", type=int, default=0)
|
| 386 |
+
ap.add_argument("--stream", action="store_true")
|
| 387 |
+
ap.add_argument("--multi", default=None, help="a,b,reps,alpha;... several loop windows")
|
| 388 |
+
ap.add_argument("--gains", default=None, help="comma list, per-pass damping e.g. 0.5,1.0")
|
| 389 |
+
ap.add_argument("--qscale", type=float, default=1.0, help="global query scale = attention temperature")
|
| 390 |
+
ap.add_argument("--postscale", type=float, default=1.0, help="global residual branch gain")
|
| 391 |
+
ap.add_argument("--convloop", default=None, help="a,b,alpha: run only the shortconv sublayer twice inside [a,b]")
|
| 392 |
+
ap.add_argument("--arc-score", default="mean", choices=["mean", "sum"])
|
| 393 |
+
ap.add_argument("--out", default="out-tfl")
|
| 394 |
+
ap.add_argument("--data-dir", default=os.environ.get("LFM3_DATA", "data"),
|
| 395 |
+
help="dir with wikitext-test.txt / gsm8k-test.txt / gsm8k-train-chat.txt")
|
| 396 |
+
ap.add_argument("--base-model", default=os.environ.get("LFM3_BASE", "base-model"),
|
| 397 |
+
help="HF dir of the unmodified checkpoint (default $LFM3_BASE)")
|
| 398 |
+
args = ap.parse_args()
|
| 399 |
+
global BASE, DATA
|
| 400 |
+
BASE = args.base_model
|
| 401 |
+
DATA = args.data_dir
|
| 402 |
+
a, b = [int(x) for x in args.window.split(",")]
|
| 403 |
+
window = (a, b)
|
| 404 |
+
|
| 405 |
+
if args.cmd == "identity":
|
| 406 |
+
base, tok = load()
|
| 407 |
+
ids = torch.randint(1000, 60000, (1, 128), device="cuda")
|
| 408 |
+
with torch.no_grad():
|
| 409 |
+
ref = base(input_ids=ids).logits.float()
|
| 410 |
+
# same weights, no extra copy -> must be exact
|
| 411 |
+
dup, _ = build(window, reps=1, alpha=1.0)
|
| 412 |
+
with torch.no_grad():
|
| 413 |
+
got = dup(input_ids=ids).logits.float()
|
| 414 |
+
d = (ref - got).abs().max().item()
|
| 415 |
+
print(f"build(window={window}, reps=1, alpha=1) vs base: max|dlogit| = {d:.3e}")
|
| 416 |
+
del dup
|
| 417 |
+
torch.cuda.empty_cache()
|
| 418 |
+
# reference wrapper: run the same window reps times with alpha damping
|
| 419 |
+
for alpha in (1.0, 0.5, 1 / 3):
|
| 420 |
+
h_ref = ref_forward(base, ids, window, args.reps, alpha).float()
|
| 421 |
+
damp, _ = build(window, reps=args.reps, alpha=alpha)
|
| 422 |
+
with torch.no_grad():
|
| 423 |
+
h_dup = damp.model(input_ids=ids).last_hidden_state.float()
|
| 424 |
+
dd = (h_ref - h_dup).abs().max().item()
|
| 425 |
+
print(f"alpha={alpha:.3f}: wrapper vs static dup max|d| = {dd:.3e}")
|
| 426 |
+
del damp
|
| 427 |
+
torch.cuda.empty_cache()
|
| 428 |
+
return
|
| 429 |
+
|
| 430 |
+
if args.cmd in ("ppl", "bake", "arc", "gsm8k"):
|
| 431 |
+
if args.base:
|
| 432 |
+
m, tok = load()
|
| 433 |
+
m.eval()
|
| 434 |
+
tag = "base"
|
| 435 |
+
elif args.multi:
|
| 436 |
+
ops = []
|
| 437 |
+
for spec in args.multi.split(";"):
|
| 438 |
+
aa, bb, rr, al = [float(x) for x in spec.split(",")]
|
| 439 |
+
ops.append((int(aa), int(bb), int(rr), al))
|
| 440 |
+
m, tok = build_multi(ops)
|
| 441 |
+
tag = "multi:" + "+".join(f"{o[0]}-{o[1]}x{o[2]}@{o[3]:.2f}" for o in ops)
|
| 442 |
+
else:
|
| 443 |
+
gains = [float(x) for x in args.gains.split(",")] if args.gains else None
|
| 444 |
+
m, tok = build(window, reps=args.reps, alpha=args.alpha, gains=gains)
|
| 445 |
+
tag = (f"{args.window} gains={gains}" if gains
|
| 446 |
+
else f"{args.window} x{args.reps} alpha={1/args.reps if args.alpha is None else args.alpha}")
|
| 447 |
+
if args.qscale != 1.0:
|
| 448 |
+
scale_q(m, args.qscale)
|
| 449 |
+
tag += f" q*{args.qscale}"
|
| 450 |
+
if args.postscale != 1.0:
|
| 451 |
+
scale_all_post(m, args.postscale)
|
| 452 |
+
tag += f" post*{args.postscale}"
|
| 453 |
+
if args.convloop:
|
| 454 |
+
ca, cb, cal = [float(x) for x in args.convloop.split(",")]
|
| 455 |
+
conv_loop(m, int(ca), int(cb), cal)
|
| 456 |
+
tag += f" convloop{args.convloop}"
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
if args.cmd == "ppl":
|
| 460 |
+
DS = StreamDS if args.stream else TextDS
|
| 461 |
+
wt = DS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 462 |
+
ood = StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, args.n_pll * 2) if args.stream else TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 463 |
+
print(json.dumps({"tag": tag, "wikitext": round(ppl(m, wt, args.n_pll), 4),
|
| 464 |
+
"gsm8k_text": round(ppl(m, ood, args.n_pll), 4)}))
|
| 465 |
+
return
|
| 466 |
+
|
| 467 |
+
if args.cmd == "grid":
|
| 468 |
+
cfg = [
|
| 469 |
+
("base", None, 1, 1.0),
|
| 470 |
+
("naive K2 @[10-13]", (10, 13), 2, 1.0),
|
| 471 |
+
("damped K2 @[10-13]", (10, 13), 2, 0.5),
|
| 472 |
+
("damped K3 @[10-13]", (10, 13), 3, 1 / 3),
|
| 473 |
+
("step0.75 @[10-13]", (10, 13), 1, 0.75),
|
| 474 |
+
("damped K2 @[8-11]", (8, 11), 2, 0.5),
|
| 475 |
+
("damped K2 @[12-15]", (12, 15), 2, 0.5),
|
| 476 |
+
("damped K2 @[11-12]", (11, 12), 2, 0.5),
|
| 477 |
+
("damped K2 @[9-12]", (9, 12), 2, 0.5),
|
| 478 |
+
]
|
| 479 |
+
tok = None
|
| 480 |
+
rows = []
|
| 481 |
+
for tag, w, reps, alpha in cfg:
|
| 482 |
+
t0 = time.time()
|
| 483 |
+
if w is None:
|
| 484 |
+
m, tok = load()
|
| 485 |
+
m.eval()
|
| 486 |
+
else:
|
| 487 |
+
m, tok = build(w, reps=reps, alpha=alpha)
|
| 488 |
+
wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 489 |
+
ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 490 |
+
r = {"tag": tag, "layers": m.config.num_hidden_layers,
|
| 491 |
+
"wikitext": round(ppl(m, wt, args.n_pll), 4),
|
| 492 |
+
"gsm8k_text": round(ppl(m, ood, args.n_pll), 4), "s": round(time.time() - t0, 1)}
|
| 493 |
+
print(json.dumps(r), flush=True)
|
| 494 |
+
rows.append(r)
|
| 495 |
+
del m
|
| 496 |
+
torch.cuda.empty_cache()
|
| 497 |
+
json.dump(rows, open(os.path.join(args.out, "grid.json"), "w"), indent=1)
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
if args.cmd == "sweep":
|
| 501 |
+
m, tok = load()
|
| 502 |
+
m.eval()
|
| 503 |
+
wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 504 |
+
ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
|
| 505 |
+
names = []
|
| 506 |
+
for i in range(a, b + 1):
|
| 507 |
+
names += [m.model.layers[i].post_operator_norm.weight, m.model.layers[i].post_ffn_norm.weight]
|
| 508 |
+
orig = [t.detach().clone() for t in names]
|
| 509 |
+
for alpha in (1.0, 1.25, 1.5, 0.9, 0.85, 0.75, 0.7, 0.6, 0.5, 0.4, 0.3):
|
| 510 |
+
with torch.no_grad():
|
| 511 |
+
for t, o in zip(names, orig):
|
| 512 |
+
t.copy_(o).mul_(alpha)
|
| 513 |
+
print(json.dumps({"alpha": alpha, "wikitext": round(ppl(m, wt, args.n_pll), 4),
|
| 514 |
+
"gsm8k_text": round(ppl(m, ood, args.n_pll), 4)}), flush=True)
|
| 515 |
+
with torch.no_grad():
|
| 516 |
+
for t, o in zip(names, orig):
|
| 517 |
+
t.copy_(o)
|
| 518 |
+
return
|
| 519 |
+
|
| 520 |
+
if args.cmd == "bake":
|
| 521 |
+
outdir = os.path.join(args.out, f"baked-{a}_{b}-x{args.reps}@{ (1/args.reps if args.alpha is None else args.alpha):.3f}".replace("/", "") )
|
| 522 |
+
m.save_pretrained(outdir)
|
| 523 |
+
tok.save_pretrained(outdir)
|
| 524 |
+
for f in ("modeling_lfm3.py", "configuration_lfm3.py", "lfm3_conv.py", "chat_template.jinja"):
|
| 525 |
+
src = os.path.join(BASE, f)
|
| 526 |
+
if os.path.exists(src):
|
| 527 |
+
import shutil
|
| 528 |
+
shutil.copy2(src, os.path.join(outdir, f))
|
| 529 |
+
print("baked ->", outdir, "layers:", m.config.num_hidden_layers)
|
| 530 |
+
return
|
| 531 |
+
|
| 532 |
+
if args.cmd == "arc":
|
| 533 |
+
rows, pre = arc_rows(args.arc_config, args.arc_n, args.shots)
|
| 534 |
+
t0 = time.time()
|
| 535 |
+
per, lps = run_arc(m, tok, rows, pre, args.arc_score, dump=True)
|
| 536 |
+
acc = sum(per) / len(per)
|
| 537 |
+
print(f"{tag}: {args.arc_config} {args.shots}-shot acc_norm {acc*100:.1f}% over {len(per)} ({time.time()-t0:.0f}s)", flush=True)
|
| 538 |
+
key = f"arc-{args.arc_config}-{args.arc_n}-{args.shots}shot-{args.arc_score}-{tag}".replace(" ", "").replace(",", "_").replace("=", "")
|
| 539 |
+
json.dump({"per": per, "lp": lps, "gold": [r[3] for r in rows], "n_opt": [len(r[2]) for r in rows]},
|
| 540 |
+
open(os.path.join(args.out, key + ".json"), "w"))
|
| 541 |
+
return
|
| 542 |
+
|
| 543 |
+
if args.cmd == "gsm8k":
|
| 544 |
+
rows = gsm8k_rows(args.gsm)
|
| 545 |
+
t0 = time.time()
|
| 546 |
+
acc = run_gsm8k(m, tok, rows)
|
| 547 |
+
print(f"{tag}: GSM8K {acc*100:.1f}% over {len(rows)} ({time.time()-t0:.0f}s)", flush=True)
|
| 548 |
+
return
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
main()
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41927bd314d17d7d7fadb44e10cd0919f7b71528d7741596d8cbd15c6945ec44
|
| 3 |
+
size 17908634
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"audio_out_token": "<|audio_out|>",
|
| 3 |
+
"audio_token": "<|audio|>",
|
| 4 |
+
"backend": "tokenizers",
|
| 5 |
+
"bos_token": "<|startoftext|>",
|
| 6 |
+
"eos_token": "<|im_end|>",
|
| 7 |
+
"extra_special_tokens": [],
|
| 8 |
+
"image_token": "<|image|>",
|
| 9 |
+
"is_local": true,
|
| 10 |
+
"local_files_only": false,
|
| 11 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 12 |
+
"model_specific_special_tokens": {
|
| 13 |
+
"audio_out_token": "<|audio_out|>",
|
| 14 |
+
"audio_token": "<|audio|>",
|
| 15 |
+
"image_token": "<|image|>",
|
| 16 |
+
"video_token": "<|video|>",
|
| 17 |
+
"vision_end_token": "<|vision_end|>",
|
| 18 |
+
"vision_start_token": "<|vision_start|>"
|
| 19 |
+
},
|
| 20 |
+
"pad_token": "<|pad|>",
|
| 21 |
+
"response_template": {
|
| 22 |
+
"defaults": {
|
| 23 |
+
"role": "assistant"
|
| 24 |
+
},
|
| 25 |
+
"fields": {
|
| 26 |
+
"content": {
|
| 27 |
+
"close_pattern": "<\\|im_end\\|>\\s*",
|
| 28 |
+
"content": "text"
|
| 29 |
+
},
|
| 30 |
+
"reasoning_content": {
|
| 31 |
+
"close_pattern": "</think>\\s*",
|
| 32 |
+
"content": "text",
|
| 33 |
+
"open_pattern": "<think>\\n?"
|
| 34 |
+
},
|
| 35 |
+
"tool_calls": {
|
| 36 |
+
"close_pattern": "</tool_call>\\s*",
|
| 37 |
+
"content": "xml-inline",
|
| 38 |
+
"content_args": {
|
| 39 |
+
"tag_pattern": "<parameter=(?P<key>[^>\\n]+)>\\n?(?P<value>.*?)\\n?</parameter>(?=\\s*(?:<parameter=|</function>\\s*\\Z|\\Z))",
|
| 40 |
+
"value_parser": {
|
| 41 |
+
"args": {
|
| 42 |
+
"strip": false
|
| 43 |
+
},
|
| 44 |
+
"name": "text"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"open_pattern": "<tool_call>\\s*<function=(?P<name>[^\\n>]+)>",
|
| 48 |
+
"repeats": true,
|
| 49 |
+
"transform": {
|
| 50 |
+
"function": {
|
| 51 |
+
"arguments": "{content}",
|
| 52 |
+
"name": "{name}"
|
| 53 |
+
},
|
| 54 |
+
"type": "function"
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"start_anchor_pattern": "<\\|im_start\\|>assistant\\n"
|
| 59 |
+
},
|
| 60 |
+
"tokenizer_class": "TokenizersBackend",
|
| 61 |
+
"video_token": "<|video|>",
|
| 62 |
+
"vision_end_token": "<|vision_end|>",
|
| 63 |
+
"vision_start_token": "<|vision_start|>"
|
| 64 |
+
}
|