Text Generation
Transformers
Safetensors
English
klm
custom_code
small-language-model
base
pretrained
hybrid
gated-deltanet
Run this model with HF Jobs
Run MinimaLabs/KLM-1.6 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/MinimaLabs/KLM-1.6. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/MinimaLabs/KLM-1.6 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/MinimaLabs/KLM-1.6. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/MinimaLabs/KLM-1.6. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use MinimaLabs/KLM-1.6 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MinimaLabs/KLM-1.6 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="MinimaLabs/KLM-1.6", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("MinimaLabs/KLM-1.6", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use MinimaLabs/KLM-1.6 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "MinimaLabs/KLM-1.6" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MinimaLabs/KLM-1.6", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/MinimaLabs/KLM-1.6
- SGLang
How to use MinimaLabs/KLM-1.6 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 "MinimaLabs/KLM-1.6" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MinimaLabs/KLM-1.6", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'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 "MinimaLabs/KLM-1.6" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MinimaLabs/KLM-1.6", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use MinimaLabs/KLM-1.6 with Docker Model Runner:
docker model run hf.co/MinimaLabs/KLM-1.6
KLM 1.6 card and code
Browse filesFiles changed (11)
- LICENSEAdded+201
- README.mdAdded+131
- charts/banner.svgAdded
- charts/benchmarks.svgAdded
- config.jsonAdded+33
- configuration_klm.pyAdded+56
- generation_config.jsonAdded+72
- modeling_klm.pyAdded+418
- special_tokens_map.jsonAdded+11
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+16
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"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.
"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 (an example is provided in the Appendix below).
"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.
"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."
"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.
2. Grant of Copyright License. Subject to the terms and conditions of this License, 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.
3. Grant of Patent License. Subject to the terms and conditions of this License, 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.
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:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(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
(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.
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.
5. 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.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. 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.
8. 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.
9. 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.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131---license: apache-2.0language: - enpipeline_tag: text-generationlibrary_name: transformerstags: - custom_code - klm - small-language-model - base - pretrained - hybrid - gated-deltanetdatasets: - nvidia/Nemotron-ClimbMix - IFM/TxT360-v2 - openbmb/UltraX-Preview - HuggingFaceTB/smollm-corpus - HuggingFaceTB/cosmopedia - mlfoundations/dclm-baseline-1.0 - nvidia/OpenMathInstruct-2 - openbmb/UltraData-Math - IFM/Math-Reasoning - allenai/dolma3_dolmino_mix-100B-1025 - IFM/Pretrain-Behaviors---

# KLM 1.6
KLM 1.6 is a 99M-parameter base language model. It has the same architecture as our KLM 1.5 and shares its first 80B tokens of training, after which it spends 100B tokens on a much longer decay instead of 20B.
## What's new
- **A five times longer decay.** The learning rate now falls to zero over 100B tokens, and the longer decay raised every benchmark.- **Fresh math.** The second half of the decay replaces two math sets with [Dolmino](https://huggingface.co/datasets/allenai/dolma3_dolmino_mix-100B-1025)'s TinyGSM-MIND and CraneMath, so the model keeps reading problems it has not seen.- **Averaged weights.** The released weights are the average of the last three checkpoints, which were saved about 1B tokens apart.
## Benchmarks
All scores are zero-shot with length-normalized accuracy.
- ARC, HellaSwag and PIQA were scored using lm-eval 0.4.12.- ArithMark-3 was scored using the official [ArithMark-3.0](https://huggingface.co/datasets/AxiomicLabs/ArithMark-3.0) script.- Peer scores are taken from the [Open SLM leaderboard](https://huggingface.co/spaces/AxiomicLabs/Open_SLM_Leaderboard) as of 2026-11-09.
On that leaderboard, KLM 1.6's Intelligence Index is 33.95 which puts it first among models under 100M, under 150M and under 250M parameters.
Each chart's axis starts at random-guess accuracy, which is 25% for most benchmarks and 50% for PIQA, so the height of a bar shows how far a model scores above chance.

| Model | Params | ARC-Easy | ARC-Challenge | HellaSwag | PIQA | ArithMark-3 ||-------|--------|----------|---------------|-----------|------|-------------|| **KLM 1.6** | 99.0M | 61.07% | 33.53% | 45.28% | 70.18% | 55.90% || [KLM 1.5](https://huggingface.co/MinimaLabs/KLM-1.5) | 99.0M | 59.68% | 32.68% | 43.74% | 68.55% | 48.20% || [GPT-X3-150M](https://huggingface.co/AxiomicLabs/GPT-X3-150M) | 149M | 59.64% | 31.31% | 46.16% | 71.33% | 50.90% || [SmolLM2-135M](https://huggingface.co/HuggingFaceTB/SmolLM2-135M) | 135M | 58.63% | 29.69% | 43.22% | 68.44% | 39.20% || [LFM-2.5-230M-Base](https://huggingface.co/LiquidAI/LFM2.5-230M-Base) | 230M | 59.72% | 34.98% | 39.29% | 63.38% | 36.60% || [void.1](https://huggingface.co/dotlabs/void.1) | 90.1M | 49.32% | 29.35% | 39.46% | 67.19% | 43.70% |
## Training
KLM 1.6 was trained on 2,048-token sequences in three stages, with 128 sequences per step in the first two and 192 in the decay.
1. **Superposition warm-up** for 70,000 steps, using [Token-Superposition Training](https://arxiv.org/abs/2605.06546). Each input position is the average of 7 consecutive tokens, and the model learns to predict the next 7 tokens as an unordered group. This lets the warm-up cover 128B tokens of ClimbMix for the compute of about 18B.2. **Stable training** on 80B tokens of next-token prediction at a constant learning rate.3. **Decay** on 100B tokens while the learning rate falls to zero along a 1−√t curve.
The weight matrices were trained with MuonEq-R at a learning rate of 0.01, and the embeddings, norms and gates with AdamW at 3e-3, in bf16. Each 2,048-token sequence packs several documents, and the model never looks across a document boundary since attention is masked there, and the recurrent state and n-gram history are reset.
The training data came from the following sources.
| Data | Sources || --- | --- || Web text | [ClimbMix](https://huggingface.co/datasets/nvidia/Nemotron-ClimbMix), [TxT360-v2](https://huggingface.co/datasets/IFM/TxT360-v2), [UltraX](https://huggingface.co/datasets/openbmb/UltraX-Preview) || Q&A | TxT360-v2 Q&A, [Dolmino](https://huggingface.co/datasets/allenai/dolma3_dolmino_mix-100B-1025) Q&A and flashcards || Textbooks | [Cosmopedia v2](https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus), [Cosmopedia](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia) WikiHow || Math | [OpenMathInstruct-2](https://huggingface.co/datasets/nvidia/OpenMathInstruct-2), [UltraData-Math](https://huggingface.co/datasets/openbmb/UltraData-Math), [Math-Reasoning](https://huggingface.co/datasets/IFM/Math-Reasoning), Dolmino TinyMATH, TinyGSM-MIND and CraneMath || Science web | Dolmino || Commonsense | [DCLM-baseline](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0) filtered for physical commonsense, ATOMIC 2020, ANLI, GLUCOSE, CREAK, SciQ, QASC || Reasoning rewrites | [Pretrain-Behaviors](https://huggingface.co/datasets/IFM/Pretrain-Behaviors) |
## Architecture
| Field | Value ||---|---|| Parameters | 98,975,308, of which 5,411,832 are the n-gram memory || Layers | 24, Gated DeltaNet-2 and attention at 3:1 || Hidden size | 512 || Gated DeltaNet-2 | 4 heads × 128 || Attention | 8 query heads, 4 KV heads, head size 64, RoPE, QK-norm, output gate || Residuals | [Block Attention Residuals](https://arxiv.org/abs/2603.15031) || N-gram memory | 125,000 bigrams and 38,000 trigrams, each with its own learned vector || Feed-forward | SwiGLU, hidden size 1,408 || Context length | 2,048 tokens || Vocabulary | 4,100 tokens, tied embeddings |
## Intended use
KLM 1.6 is a base model. It continues text but has not been trained to follow instructions or chat, so it is meant to be fine-tuned for your own use case. The tokenizer already has `<|im_start|>`, `<|im_end|>`, `<think>` and `</think>` as single tokens, so they are ready to use in chat and reasoning fine-tunes.
## Usage
The model code is plain PyTorch, so KLM 1.6 runs on a CPU as well as on any GPU without extra packages beyond Transformers.
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "MinimaLabs/KLM-1.6"device = "cuda" if torch.cuda.is_available() else "cpu"tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).to(device)
inputs = tokenizer("The three primary colors are", return_tensors="pt").to(device)outputs = model.generate(**inputs, max_new_tokens=40, do_sample=True, temperature=0.7, top_p=0.9)print(tokenizer.decode(outputs[0], skip_special_tokens=True))```
## Limitations
- The model's knowledge is thin, and the facts it states are often wrong.- It only works in English and has a 2,048-token context window.- It has no safety alignment, so add your own filtering before putting it in front of users.
## License
KLM 1.6 is released under the Apache-2.0 license, which you can find in [LICENSE](LICENSE).123456789101112131415161718192021222324252627282930313233{ "architectures": [ "KLMForCausalLM" ], "attention_every": 4, "auto_map": { "AutoConfig": "configuration_klm.KLMConfig", "AutoModelForCausalLM": "modeling_klm.KLMForCausalLM" }, "bos_token_id": 1, "decay_floor": -20.0, "dtype": "float32", "eos_token_id": 2, "gdn_head_dim": 128, "gdn_heads": 4, "gdn_norm_eps": 1e-05, "hidden_size": 512, "intermediate_size": 1408, "max_position_embeddings": 2048, "model_type": "klm", "n_bigrams": 125000, "n_trigrams": 38000, "ngram_dim": 32, "num_attention_heads": 8, "num_hidden_layers": 24, "num_key_value_heads": 4, "pad_token_id": 0, "rms_norm_eps": 1e-06, "rope_theta": 10000.0, "tie_word_embeddings": true, "transformers_version": "5.20.2", "vocab_size": 4160}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""KLMConfig: Transformers config for KLM 1.6."""from __future__ import annotations
from transformers import PretrainedConfig
class KLMConfig(PretrainedConfig): model_type = "klm"
def __init__( self, vocab_size: int = 4160, hidden_size: int = 512, num_hidden_layers: int = 24, attention_every: int = 4, gdn_heads: int = 4, gdn_head_dim: int = 128, num_attention_heads: int = 8, num_key_value_heads: int = 4, intermediate_size: int = 1408, max_position_embeddings: int = 2048, rope_theta: float = 10000.0, n_bigrams: int = 125000, n_trigrams: int = 38000, ngram_dim: int = 32, rms_norm_eps: float = 1e-6, gdn_norm_eps: float = 1e-5, decay_floor: float = -20.0, bos_token_id: int = 1, eos_token_id: int = 2, pad_token_id: int = 0, tie_word_embeddings: bool = True, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.attention_every = attention_every self.gdn_heads = gdn_heads self.gdn_head_dim = gdn_head_dim self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.intermediate_size = intermediate_size self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.n_bigrams = n_bigrams self.n_trigrams = n_trigrams self.ngram_dim = ngram_dim self.rms_norm_eps = rms_norm_eps self.gdn_norm_eps = gdn_norm_eps self.decay_floor = decay_floor super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
def is_attention(self, layer: int) -> bool: return layer % self.attention_every == self.attention_every - 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "bos_token_id": 1, "eos_token_id": 2, "pad_token_id": 0, "do_sample": true, "temperature": 0.7, "top_p": 0.9, "max_new_tokens": 200, "use_cache": true, "suppress_tokens": [ 4100, 4101, 4102, 4103, 4104, 4105, 4106, 4107, 4108, 4109, 4110, 4111, 4112, 4113, 4114, 4115, 4116, 4117, 4118, 4119, 4120, 4121, 4122, 4123, 4124, 4125, 4126, 4127, 4128, 4129, 4130, 4131, 4132, 4133, 4134, 4135, 4136, 4137, 4138, 4139, 4140, 4141, 4142, 4143, 4144, 4145, 4146, 4147, 4148, 4149, 4150, 4151, 4152, 4153, 4154, 4155, 4156, 4157, 4158, 4159 ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418"""KLM 1.6 for Transformers, in plain PyTorch, so it runs on CPU or any GPU without custom kernels.
Parameter names match the training code, and export_hf.py checks the logits against it beforewriting the weights. A sequence may hold several documents separated by <eos>: after each <eos>the attention mask, the Gated DeltaNet-2 state, its short convolutions and the n-gram history allrestart, as they did in training.
generate() decodes with a KLMCache, which keeps the attention layers' keys and values, theGated DeltaNet-2 recurrent states and convolution windows, and the last two tokens for then-gram lookup, so every new token costs one step. Left padding (batched generation) starts a newdocument at each row's first real token, so the pads are never seen; scoring also accepts rightpadding."""from __future__ import annotations
import math
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import PreTrainedModelfrom transformers.generation import GenerationMixinfrom transformers.modeling_outputs import CausalLMOutputWithPast
try: from .configuration_klm import KLMConfig # remote code: sibling module in the cache packageexcept ImportError: from configuration_klm import KLMConfig # direct import from the repo folder
CONV = 4 # short-convolution width
class KLMCache: """Decoding state of a batch. `layers[i]` is an attention layer's (keys, values) or a Gated DeltaNet-2 layer's (recurrent state, (q, k, v) convolution windows)."""
def __init__(self, n_layers: int): self.layers = [None] * n_layers self.length = 0 self.history = None # (B, <=2) last tokens, for the n-gram lookup self.docs = None # (B, length) document id of every cached position self.pos = None # (B,) position of the last token within its document
def get_seq_length(self, layer_idx: int = 0) -> int: return self.length
def reorder_cache(self, beam_idx: torch.Tensor) -> None: def pick(x): if isinstance(x, tuple): return tuple(pick(t) for t in x) return x.index_select(0, beam_idx.to(x.device)) self.layers = [pick(layer) for layer in self.layers] self.history, self.docs, self.pos = pick((self.history, self.docs, self.pos))
class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x): return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps)
def segments(tokens, eos_id, cache, real=None): """Document-start flags, document ids and in-document positions of new tokens (B, T), continuing the cached sequence. `real` (B, T) marks non-pad tokens of a fresh sequence: a row's first real token after left padding starts a document.""" batch, seq_len = tokens.shape starts = torch.zeros_like(tokens, dtype=torch.bool) starts[:, 1:] = tokens[:, :-1] == eos_id if real is not None: starts[:, 1:] |= real[:, 1:] & ~real[:, :-1] idx = torch.arange(seq_len, device=tokens.device).expand(batch, seq_len) if cache is None or cache.length == 0: starts[:, 0] = True docs = starts.cumsum(1) return starts, docs, idx - torch.where(starts, idx, 0).cummax(1).values starts[:, 0] = cache.history[:, -1] == eos_id docs = cache.docs[:, -1:] + starts.cumsum(1) first = torch.where(starts, idx, -1).cummax(1).values pos = torch.where(first < 0, cache.pos[:, None] + 1 + idx, idx - first) return starts, docs, pos
def lookup(keys, queries): """Row of each query in a sorted key bank: p + 1 where keys[p] == query, else 0 (unknown).""" queries = queries.to(keys.dtype) p = torch.searchsorted(keys, queries).clamp_(max=keys.numel() - 1) return torch.where(keys[p] == queries, p + 1, 0)
class NgramMemory(nn.Module): """Learned rows for the most frequent bigrams and trigrams, found by exact key lookup. Missing history (row start, or right after <eos>) is token 0."""
def __init__(self, cfg: KLMConfig): super().__init__() self.vocab_size = cfg.vocab_size self.register_buffer("bigram_keys", torch.zeros(cfg.n_bigrams, dtype=torch.int32)) self.register_buffer("trigram_keys", torch.zeros(cfg.n_trigrams, dtype=torch.int64)) self.bigram = nn.Embedding(cfg.n_bigrams + 1, cfg.ngram_dim) self.trigram = nn.Embedding(cfg.n_trigrams + 1, cfg.ngram_dim) self.bigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False) self.trigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False)
def forward(self, tokens, history, eos_id): seq_len = tokens.shape[1] t = tokens.long() if history is None else torch.cat([history, tokens], 1).long() n, v = t.shape[1], self.vocab_size prev1 = F.pad(t, (1, 0))[:, :n] prev2 = F.pad(t, (2, 0))[:, :n] reset = prev1 == eos_id prev1 = prev1.masked_fill(reset, 0) prev2 = prev2.masked_fill(reset | (prev2 == eos_id), 0) bigram = (prev1 * v + t)[:, n - seq_len:] trigram = ((prev2 * v + prev1) * v + t)[:, n - seq_len:] return (self.bigram_proj(self.bigram(lookup(self.bigram_keys, bigram))) + self.trigram_proj(self.trigram(lookup(self.trigram_keys, trigram))))
def rope(x, positions, theta): """Half-rotation RoPE on (B, H, T, D) at absolute positions (T,).""" dim = x.shape[-1] freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device).float() / dim)) angles = positions.float()[:, None] * freqs cos, sin = angles.cos().to(x.dtype), angles.sin().to(x.dtype) x1, x2 = x.chunk(2, dim=-1) return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
class Attention(nn.Module): """GQA with per-head QK-RMSNorm, RoPE, a sigmoid output gate, and a value residual that mixes each layer's values with the first attention layer's."""
def __init__(self, cfg: KLMConfig): super().__init__() dim = cfg.hidden_size self.n_heads, self.n_kv_heads = cfg.num_attention_heads, cfg.num_key_value_heads self.head_dim = dim // self.n_heads self.theta = cfg.rope_theta self.q_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False) self.gate_proj = nn.Linear(dim, dim, bias=False) self.o_proj = nn.Linear(dim, dim, bias=False) self.q_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps) self.k_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps) self.value_mix = nn.Parameter(torch.tensor([0.5, 0.5]))
def forward(self, x, v_first, positions, mask, cached): batch, seq_len, dim = x.shape q = self.q_proj(x).view(batch, seq_len, self.n_heads, self.head_dim) k = self.k_proj(x).view(batch, seq_len, self.n_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, seq_len, self.n_kv_heads, self.head_dim) if v_first is None: v_first = v mix = self.value_mix.float() values = (mix[0] * v.float() + mix[1] * v_first.float()).to(x.dtype).transpose(1, 2) q = rope(self.q_norm(q.float()).transpose(1, 2), positions, self.theta).to(x.dtype) keys = rope(self.k_norm(k.float()).transpose(1, 2), positions, self.theta).to(x.dtype) if cached is not None: keys, values = torch.cat([cached[0], keys], 2), torch.cat([cached[1], values], 2) out = F.scaled_dot_product_attention(q, keys, values, attn_mask=mask, enable_gqa=True) out = out.transpose(1, 2).reshape(batch, seq_len, dim) return self.o_proj(out * torch.sigmoid(self.gate_proj(x))), v_first, (keys, values)
def short_conv(weight, x, taps_valid, window): """Causal depthwise convolution plus SiLU that never reaches back past a document start. x (B, T, C); taps_valid (B, T, CONV) zeroes taps before the document start; window holds the previous CONV - 1 inputs (B, CONV - 1, C) or is None.""" batch, seq_len, channels = x.shape if window is None: window = x.new_zeros(batch, CONV - 1, channels) ext = torch.cat([window, x], 1) windows = ext.unfold(1, CONV, 1) # (B, T, C, CONV), oldest input first out = (windows * weight.view(channels, CONV).to(x.dtype) * taps_valid.unsqueeze(2)).sum(-1) return F.silu(out), ext[:, -(CONV - 1):]
def l2norm(x): return x * torch.rsqrt((x * x).sum(-1, keepdim=True) + 1e-6)
def recurrence(q, k, v, g, b, w, starts, state): """Gated DeltaNet-2 step by step in fp32: S <- (I - k (b*k)^T) diag(exp g) S + k (w*v)^T and o = q^T S / sqrt(K), with S cleared at every document start. Inputs are (B, T, H, K).""" batch, seq_len, heads, key_dim = k.shape q = q * key_dim**-0.5 if state is None: state = q.new_zeros(batch, heads, key_dim, v.shape[-1]) keep = (~starts).float() out = [] with torch.autocast(q.device.type, enabled=False): for t in range(seq_len): state = state * (keep[:, t, None, None, None] * g[:, t].exp().unsqueeze(-1)) erase = torch.einsum("bhk,bhkv->bhv", b[:, t] * k[:, t], state) state = state + k[:, t].unsqueeze(-1) * (w[:, t] * v[:, t] - erase).unsqueeze(-2) out.append(torch.einsum("bhk,bhkv->bhv", q[:, t], state)) return torch.stack(out, 1), state
class GatedDeltaNet2(nn.Module): """Gated DeltaNet-2 in flash-linear-attention's parameter layout: q/k/v short convolutions, channel-wise erase (b) and write (w) gates, a low-rank channel-wise decay with A_log and dt_bias, and a sigmoid-gated RMSNorm on the output."""
def __init__(self, cfg: KLMConfig): super().__init__() dim, self.heads, self.head_dim = cfg.hidden_size, cfg.gdn_heads, cfg.gdn_head_dim inner = self.heads * self.head_dim self.decay_floor = cfg.decay_floor self.q_proj = nn.Linear(dim, inner, bias=False) self.k_proj = nn.Linear(dim, inner, bias=False) self.v_proj = nn.Linear(dim, inner, bias=False) self.q_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.k_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.v_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.f_proj = nn.Sequential(nn.Linear(dim, self.head_dim, bias=False), nn.Linear(self.head_dim, inner, bias=False)) self.b_proj = nn.Linear(dim, inner, bias=False) self.w_proj = nn.Linear(dim, inner, bias=False) self.A_log = nn.Parameter(torch.zeros(self.heads)) self.dt_bias = nn.Parameter(torch.zeros(inner)) self.g_proj = nn.Sequential(nn.Linear(dim, self.head_dim, bias=False), nn.Linear(self.head_dim, inner, bias=True)) self.o_norm = RMSNorm(self.head_dim, cfg.gdn_norm_eps) self.o_proj = nn.Linear(inner, dim, bias=False)
def log_decay(self, x): """-exp(A_log) * softplus(f(x) + dt_bias), combined in log space in fp32 and floored.""" s = self.f_proj(x).float().unflatten(-1, (self.heads, self.head_dim)) + self.dt_bias.float().view( self.heads, self.head_dim) log_act = torch.where(s < -20, s, F.softplus(s.clamp_min(-20)).log()) log_mag = self.A_log.float().unsqueeze(-1) + log_act ceiling = math.log(-self.decay_floor) return torch.where(log_mag >= ceiling, self.decay_floor, -log_mag.clamp(max=ceiling).exp())
def forward(self, x, starts, taps_valid, cached): batch, seq_len, _ = x.shape state, windows = cached if cached is not None else (None, (None, None, None)) q, wq = short_conv(self.q_conv1d.weight, self.q_proj(x), taps_valid, windows[0]) k, wk = short_conv(self.k_conv1d.weight, self.k_proj(x), taps_valid, windows[1]) v, wv = short_conv(self.v_conv1d.weight, self.v_proj(x), taps_valid, windows[2]) heads = lambda t: t.float().view(batch, seq_len, self.heads, self.head_dim) # noqa: E731 o, state = recurrence(l2norm(heads(q)), l2norm(heads(k)), heads(v), self.log_decay(x), torch.sigmoid(heads(self.b_proj(x))), torch.sigmoid(heads(self.w_proj(x))), starts, state) gate = self.g_proj(x).view(batch, seq_len, self.heads, self.head_dim) o = self.o_norm(o.to(x.dtype)) * torch.sigmoid(gate) return self.o_proj(o.reshape(batch, seq_len, -1)), (state, (wq, wk, wv))
class SwiGLU(nn.Module): def __init__(self, dim: int, hidden: int): super().__init__() self.gate = nn.Linear(dim, hidden, bias=False) self.up = nn.Linear(dim, hidden, bias=False) self.down = nn.Linear(hidden, dim, bias=False)
def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x))
class Block(nn.Module): def __init__(self, cfg: KLMConfig, index: int): super().__init__() self.is_attention = cfg.is_attention(index) self.mixer_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) self.mixer = Attention(cfg) if self.is_attention else GatedDeltaNet2(cfg) self.ffn_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) self.ffn = SwiGLU(cfg.hidden_size, cfg.intermediate_size)
class AttnResSources: """Block Attention Residual sources in preallocated buffers. Each source is RMS-normalized once, when it is added, so a consumer costs one matmul and one weighted sum."""
def __init__(self, first, capacity: int, eps: float): batch, seq_len, dim = first.shape self.values = first.new_empty(batch, seq_len, capacity, dim) self.normed = torch.empty(batch, seq_len, capacity, dim, dtype=torch.float32, device=first.device) self.n, self.eps = 0, eps self.add(first)
def _norm(self, v): return F.rms_norm(v.float(), (v.shape[-1],), eps=self.eps)
def add(self, v): self.values[:, :, self.n] = v self.normed[:, :, self.n] = self._norm(v) self.n += 1
def mix(self, query, partial=None): """Softmax mix of the sources weighted by query . RMSNorm(source); `partial` (the current layer's mixer output, seen only by its FFN) joins as one more source.""" n = self.n with torch.autocast(query.device.type, enabled=False): logits = self.normed[:, :, :n] @ query if partial is not None: logits = torch.cat([logits, (self._norm(partial) @ query).unsqueeze(-1)], -1) weights = logits.softmax(-1) out = (weights[..., :n, None].to(self.values.dtype) * self.values[:, :, :n]).sum(-2) if partial is not None: out = out + weights[..., n:].to(partial.dtype) * partial return out
class KLM(nn.Module): def __init__(self, cfg: KLMConfig): super().__init__() self.cfg = cfg self.embed = nn.Embedding(cfg.vocab_size, cfg.hidden_size) self.memory = NgramMemory(cfg) self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.num_hidden_layers)]) n_consumers = 2 * cfg.num_hidden_layers + 1 # every mixer and FFN, plus the readout self.attn_res_query = nn.Parameter(torch.zeros(n_consumers, cfg.hidden_size)) self.attn_res_norm = nn.Parameter(torch.ones(n_consumers, cfg.hidden_size)) self.norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
def forward(self, tokens, cache: KLMCache | None = None, real=None): cfg, eps = self.cfg, self.cfg.rms_norm_eps seq_len = tokens.shape[1] fresh = cache is None or cache.length == 0 starts, docs, pos = segments(tokens, cfg.eos_token_id, cache, real if fresh else None) offset = cache.length if cache is not None else 0 positions = torch.arange(offset, offset + seq_len, device=tokens.device) all_docs = docs if offset == 0 else torch.cat([cache.docs, docs], 1) causal = torch.arange(offset + seq_len, device=tokens.device)[None, :] <= positions[:, None] mask = ((docs[:, :, None] == all_docs[:, None, :]) & causal).unsqueeze(1) history = cache.history if offset else None lags = torch.arange(CONV - 1, -1, -1, device=tokens.device) taps_valid = (pos[..., None] >= lags).to(self.embed.weight.dtype)
queries = (self.attn_res_query * self.attn_res_norm).float() sources = AttnResSources(self.embed(tokens), cfg.num_hidden_layers + 2, eps) sources.add(self.memory(tokens, history, cfg.eos_token_id)) v_first = None for i, block in enumerate(self.blocks): cached = cache.layers[i] if cache is not None else None h = block.mixer_norm(sources.mix(queries[2 * i])) if block.is_attention: out, v_first, new = block.mixer(h, v_first, positions, mask, cached) else: out, new = block.mixer(h, starts, taps_valid, cached) if cache is not None: cache.layers[i] = new ffn = block.ffn(block.ffn_norm(sources.mix(queries[2 * i + 1], out))) sources.add(out + ffn) x = self.norm(sources.mix(queries[-1]))
if cache is not None: cache.history = (tokens if history is None else torch.cat([history, tokens], 1))[:, -2:] cache.docs, cache.pos = all_docs, pos[:, -1] cache.length = offset + seq_len return F.linear(x, self.embed.weight.to(x.dtype))
class KLMForCausalLM(PreTrainedModel, GenerationMixin): config_class = KLMConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules = ["Block"] _is_stateful = True # the recurrent state cannot be cropped, so no assisted decoding
@classmethod def _supports_default_dynamic_cache(cls) -> bool: return False # generate() must not build a DynamicCache; forward returns a KLMCache
def __init__(self, config: KLMConfig): super().__init__(config) self.model = KLM(config) self.post_init()
def _init_weights(self, module): pass # every weight comes from the checkpoint
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed = value
def get_output_embeddings(self) -> nn.Embedding: return self.model.embed # tied: the output layer reads embed.weight
def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=None, labels=None, return_dict=True, **kwargs) -> CausalLMOutputWithPast: if past_key_values is not None and not isinstance(past_key_values, KLMCache): raise TypeError("past_key_values must be the KLMCache this model returned") cache = past_key_values if cache is None and use_cache: cache = KLMCache(self.config.num_hidden_layers) real = None if attention_mask is not None: mask = attention_mask.bool() left = (mask[:, 1:] >= mask[:, :-1]).all() if cache is not None and not left: raise ValueError("generation supports left padding only") if not left and not (mask[:, 1:] <= mask[:, :-1]).all(): raise ValueError("only left or right padding is supported") if left: real = mask[:, -input_ids.shape[1]:] logits = self.model(input_ids, cache, real) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1).float(), labels[:, 1:].flatten(), ignore_index=-100) return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=cache)
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, **kwargs): if past_key_values is not None and past_key_values.length: input_ids = input_ids[:, past_key_values.length:] return {"input_ids": input_ids, "past_key_values": past_key_values, "attention_mask": attention_mask, "use_cache": use_cache}1234567891011{ "pad_token": "<pad>", "bos_token": "<bos>", "eos_token": "<eos>", "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<think>", "</think>" ]}12345678910111213141516{ "tokenizer_class": "PreTrainedTokenizerFast", "model_max_length": 2048, "pad_token": "<pad>", "bos_token": "<bos>", "eos_token": "<eos>", "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<think>", "</think>" ], "add_bos_token": false, "add_eos_token": false, "clean_up_tokenization_spaces": false}LICENSEAdded+201
README.mdAdded+131
charts/banner.svgAdded
charts/benchmarks.svgAdded
config.jsonAdded+33
configuration_klm.pyAdded+56
generation_config.jsonAdded+72
modeling_klm.pyAdded+418
special_tokens_map.jsonAdded+11
tokenizer.jsonAdded
tokenizer_config.jsonAdded+16