flash-linear-attention-benchmark
https://github.com/aniketm3/flash-linear-attention-benchmark
Science Score: 54.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
✓CITATION.cff file
Found CITATION.cff file -
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
○DOI references
-
✓Academic publication links
Links to: arxiv.org -
○Academic email domains
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (11.2%) to scientific vocabulary
Repository
Basic Info
- Host: GitHub
- Owner: aniketm3
- License: mit
- Language: Python
- Default Branch: main
- Size: 4.22 MB
Statistics
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
- Releases: 0
Metadata Files
README.md
This repo aims at providing a collection of efficient Triton-based implementations for state-of-the-art linear attention models. Any pull requests are welcome!
News
- $\texttt{[2025-04]}$: 🎉 Add DeltaProduct implementation to
fla(paper). - $\texttt{[2025-04]}$: 🎉 Add FoX implementation to
fla(paper). - $\texttt{[2025-03]}$: We have changed the default
initializer_rangeto the magic 🐳 0.006, leading to great improvements across all models. (Caveat: This std init range may be less robust when using a larger learning rate compared to 0.02. It is recommended to tune both initializer_range and learning rate together during actual training.) - $\texttt{[2025-02]}$: 🐳 Add NSA implementations to
fla. See kernels here. - $\texttt{[2025-01]}$: 🔥 We are migrating to
torchtitan-based training framework. Check out the flame repo for more details. - $\texttt{[2025-01]}$: 🎉 Add RWKV7 implementations (both kernels and models) to
fla. - $\texttt{[2024-12]}$: Integrated
flash-bidirectional-attentiontofla-org(repo) - $\texttt{[2024-12]}$: 🎉 Add Gated DeltaNet implementation to
fla(paper). - $\texttt{[2024-12]}$: 🚀
flanow officially supports kernels with variable-length inputs. - $\texttt{[2024-11]}$: The inputs are now switched from head-first to seq-first format.
- $\texttt{[2024-11]}$: 💥
flanow provides a flexible way for training hybrid models. - $\texttt{[2024-10]}$: 🔥 Announcing
flame, a minimal and scalable framework for trainingflamodels. Check out the details here. - $\texttt{[2024-09]}$:
flanow includes a fused linear and cross-entropy layer, significantly reducing memory usage during training. - $\texttt{[2024-09]}$: 🎉 Add GSA implementation to
fla(paper). - $\texttt{[2024-05]}$: 🎉 Add DeltaNet implementation to
fla(paper). - $\texttt{[2024-05]}$: 💥
flav0.1: a variety of subquadratic kernels/layers/models integrated (RetNet/GLA/Mamba/HGRN/HGRN2/RWKV6, etc., see Models). - $\texttt{[2023-12]}$: 💥 Launched
fla, offering a collection of implementations for state-of-the-art linear attention models.
Models
Roughly sorted according to the timeline supported in fla. The recommended training mode is chunk when available.
| Year | Venue | Model | Paper | Code | fla impl |
| :--- | :------ | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: |
| 2023 | | RetNet | Retentive network: a successor to transformer for large language models | official | code |
| 2024 | ICML | GLA | Gated Linear Attention Transformers with Hardware-Efficient Training | official | code |
| 2024 | ICML | Based | Simple linear attention language models balance the recall-throughput tradeoff | official | code |
| 2024 | ACL | Rebased | Linear Transformers with Learnable Kernel Functions are Better In-Context Models | official | code |
| 2024 | NeurIPS | DeltaNet | Parallelizing Linear Transformers with Delta Rule over Sequence Length | official | code |
| 2022 | ACL | ABC | ABC: Attention with Bounded-memory Control | | code |
| 2023 | NeurIPS | HGRN | Hierarchically Gated Recurrent Neural Network for Sequence Modeling | official | code |
| 2024 | COLM | HGRN2 | HGRN2: Gated Linear RNNs with State Expansion | official | code |
| 2024 | COLM | RWKV6 | Eagle and Finch: RWKV with Matrix-Valued States and Dynamic Recurrence | official | code |
| 2024 | | LightNet | You Only Scan Once: Efficient Multi-dimension Sequential Modeling with LightNet | official | code |
| 2025 | ICLR | Samba | Samba: Simple Hybrid State Space Models for Efficient Unlimited Context Language Modeling | official | code |
| 2024 | ICML | Mamba2 | Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality | official | code |
| 2024 | NeurIPS | GSA | Gated Slot Attention for Efficient Linear-Time Sequence Modeling | official | code |
| 2025 | ICLR | Gated DeltaNet | Gated Delta Networks: Improving Mamba2 with Delta Rule | official | code |
| 2025 | | RWKV7 | RWKV-7 "Goose" with Expressive Dynamic State Evolution | official | code |
| 2025 | | NSA | Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention | | code |
| 2025 | | FoX | Forgetting Transformer: Softmax Attention with a Forget Gate | official | code |
| 2025 | | DeltaProduct | DeltaProduct: Improving State-Tracking in Linear RNNs via Householder Products | | code |
Installation
The following requirements should be satisfied - PyTorch >= 2.5 - Triton >=3.0 (or nightly version, see FAQs) - einops - transformers >=4.45.0 - datasets >=3.3.0 - causal-conv1d >=1.4.0
You can install fla with pip:
sh
pip install --no-use-pep517 flash-linear-attention
As fla is actively developed now, for the latest features and updates, an alternative way is to install the package from source
```sh
uninstall fla first to ensure a successful upgrade
pip uninstall flash-linear-attention && pip install -U --no-use-pep517 git+https://github.com/fla-org/flash-linear-attention
or manage `fla` with submodules
sh
git submodule add https://github.com/fla-org/flash-linear-attention.git 3rdparty/flash-linear-attention
ln -s 3rdparty/flash-linear-attention/fla fla
```
If you have installed triton-nightly and torch pre version, please use the following command:
sh
pip install einops ninja datasets transformers numpy
pip uninstall flash-linear-attention && pip install -U --no-use-pep517 git+https://github.com/fla-org/flash-linear-attention --no-deps
Usage
Token Mixing
We provide token mixing'' linear attention layers in `fla.layers` for you to use.
You can replace the standard multihead attention layer in your model with other linear attention layers.
Example usage is as follows:
`py
import torch from fla.layers import MultiScaleRetention batchsize, numheads, seqlen, hiddensize = 32, 4, 2048, 1024 device, dtype = 'cuda:0', torch.bfloat16 retnet = MultiScaleRetention(hiddensize=hiddensize, numheads=numheads).to(device=device, dtype=dtype) retnet MultiScaleRetention( (qproj): Linear(infeatures=1024, outfeatures=1024, bias=False) (kproj): Linear(infeatures=1024, outfeatures=1024, bias=False) (vproj): Linear(infeatures=1024, outfeatures=2048, bias=False) (gproj): Linear(infeatures=1024, outfeatures=2048, bias=False) (oproj): Linear(infeatures=2048, outfeatures=1024, bias=False) (gnormswishgate): FusedRMSNormGated(512, eps=1e-05, activation=swish) (rotary): RotaryEmbedding(dim=256, base=10000.0, interleaved=False, posidxinfp32=True) ) x = torch.randn(batchsize, seqlen, hiddensize).to(device=device, dtype=dtype) y, *_ = retnet(x) y.shape torch.Size([32, 2048, 1024]) ```
We provide the implementations of models that are compatible with 🤗 Transformers library.
Here's an example of how to initialize a GLA model from the default configs in fla:
```py
from fla.models import GLAConfig from transformers import AutoModelForCausalLM config = GLAConfig() config GLAConfig { "attn": null, "attnmode": "chunk", "bostokenid": 1, "clampmin": null, "convsize": 4, "elementwiseaffine": true, "eostokenid": 2, "expandk": 0.5, "expandv": 1, "featuremap": null, "fusecrossentropy": true, "fusenorm": true, "fuseswiglu": true, "hiddenact": "swish", "hiddenratio": 4, "hiddensize": 2048, "initializerrange": 0.006, "intermediatesize": null, "maxpositionembeddings": 2048, "modeltype": "gla", "normeps": 1e-06, "numheads": 4, "numhiddenlayers": 24, "numkvheads": null, "tiewordembeddings": false, "transformersversion": "4.50.1", "usecache": true, "usegk": true, "usegv": false, "useoutputgate": true, "useshortconv": false, "vocabsize": 32000 }
AutoModelForCausalLM.fromconfig(config) GLAForCausalLM( (model): GLAModel( (embeddings): Embedding(32000, 2048) (layers): ModuleList( (0-23): 24 x GLABlock( (attnnorm): RMSNorm(2048, eps=1e-06) (attn): GatedLinearAttention( (qproj): Linear(infeatures=2048, outfeatures=1024, bias=False) (kproj): Linear(infeatures=2048, outfeatures=1024, bias=False) (vproj): Linear(infeatures=2048, outfeatures=2048, bias=False) (gproj): Linear(infeatures=2048, outfeatures=2048, bias=False) (gkproj): Sequential( (0): Linear(infeatures=2048, outfeatures=16, bias=False) (1): Linear(infeatures=16, outfeatures=1024, bias=True) ) (oproj): Linear(infeatures=2048, outfeatures=2048, bias=False) (gnormswishgate): FusedRMSNormGated(512, eps=1e-06, activation=swish) ) (mlpnorm): RMSNorm(2048, eps=1e-06) (mlp): GatedMLP( (gateproj): Linear(infeatures=2048, outfeatures=5632, bias=False) (upproj): Linear(infeatures=2048, outfeatures=5632, bias=False) (downproj): Linear(infeatures=5632, outfeatures=2048, bias=False) (swiglulinear): SwiGLULinear() ) ) ) (norm): RMSNorm(2048, eps=1e-06) ) (lmhead): Linear(infeatures=2048, out_features=32000, bias=False) ) ```
Fused Modules
We offer a collection of fused modules in fla.modules to facilitate faster training:
Rotary Embedding: rotary positional embeddings as adopted by the Llama architecture, a.k.a., Transformer++.Norm Layers:RMSNorm,LayerNormandGroupNormRMSNormLinear,LayerNormLinearandGroupNormLinearto reduce memory usage of intermediate tensors for improved memory efficiency.
Norm Layers with Gating: combine norm layers with element-wise gating, as used by RetNet/GLA.Cross Entropy: faster Triton implementation of cross entropy loss.Linear Cross Entropy: fused linear layer and cross entropy loss to avoid the materialization of large logits tensors. Also refer to implementations by mgmalek and Liger-Kernel.Linear KL Divergence: fused linear layer and KL divergence loss in a similar vein as CE loss.
Generation
Upon successfully pretraining a model, it becomes accessible for generating text using the 🤗 text generation APIs. In the following, we give a generation example: ```py
import fla from transformers import AutoModelForCausalLM, AutoTokenizer name = 'fla-hub/gla-1.3B-100B' tokenizer = AutoTokenizer.frompretrained(name) model = AutoModelForCausalLM.frompretrained(name).cuda() inputprompt = "Power goes with permanence. Impermanence is impotence. And rotation is castration." inputids = tokenizer(inputprompt, returntensors="pt").inputids.cuda() outputs = model.generate(inputids, maxlength=64) tokenizer.batchdecode(outputs, skipspecialtokens=True)[0] ```
We also provide a simple script here for benchmarking the generation speed. Simply run it by: ```sh $ python -m benchmarks.benchmarkgeneration \ --path 'fla-hub/gla-1.3B-100B' \ --repetitionpenalty 2. \ --prompt="Hello everyone, I'm Songlin Yang"
Prompt: Hello everyone, I'm Songlin Yang Generated: Hello everyone, I'm Songlin Yang. I am a 20 year old girl from China who is currently studying in the United States of America for my Master degree and also working as an English teacher at school here on campus since last summer (1st semester). My main goal to be able do well with this course so that we can have
Prompt length: 10, generation length: 64 Total prompt processing + decoding time: 4593ms ```
All of the pretrained models currently available can be found in fla-hub.
```py
from huggingfacehub import listmodels for model in list_models(author='fla-hub'): print(model.id) ```
Hybrid Models
fla provides a flexible method to incorporate standard attention layers into existing linear attention models.
This is easily achieved by specifying the attn argument in the model configuration.
For example, to create a 2-layer Samba model with interleaved Mamba and local attention layers, using a sliding window size of 2048:
```py
from fla.models import SambaConfig from transformers import AutoModelForCausalLM config = SambaConfig(numhiddenlayers=2) config.attn = { 'layers': [1], 'numheads': 18, 'numkvheads': 18, 'qkvbias': False, 'ropetheta': 10000., 'windowsize': 2048 } config SambaConfig { "attn": { "layers": [ 1 ], "numheads": 18, "numkvheads": 18, "qkvbias": false, "ropetheta": 10000.0, "windowsize": 2048 }, "bostokenid": 1, "convkernel": 4, "eostokenid": 2, "expand": 2, "fusecrossentropy": true, "fusenorm": true, "fuseswiglu": true, "hiddenact": "swish", "hiddenratio": 4, "hiddensize": 2304, "initializerrange": 0.02, "intermediatesize": 4608, "maxpositionembeddings": 2048, "modeltype": "samba", "normeps": 1e-05, "numhiddenlayers": 2, "padtokenid": 0, "rescaleprenormresidual": false, "residualinfp32": false, "statesize": 16, "tiewordembeddings": false, "timestepfloor": 0.0001, "timestepinitscheme": "random", "timestepmax": 0.1, "timestepmin": 0.001, "timesteprank": 144, "timestepscale": 1.0, "transformersversion": "4.50.1", "usebias": false, "usecache": true, "useconvbias": true, "vocabsize": 32000 }
AutoModelForCausalLM.fromconfig(config) SambaForCausalLM( (backbone): SambaModel( (embeddings): Embedding(32000, 2304) (layers): ModuleList( (0): SambaBlock( (mixernorm): RMSNorm(2304, eps=1e-05) (mixer): Mamba( (conv1d): Conv1d(4608, 4608, kernelsize=(4,), stride=(1,), padding=(3,), groups=4608) (inproj): Linear(infeatures=2304, outfeatures=9216, bias=False) (xproj): Linear(infeatures=4608, outfeatures=176, bias=False) (dtproj): Linear(infeatures=144, outfeatures=4608, bias=True) (outproj): Linear(infeatures=4608, outfeatures=2304, bias=False) ) (mlpnorm): RMSNorm(2304, eps=1e-05) (mlp): GatedMLP( (gateproj): Linear(infeatures=2304, outfeatures=6144, bias=False) (upproj): Linear(infeatures=2304, outfeatures=6144, bias=False) (downproj): Linear(infeatures=6144, outfeatures=2304, bias=False) (swiglulinear): SwiGLULinear() ) ) (1): SambaBlock( (mixernorm): RMSNorm(2304, eps=1e-05) (mixer): Attention( (qproj): Linear(infeatures=2304, outfeatures=2304, bias=False) (kproj): Linear(infeatures=2304, outfeatures=2304, bias=False) (vproj): Linear(infeatures=2304, outfeatures=2304, bias=False) (oproj): Linear(infeatures=2304, outfeatures=2304, bias=False) (rotary): RotaryEmbedding(dim=128, base=10000.0, interleaved=False, posidxinfp32=True) ) (mlpnorm): RMSNorm(2304, eps=1e-05) (mlp): GatedMLP( (gateproj): Linear(infeatures=2304, outfeatures=6144, bias=False) (upproj): Linear(infeatures=2304, outfeatures=6144, bias=False) (downproj): Linear(infeatures=6144, outfeatures=2304, bias=False) (swiglulinear): SwiGLULinear() ) ) ) (normf): RMSNorm(2304, eps=1e-05) ) (lmhead): Linear(infeatures=2304, out_features=32000, bias=False) ) ```
During inference, you DO NOT need to revise anything for generation! The model will produce output as-is, without any need for additional configurations or modifications.
Training
We provide a minimal framework called 🔥 flame built on top of torchtitan, for efficient training of fla models.
Checkout the GLA example for more details.
Evaluation
The lm-evaluation-harness library allows you to easily perform (zero-shot) model evaluations. Follow the steps below to use this library:
Install
lm_evalfollowing their instructions.Run evaluation with:
sh $ PATH='fla-hub/gla-1.3B-100B' $ python -m evals.harness --model hf \ --model_args pretrained=$PATH,dtype=bfloat16 \ --tasks wikitext,lambada_openai,piqa,hellaswag,winogrande,arc_easy,arc_challenge,boolq,sciq,copa,openbookqa \ --batch_size 64 \ --num_fewshot 0 \ --device cuda \ --show_config
We've made fla compatible with hf-style evaluations, you can call evals.harness to finish the evaluations.
Running the command above will provide the task results reported in the GLA paper.
- Multi-GPU Evaluation with Hugging Face accelerate 🚀
To perform data-parallel evaluation (where each GPU loads a separate full copy of the model), we leverage the accelerate launcher as follows:
sh
$ PATH='fla-hub/gla-1.3B-100B'
$ accelerate launch -m evals.harness --model hf \
--model_args pretrained=$PATH,dtype=bfloat16 \
--tasks wikitext,lambada_openai,piqa,hellaswag,winogrande,arc_easy,arc_challenge,boolq,sciq,copa,openbookqa \
--batch_size 64 \
--num_fewshot 0 \
--device cuda \
--show_config
If a GPU can't load a full copy of the model, please refer to this link for FSDP settings.
[!Tip] If you are using
lm-evaluation-harnessas an external library and can't find (almost) any tasks available, before callinglm_eval.evaluate()orlm_eval.simple_evaluate(), simply run the following to load the library's stock tasks! ```pyfrom lmeval.tasks import TaskManager; TaskManager().initializetasks() ```
Benchmarks
We compared our Triton-based RetNet implementation with CUDA-based FlashAttention2, using a batch size of 8, 32 heads, and a head dimension of 128, across different sequence lengths. These tests were conducted on a single H100 80GB GPU, as illustrated in the following graph ```py
you might have to first install fla to enable its import via pip install -e .
$ python benchmarkretention.py Performance: T chunkfwd parallelfwd flashfwd chunkfwdbwd parallelfwdbwd flash_fwdbwd 0 128.0 0.264032 0.243536 0.083488 1.301856 1.166784 0.320704 1 256.0 0.273472 0.252848 0.094304 1.345872 1.300608 0.807936 2 512.0 0.303600 0.278896 0.098112 1.503168 1.433184 0.857216 3 1024.0 0.357248 0.367360 0.156528 1.773552 2.303424 1.160864 4 2048.0 0.454624 0.605616 0.340928 2.283728 4.483360 1.955936 5 4096.0 0.638960 1.378016 1.004992 3.374720 12.271215 4.813776 6 8192.0 1.012352 4.201344 3.625008 5.581808 40.833618 15.023697 7 16384.0 1.748512 14.489664 13.710080 10.191552 153.093765 54.336864 ```
Citation
If you find this repository helpful, please cite our work: ```bib @software{yang2024fla, title = {FLA: A Triton-Based Library for Hardware-Efficient Implementations of Linear Attention Mechanism}, author = {Yang, Songlin and Zhang, Yu}, url = {https://github.com/fla-org/flash-linear-attention}, month = jan, year = {2024} }
@inproceedings{yang2024gdn, title = {Gated Delta Networks: Improving Mamba2 with Delta Rule}, author = {Songlin Yang and Jan Kautz and Ali Hatamizadeh}, booktitle = {Proceedings of ICLR}, year = {2025} }
@inproceedings{yang2024deltanet, title = {Parallelizing Linear Transformers with the Delta Rule over Sequence Length}, author = {Yang, Songlin and Wang, Bailin and Zhang, Yu and Shen, Yikang and Kim, Yoon}, booktitle = {Proceedings of NeurIPS}, year = {2024} }
@inproceedings{zhang2024gsa, title = {Gated Slot Attention for Efficient Linear-Time Sequence Modeling}, author = {Zhang, Yu and Yang, Songlin and Zhu, Ruijie and Zhang, Yue and Cui, Leyang and Wang, Yiqiao and Wang, Bolun and Shi, Freda and Wang, Bailin and Bi, Wei and Zhou, Peng and Fu, Guohong}, booktitle = {Proceedings of NeurIPS}, year = {2024} }
@inproceedings{qin2024hgrn2, title = {HGRN2: Gated Linear RNNs with State Expansion}, author = {Qin, Zhen and Yang, Songlin and Sun, Weixuan and Shen, Xuyang and Li, Dong and Sun, Weigao and Zhong, Yiran}, booktitle = {Proceedings of COLM}, year = {2024} }
@inproceedings{yang2024gla, title = {Gated Linear Attention Transformers with Hardware-Efficient Training}, author = {Yang, Songlin and Wang, Bailin and Shen, Yikang and Panda, Rameswar and Kim, Yoon}, booktitle = {Proceedings of ICML}, year = {2024} } ```
Star History
Acknowledgments
We extend our gratitude to Intel Corporation and Bitdeer for providing CI server resources that power our infrastructure.
Owner
- Login: aniketm3
- Kind: user
- Repositories: 1
- Profile: https://github.com/aniketm3
Citation (CITATION.cff)
cff-version: 1.2.0 message: "If you use this software, please cite it as below." authors: - family-names: "Yang" given-names: "Songlin" orcid: "https://orcid.org/0000-0002-5944-0110" - family-names: "Zhang" given-names: "Yu" orcid: "https://orcid.org/0000-0002-8345-3835" title: "FLA: A Triton-Based Library for Hardware-Efficient Implementations of Linear Attention Mechanism" version: 0.1 date-released: 2024-01-18 url: "https://github.com/fla-org/flash-linear-attention"
GitHub Events
Total
- Push event: 2
- Create event: 2
Last Year
- Push event: 2
- Create event: 2