{"id":24269192,"url":"https://github.com/fla-org/flash-linear-attention","last_synced_at":"2026-01-14T06:59:58.196Z","repository":{"id":214928648,"uuid":"733802106","full_name":"fla-org/flash-linear-attention","owner":"fla-org","description":"🚀 Efficient implementations of state-of-the-art linear attention models","archived":false,"fork":false,"pushed_at":"2026-01-12T09:30:47.000Z","size":5905,"stargazers_count":4224,"open_issues_count":62,"forks_count":349,"subscribers_count":31,"default_branch":"main","last_synced_at":"2026-01-12T15:22:23.477Z","etag":null,"topics":["large-language-models","machine-learning-systems","natural-language-processing"],"latest_commit_sha":null,"homepage":"https://github.com/fla-org/flash-linear-attention","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fla-org.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-12-20T06:50:18.000Z","updated_at":"2026-01-12T14:28:10.000Z","dependencies_parsed_at":"2024-03-22T14:45:26.380Z","dependency_job_id":"64e99b08-87a2-4813-9f2d-df563a014eab","html_url":"https://github.com/fla-org/flash-linear-attention","commit_stats":null,"previous_names":["sustcsonglin/flash-linear-attention","fla-org/flash-linear-attention"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/fla-org/flash-linear-attention","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fla-org%2Fflash-linear-attention","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fla-org%2Fflash-linear-attention/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fla-org%2Fflash-linear-attention/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fla-org%2Fflash-linear-attention/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fla-org","download_url":"https://codeload.github.com/fla-org/flash-linear-attention/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fla-org%2Fflash-linear-attention/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28412478,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["large-language-models","machine-learning-systems","natural-language-processing"],"created_at":"2025-01-15T15:00:46.279Z","updated_at":"2026-01-14T06:59:58.190Z","avatar_url":"https://github.com/fla-org.png","language":"Python","funding_links":[],"categories":["Frameworks","Python","📄 Paper List","Repos","Linear attention"],"sub_categories":["Linear Sequence Modeling"],"readme":"\u003cdiv align=\"center\"\u003e\n\n# 💥 Flash Linear Attention\n\n[![hf_model](https://img.shields.io/badge/-Models-gray.svg?logo=huggingface\u0026style=flat-square)](https://huggingface.co/fla-hub)  [![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?\u0026logo=discord\u0026logoColor=white\u0026style=flat-square)](https://discord.gg/vDaJTmKNcS)\n\n\u003c/div\u003e\n\nThis repo aims at providing a collection of efficient Triton-based implementations for state-of-the-art linear attention models. **All implementations are written purely in PyTorch and Triton, making them platform-agnostic.** Currently verified platforms include NVIDIA, AMD, and Intel. **Any pull requests are welcome!**\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"400\" alt=\"image\" src=\"https://github.com/fla-org/flash-linear-attention/assets/18402347/02ff2e26-1495-4088-b701-e72cd65ac6cf\"\u003e\n\u003c/div\u003e\n\n* [News](#news)\n* [Models](#models)\n* [Installation](#installation)\n* [Usage](#usage)\n  * [Token Mixing](#token-mixing)\n  * [Fused Modules](#fused-modules)\n  * [Generation](#generation)\n  * [Hybrid Models](#hybrid-models)\n* [Training](#training)\n* [Evaluation](#evaluation)\n* [Benchmarks](#benchmarks)\n* [Citation](#citation)\n* [Star History](#star-history)\n* [Acknowledgements](#acknowledgements)\n\n## News\n\n- **$\\texttt{[2025-10]}$:** 🌑 Add Kimi Delta Attention implementation to `fla` ([paper](https://arxiv.org/abs/2510.26692)).\n- **$\\texttt{[2025-09]}$:** 🌲 Add DeltaFormer implementation to `fla` ([paper](https://arxiv.org/abs/2505.19488v1)).\n- **$\\texttt{[2025-09]}$:** 🐻 Thrilled to announce that [GDN](fla/ops/gated_delta_rule) has been integrated into Qwen3-Next. Check out their [blog post](https://qwen.ai/blog?id=4074cca80393150c248e508aa62983f9cb7d27cd\u0026from=research.latest-advancements-list) for more infos!\n- **$\\texttt{[2025-08]}$:** 🌲 Add Log-Linear Attention implementation to `fla` ([paper](https://arxiv.org/abs/2506.04761)).\n- **$\\texttt{[2025-08]}$:** 🎓 Add MoM implementation to `fla` ([paper](https://arxiv.org/abs/2502.13685)).\n- **$\\texttt{[2025-07]}$:** 🐳 Add MLA implementation to `fla` ([paper](https://arxiv.org/abs/2405.04434)).\n- **$\\texttt{[2025-07]}$:** 🛣️ Added PaTH Attention to fla ([paper](https://arxiv.org/abs/2505.16381)).\n- **$\\texttt{[2025-06]}$:** 🎉 Added MesaNet to fla ([paper](https://arxiv.org/abs/2506.05233)).\n- **$\\texttt{[2025-06]}$:** 🐍 Add Comba implementation to `fla` ([paper](https://arxiv.org/abs/2506.02475)).\n- **$\\texttt{[2025-05]}$:** 🎉 Add Rodimus\u0026ast; implementation to `fla` ([paper](https://arxiv.org/abs/2410.06577)).\n- **$\\texttt{[2025-04]}$:** 🎉 Add DeltaProduct implementation to `fla` ([paper](https://arxiv.org/abs/2502.10297)).\n- **$\\texttt{[2025-04]}$:** 🎉 Add FoX implementation to `fla` ([paper](https://arxiv.org/abs/2503.02130)).\n- **$\\texttt{[2025-03]}$:** ~~We have changed the default `initializer_range` to the magic 🐳 0.006~~ The `initializer_range` was rolled back to the default value of 0.02. For actual training, we recommend trying both.\n- **$\\texttt{[2025-02]}$:** 🐳 Add NSA implementations to `fla`. See kernels [here](fla/ops/nsa).\n- **$\\texttt{[2025-01]}$:** 🔥 We are migrating to `torchtitan`-based training framework. Check out the [flame](https://github.com/fla-org/flame) repo for more details.\n- **$\\texttt{[2025-01]}$:** 🦅 Add RWKV7 implementations (both kernels and models) to `fla`.\n- **$\\texttt{[2024-12]}$:** Integrated `flash-bidirectional-attention` to `fla-org` ([repo](https://github.com/fla-org/flash-bidirectional-linear-attention))\n- **$\\texttt{[2024-12]}$:** 🎉 Add Gated DeltaNet implementation to `fla` ([paper](https://arxiv.org/abs/2412.06464)).\n- **$\\texttt{[2024-12]}$:** 🚀 `fla` now officially supports kernels with variable-length inputs.\n- **$\\texttt{[2024-11]}$:** The inputs are now switched from head-first to seq-first format.\n- **$\\texttt{[2024-11]}$:** 💥 `fla` now provides a flexible way for training hybrid models.\n- **$\\texttt{[2024-10]}$:** 🔥 Announcing `flame`, a minimal and scalable framework for training `fla` models. Check out the details [here](training/README.md).\n- **$\\texttt{[2024-09]}$:** `fla` now includes a fused linear and cross-entropy layer, significantly reducing memory usage during training.\n- **$\\texttt{[2024-09]}$:** 🎉 Add GSA implementation to `fla` ([paper](https://arxiv.org/abs/2409.07146)).\n- **$\\texttt{[2024-05]}$:** 🎉 Add DeltaNet implementation to `fla` ([paper](https://arxiv.org/abs/2102.11174)).\n- **$\\texttt{[2024-05]}$:** 💥 `fla` v0.1: a variety of subquadratic kernels/layers/models integrated (RetNet/GLA/Mamba/HGRN/HGRN2/RWKV6, etc., see [Models](#models)).\n- **$\\texttt{[2023-12]}$:** 💥 Launched `fla`, offering a collection of implementations for state-of-the-art linear attention models.\n\n## Models\n\nRoughly sorted according to the timeline supported in `fla`. The recommended training mode is `chunk` when available.\n\n| Year | Venue   | Model                | Paper                                                                                                                                         | Code                                                                                            |                                                                                                       |\n| :--- | :------ | :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------: |\n| 2023 |         | RetNet               | [Retentive network: a successor to transformer for large language models](https://arxiv.org/abs/2307.08621)                                   | [official](https://github.com/microsoft/torchscale/tree/main)                                   | [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/multiscale_retention.py) |\n| 2024 | ICML    | GLA                  | [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635)                                      | [official](https://github.com/berlino/gated_linear_attention)                                   |         [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/gla.py)          |\n| 2024 | ICML    | Based                | [Simple linear attention language models balance the recall-throughput tradeoff](https://arxiv.org/abs/2402.18668)                            | [official](https://github.com/HazyResearch/based)                                               |        [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/based.py)         |\n| 2024 | ACL     | Rebased              | [Linear Transformers with Learnable Kernel Functions are Better In-Context Models](https://arxiv.org/abs/2402.10644)                          | [official](https://github.com/corl-team/rebased/)                                               |       [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/rebased.py)        |\n| 2024 | NeurIPS | DeltaNet             | [Parallelizing Linear Transformers with Delta Rule  over Sequence Length](https://arxiv.org/abs/2406.06484)                                   | [official](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/delta_net.py) |      [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/delta_net.py)       |\n| 2022 | ACL     | ABC                  | [ABC: Attention with Bounded-memory Control](https://arxiv.org/abs/2110.02488)                                                                |                                                                                                 |         [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/abc.py)          |\n| 2023 | NeurIPS | HGRN                 | [Hierarchically Gated Recurrent Neural Network for Sequence Modeling](https://openreview.net/forum?id=P1TCHxJwLB)                             | [official](https://github.com/OpenNLPLab/HGRN)                                                  |         [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/hgrn.py)         |\n| 2024 | COLM    | HGRN2                | [HGRN2: Gated Linear RNNs with State Expansion](https://arxiv.org/abs/2404.07904)                                                             | [official](https://github.com/OpenNLPLab/HGRN2)                                                 |        [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/hgrn2.py)         |\n| 2024 | COLM    | RWKV6                | [Eagle and Finch: RWKV with Matrix-Valued States and Dynamic Recurrence](https://arxiv.org/abs/2404.05892)                                    | [official](https://github.com/RWKV/RWKV-LM)                                                     |        [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/rwkv6.py)         |\n| 2024 |         | LightNet             | [You Only Scan Once: Efficient Multi-dimension Sequential Modeling with LightNet](https://arxiv.org/abs/2405.21022)                           | [official](https://github.com/OpenNLPLab/LightNet)                                              |       [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/lightnet.py)       |\n| 2025 | ICLR    | Samba                | [Samba: Simple Hybrid State Space Models for Efficient Unlimited Context Language Modeling](https://arxiv.org/abs/2406.07522)                 | [official](https://github.com/microsoft/Samba)                                                  |          [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/models/samba)          |\n| 2024 | ICML    | Mamba2               | [Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality](https://arxiv.org/abs/2405.21060) | [official](https://github.com/state-spaces/mamba)                                               |         [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/models/mamba2)          |\n| 2024 | NeurIPS | GSA                  | [Gated Slot Attention for Efficient Linear-Time Sequence Modeling](https://arxiv.org/abs/2409.07146)                                          | [official](https://github.com/fla-org/flash-linear-attention/tree/main/fla/models/gsa)          |           [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/models/gsa)           |\n| 2025 | ICLR    | Gated DeltaNet       | [Gated Delta Networks: Improving Mamba2 with Delta Rule](https://arxiv.org/abs/2412.06464)                                                    | [official](https://github.com/NVlabs/GatedDeltaNet)                                             |      [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/gated_delta_rule)      |\n| 2025 |         | RWKV7                | [RWKV-7 \"Goose\" with Expressive Dynamic State Evolution](https://arxiv.org/abs/2503.14456)                                                    | [official](https://github.com/BlinkDL/RWKV-LM/tree/main/RWKV-v7)                                |           [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/rwkv7)            |\n| 2025 |         | NSA                  | [Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention](https://arxiv.org/abs/2502.11089)                         |                                                                                                 |            [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/nsa)             |\n| 2025 | ICLR    | FoX                  | [Forgetting Transformer: Softmax Attention with a Forget Gate](https://arxiv.org/abs/2503.02130)                                              | [official](https://github.com/zhixuan-lin/forgetting-transformer)                               |      [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/forgetting_attn)       |\n| 2025 |         | DeltaProduct         | [DeltaProduct: Improving State-Tracking in Linear RNNs via Householder Products](https://arxiv.org/abs/2502.10297)                            |                                                                                                 |  [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/layers/gated_deltaproduct.py)  |\n| 2025 | ICLR    | Rodimus\u0026ast;         | [Rodimus*: Breaking the Accuracy-Efficiency Trade-Off with Efficient Attentions](https://arxiv.org/abs/2410.06577)                            | [official](https://github.com/codefuse-ai/rodimus)                                              |       [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/rodimus.py)        |\n| 2025 |         | MesaNet              | [MesaNet: Sequence Modeling by Locally Optimal Test-Time Training](https://arxiv.org/abs/2506.05233)                                          |                                                                                                 |       [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/mesa_net.py)       |\n| 2025 |         | Comba                | [Comba: Improving Bilinear RNNs with Closed-loop Control](https://arxiv.org/abs/2506.02475)                                                   | [official](https://github.com/AwesomeSeq/Comba-triton)                                          |        [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/comba.py)         |\n| 2025 |         | PaTH                 | [PaTH Attention: Position Encoding via Accumulating Householder Transformations](https://arxiv.org/abs/2505.16381)                            |                                                                                                 |      [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/path_attn.py)       |\n| 2025 |         | MoM                  | [MoM: Linear Sequence Modeling with Mixture-of-Memories](https://arxiv.org/abs/2502.13685)                                                    | [official](https://github.com/OpenSparseLLMs/MoM)                                               |         [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/mom.py)          |\n| 2025 |         | Log-Linear Attention | [Log-Linear Attention](https://arxiv.org/abs/2506.04761)                                                                                      | [official](https://github.com/HanGuo97/log-linear-attention)                                    |      [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/log_linear_attn)       |\n| 2025 |         | DeltaFormer          | [Understanding Transformer from the Perspective of Associative Memory](https://arxiv.org/abs/2505.19488v1)                                    |                                                                                                 |     [fla](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/deltaformer.py)      |\n| 2025 |         | KDA                  | [Kimi Linear: An Expressive, Efficient Attention Architecture](https://arxiv.org/abs/2510.26692)                                              |                                                                                                 |            [fla](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/kda)             |\n\n## Installation\n\n[![nvidia-4090-ci](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-4090.yml/badge.svg?branch=main\u0026event=push)](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-4090.yml) [![nvidia-a100-ci](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-a100.yml/badge.svg?branch=main)](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-a100.yml) [![nvidia-h100-ci](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-h100.yml/badge.svg?branch=main\u0026event=push)](https://github.com/fla-org/flash-linear-attention/actions/workflows/nvidia-h100.yml) [![intel-b580-ci](https://github.com/fla-org/flash-linear-attention/actions/workflows/intel-b580.yml/badge.svg?event=push)](https://github.com/fla-org/flash-linear-attention/actions/workflows/intel-b580.yml)\n\nThe following requirements should be satisfied\n- [PyTorch](https://pytorch.org/) \u003e= 2.5\n- [Triton](https://github.com/openai/triton) \u003e=3.0 (or nightly version, see [FAQs](FAQs.md))\n- [einops](https://einops.rocks/)\n- [transformers](https://github.com/huggingface/transformers) \u003e=4.45.0\n- [datasets](https://github.com/huggingface/datasets) \u003e=3.3.0\n\nStarting from v0.3.2, the packages published on PyPI are `fla-core` and `flash-linear-attention`. The former contains all our customized kernels and only depends on PyTorch, Triton, and einops. The latter is an extension package of the former, containing `fla/layers` and `fla/models`, and depends on transformers. We also provide Triton implementations for conv1d operations, so causal-conv1d is not required.\n\nYou can install `fla` with pip:\n```sh\npip install flash-linear-attention\n```\n\nAs `fla` is actively developed now, for the latest features and updates, an alternative way is to install the package from source. Note that installing from git uses the default mode, so you need to uninstall both `fla-core` and `flash-linear-attention` first:\n```sh\n# uninstall both packages first to ensure a successful upgrade\npip uninstall fla-core flash-linear-attention -y \u0026\u0026 pip install -U git+https://github.com/fla-org/flash-linear-attention\n```\nor manage `fla` with submodules\n```sh\ngit submodule add https://github.com/fla-org/flash-linear-attention.git 3rdparty/flash-linear-attention\nln -s 3rdparty/flash-linear-attention/fla fla\n```\n\nIf you have installed `triton-nightly` and `torch` pre version, please use the following command:\n```sh\npip install einops ninja datasets transformers numpy\n# uninstall both packages first to ensure a successful upgrade\npip uninstall fla-core flash-linear-attention -y \u0026\u0026 pip install -U --no-use-pep517 git+https://github.com/fla-org/flash-linear-attention --no-deps\n```\n\n\n## Usage\n\n[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/fla-org/flash-linear-attention)\n\n### Token Mixing\n\nWe provide ``token mixing'' linear attention layers in `fla.layers` for you to use.\nYou can replace the standard multihead attention layer in your model with other linear attention layers.\nExample usage is as follows:\n```py\n\u003e\u003e\u003e import torch\n\u003e\u003e\u003e from fla.layers import MultiScaleRetention\n\u003e\u003e\u003e batch_size, num_heads, seq_len, hidden_size = 32, 4, 2048, 1024\n\u003e\u003e\u003e device, dtype = 'cuda:0', torch.bfloat16\n\u003e\u003e\u003e retnet = MultiScaleRetention(hidden_size=hidden_size, num_heads=num_heads).to(device=device, dtype=dtype)\n\u003e\u003e\u003e retnet\nMultiScaleRetention(\n  (q_proj): Linear(in_features=1024, out_features=1024, bias=False)\n  (k_proj): Linear(in_features=1024, out_features=1024, bias=False)\n  (v_proj): Linear(in_features=1024, out_features=2048, bias=False)\n  (g_proj): Linear(in_features=1024, out_features=2048, bias=False)\n  (o_proj): Linear(in_features=2048, out_features=1024, bias=False)\n  (g_norm_swish_gate): FusedRMSNormGated(512, eps=1e-05, activation=swish)\n  (rotary): RotaryEmbedding(dim=256, base=10000.0, interleaved=False, pos_idx_in_fp32=True)\n)\n\u003e\u003e\u003e x = torch.randn(batch_size, seq_len, hidden_size).to(device=device, dtype=dtype)\n\u003e\u003e\u003e y, *_ = retnet(x)\n\u003e\u003e\u003e y.shape\ntorch.Size([32, 2048, 1024])\n```\n\nWe provide the implementations of models that are compatible with 🤗 Transformers library.\nHere's an example of how to initialize a GLA model from the default configs in `fla`:\n\n```py\n\u003e\u003e\u003e from fla.models import GLAConfig\n\u003e\u003e\u003e from transformers import AutoModelForCausalLM\n\u003e\u003e\u003e config = GLAConfig()\n\u003e\u003e\u003e config\nGLAConfig {\n  \"attn\": null,\n  \"attn_mode\": \"chunk\",\n  \"bos_token_id\": 1,\n  \"clamp_min\": null,\n  \"conv_size\": 4,\n  \"elementwise_affine\": true,\n  \"eos_token_id\": 2,\n  \"expand_k\": 0.5,\n  \"expand_v\": 1,\n  \"feature_map\": null,\n  \"fuse_cross_entropy\": true,\n  \"fuse_norm\": true,\n  \"fuse_swiglu\": true,\n  \"hidden_act\": \"swish\",\n  \"hidden_ratio\": 4,\n  \"hidden_size\": 2048,\n  \"initializer_range\": 0.006,\n  \"intermediate_size\": null,\n  \"max_position_embeddings\": 2048,\n  \"model_type\": \"gla\",\n  \"norm_eps\": 1e-06,\n  \"num_heads\": 4,\n  \"num_hidden_layers\": 24,\n  \"num_kv_heads\": null,\n  \"tie_word_embeddings\": false,\n  \"transformers_version\": \"4.50.1\",\n  \"use_cache\": true,\n  \"use_gk\": true,\n  \"use_gv\": false,\n  \"use_output_gate\": true,\n  \"use_short_conv\": false,\n  \"vocab_size\": 32000\n}\n\n\u003e\u003e\u003e AutoModelForCausalLM.from_config(config)\nGLAForCausalLM(\n  (model): GLAModel(\n    (embeddings): Embedding(32000, 2048)\n    (layers): ModuleList(\n      (0-23): 24 x GLABlock(\n        (attn_norm): RMSNorm(2048, eps=1e-06)\n        (attn): GatedLinearAttention(\n          (q_proj): Linear(in_features=2048, out_features=1024, bias=False)\n          (k_proj): Linear(in_features=2048, out_features=1024, bias=False)\n          (v_proj): Linear(in_features=2048, out_features=2048, bias=False)\n          (g_proj): Linear(in_features=2048, out_features=2048, bias=False)\n          (gk_proj): Sequential(\n            (0): Linear(in_features=2048, out_features=16, bias=False)\n            (1): Linear(in_features=16, out_features=1024, bias=True)\n          )\n          (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n          (g_norm_swish_gate): FusedRMSNormGated(512, eps=1e-06, activation=swish)\n        )\n        (mlp_norm): RMSNorm(2048, eps=1e-06)\n        (mlp): GatedMLP(\n          (gate_proj): Linear(in_features=2048, out_features=5632, bias=False)\n          (up_proj): Linear(in_features=2048, out_features=5632, bias=False)\n          (down_proj): Linear(in_features=5632, out_features=2048, bias=False)\n          (swiglu_linear): SwiGLULinear()\n        )\n      )\n    )\n    (norm): RMSNorm(2048, eps=1e-06)\n  )\n  (lm_head): Linear(in_features=2048, out_features=32000, bias=False)\n)\n```\n\n### Fused Modules\n\nWe offer a collection of fused modules in `fla.modules` to facilitate faster training:\n\n* [`Rotary Embedding`](fla/modules/rotary.py): rotary positional embeddings as adopted by the Llama architecture, a.k.a., Transformer++.\n* [`Norm Layers`](fla/modules/layernorm.py):\n  * `RMSNorm`, `LayerNorm` and `GroupNorm`\n  * `RMSNormLinear`, `LayerNormLinear` and `GroupNormLinear` to reduce memory usage of intermediate tensors for improved memory efficiency.\n* [`Norm Layers with Gating`](fla/modules/fused_norm_gate.py): combine norm layers with element-wise sigmoid or swish gating, as used by RetNet/GLA.\n* [`Cross Entropy`](fla/modules/fused_cross_entropy.py): faster Triton implementation of cross entropy loss.\n* [`Linear Cross Entropy`](fla/modules/fused_linear_cross_entropy.py): fused linear layer and cross entropy loss to avoid the materialization of large logits tensors. Also refer to implementations by [mgmalek](https://github.com/mgmalek/efficient_cross_entropy) and [Liger-Kernel](https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py).\n* [`Linear KL Divergence`](fla/modules/fused_kl_div.py): fused linear layer and KL divergence loss in a similar vein as CE loss.\n\n\u003e [!IMPORTANT]\n\u003e You can control using `fuse_linear_cross_entropy` in the model configuration to enable/disable the fused linear cross entropy loss.\n\u003e\n\u003e This fused implementation is more memory-efficient but may reduce numerical precision. Due to this trade-off, it is disabled by default.\n\u003e If you enable this feature and encounter training instability (e.g., loss divergence), we recommend disabling it to see if the issue is resolved.\n\n### Generation\n\nUpon successfully pretraining a model, it becomes accessible for generating text using the 🤗 text generation APIs.\nIn the following, we give a generation example:\n```py\n\u003e\u003e\u003e import fla\n\u003e\u003e\u003e from transformers import AutoModelForCausalLM, AutoTokenizer\n\u003e\u003e\u003e name = 'fla-hub/gla-1.3B-100B'\n\u003e\u003e\u003e tokenizer = AutoTokenizer.from_pretrained(name)\n\u003e\u003e\u003e model = AutoModelForCausalLM.from_pretrained(name).cuda()\n\u003e\u003e\u003e input_prompt = \"Power goes with permanence. Impermanence is impotence. And rotation is castration.\"\n\u003e\u003e\u003e input_ids = tokenizer(input_prompt, return_tensors=\"pt\").input_ids.cuda()\n\u003e\u003e\u003e outputs = model.generate(input_ids, max_length=64)\n\u003e\u003e\u003e tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]\n```\n\nWe also provide a simple script [here](benchmarks/benchmark_generation.py) for benchmarking the generation speed.\nSimply run it by:\n```sh\n$ python -m benchmarks.benchmark_generation \\\n  --path 'fla-hub/gla-1.3B-100B' \\\n  --repetition_penalty 2. \\\n  --prompt=\"Hello everyone, I'm Songlin Yang\"\n\nPrompt:\nHello everyone, I'm Songlin Yang\nGenerated:\nHello everyone, I'm Songlin Yang.\nI 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\n\nPrompt length: 10, generation length: 64\nTotal prompt processing + decoding time: 4593ms\n```\n\nAll of the pretrained models currently available can be found in [`fla-hub`](https://huggingface.co/fla-hub).\n```py\n\u003e\u003e\u003e from huggingface_hub import list_models\n\u003e\u003e\u003e for model in list_models(author='fla-hub'): print(model.id)\n```\n\n### Hybrid Models\n\n`fla` provides a flexible method to incorporate standard attention layers into existing linear attention models.\nThis is easily achieved by specifying the `attn` argument in the model configuration.\n\nFor example, to create a 2-layer Samba model with interleaved Mamba and local attention layers, using a sliding window size of 2048:\n\n```py\n\u003e\u003e\u003e from fla.models import SambaConfig\n\u003e\u003e\u003e from transformers import AutoModelForCausalLM\n\u003e\u003e\u003e config = SambaConfig(num_hidden_layers=2)\n\u003e\u003e\u003e config.attn = {\n  'layers': [1],\n  'num_heads': 18,\n  'num_kv_heads': 18,\n  'qkv_bias': False,\n  'rope_theta': 10000.,\n  'window_size': 2048\n}\n\u003e\u003e\u003e config\nSambaConfig {\n  \"attn\": {\n    \"layers\": [\n      1\n    ],\n    \"num_heads\": 18,\n    \"num_kv_heads\": 18,\n    \"qkv_bias\": false,\n    \"rope_theta\": 10000.0,\n    \"window_size\": 2048\n  },\n  \"bos_token_id\": 1,\n  \"conv_kernel\": 4,\n  \"eos_token_id\": 2,\n  \"expand\": 2,\n  \"fuse_cross_entropy\": true,\n  \"fuse_norm\": true,\n  \"fuse_swiglu\": true,\n  \"hidden_act\": \"swish\",\n  \"hidden_ratio\": 4,\n  \"hidden_size\": 2304,\n  \"initializer_range\": 0.02,\n  \"intermediate_size\": 4608,\n  \"max_position_embeddings\": 2048,\n  \"model_type\": \"samba\",\n  \"norm_eps\": 1e-05,\n  \"num_hidden_layers\": 2,\n  \"pad_token_id\": 0,\n  \"rescale_prenorm_residual\": false,\n  \"residual_in_fp32\": false,\n  \"state_size\": 16,\n  \"tie_word_embeddings\": false,\n  \"time_step_floor\": 0.0001,\n  \"time_step_init_scheme\": \"random\",\n  \"time_step_max\": 0.1,\n  \"time_step_min\": 0.001,\n  \"time_step_rank\": 144,\n  \"time_step_scale\": 1.0,\n  \"transformers_version\": \"4.50.1\",\n  \"use_bias\": false,\n  \"use_cache\": true,\n  \"use_conv_bias\": true,\n  \"vocab_size\": 32000\n}\n\n\u003e\u003e\u003e AutoModelForCausalLM.from_config(config)\nSambaForCausalLM(\n  (backbone): SambaModel(\n    (embeddings): Embedding(32000, 2304)\n    (layers): ModuleList(\n      (0): SambaBlock(\n        (mixer_norm): RMSNorm(2304, eps=1e-05)\n        (mixer): Mamba(\n          (conv1d): Conv1d(4608, 4608, kernel_size=(4,), stride=(1,), padding=(3,), groups=4608)\n          (in_proj): Linear(in_features=2304, out_features=9216, bias=False)\n          (x_proj): Linear(in_features=4608, out_features=176, bias=False)\n          (dt_proj): Linear(in_features=144, out_features=4608, bias=True)\n          (out_proj): Linear(in_features=4608, out_features=2304, bias=False)\n        )\n        (mlp_norm): RMSNorm(2304, eps=1e-05)\n        (mlp): GatedMLP(\n          (gate_proj): Linear(in_features=2304, out_features=6144, bias=False)\n          (up_proj): Linear(in_features=2304, out_features=6144, bias=False)\n          (down_proj): Linear(in_features=6144, out_features=2304, bias=False)\n          (swiglu_linear): SwiGLULinear()\n        )\n      )\n      (1): SambaBlock(\n        (mixer_norm): RMSNorm(2304, eps=1e-05)\n        (mixer): Attention(\n          (q_proj): Linear(in_features=2304, out_features=2304, bias=False)\n          (k_proj): Linear(in_features=2304, out_features=2304, bias=False)\n          (v_proj): Linear(in_features=2304, out_features=2304, bias=False)\n          (o_proj): Linear(in_features=2304, out_features=2304, bias=False)\n          (rotary): RotaryEmbedding(dim=128, base=10000.0, interleaved=False, pos_idx_in_fp32=True)\n        )\n        (mlp_norm): RMSNorm(2304, eps=1e-05)\n        (mlp): GatedMLP(\n          (gate_proj): Linear(in_features=2304, out_features=6144, bias=False)\n          (up_proj): Linear(in_features=2304, out_features=6144, bias=False)\n          (down_proj): Linear(in_features=6144, out_features=2304, bias=False)\n          (swiglu_linear): SwiGLULinear()\n        )\n      )\n    )\n    (norm_f): RMSNorm(2304, eps=1e-05)\n  )\n  (lm_head): Linear(in_features=2304, out_features=32000, bias=False)\n)\n```\n\nDuring inference, you **DO NOT** need to revise anything for generation!\nThe model will produce output as-is, without any need for additional configurations or modifications.\n\n## Training\n\nWe provide a minimal framework called [🔥 `flame`](https://github.com/fla-org/flame) built on top of `torchtitan`, for efficient training of `fla` models.\n\nCheckout [the GLA example](https://github.com/fla-org/flash-linear-attention/blob/main/examples/training.md) for more details.\n\n## Evaluation\n\nThe [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) library allows you to easily perform (zero-shot) model evaluations.\nFollow the steps below to use this library:\n\n1. Install `lm_eval` following [their instructions](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/README.md).\n\n2. Run evaluation with:\n```sh\n$ MODEL='fla-hub/gla-1.3B-100B'\n$ python -m evals.harness --model hf \\\n    --model_args pretrained=$MODEL,dtype=bfloat16 \\\n    --tasks wikitext,lambada_openai,piqa,hellaswag,winogrande,arc_easy,arc_challenge,boolq,sciq,copa,openbookqa \\\n    --batch_size 64 \\\n    --num_fewshot 0 \\\n    --device cuda \\\n    --show_config\n```\n\nWe've made `fla` compatible with hf-style evaluations, you can call [evals.harness](evals/harness.py) to finish the evaluations.\nRunning the command above will provide the task results reported in the GLA paper.\n\n3. Multi-GPU Evaluation with Hugging Face accelerate 🚀\n\nTo perform data-parallel evaluation (where each GPU loads a separate full copy of the model), we leverage the accelerate launcher as follows:\n```sh\n$ MODEL='fla-hub/gla-1.3B-100B'\n$ accelerate launch -m evals.harness --model hf  \\\n    --model_args pretrained=$MODEL,dtype=bfloat16,trust_remote_code=True  \\\n    --tasks wikitext,lambada_openai,piqa,hellaswag,winogrande,arc_easy,arc_challenge,boolq,sciq,copa,openbookqa \\\n    --batch_size 64  \\\n    --num_fewshot 0  \\\n    --device cuda  \\\n    --show_config  \\\n    --trust_remote_code\n```\n\n4. 📏 RULER Benchmark suite\n\nThe RULER benchmarks are commonly used for evaluating model performance on long-context tasks.\nYou can evaluate `fla` models on RULER directly using `lm-evaluation-harness`. RULER is only available in a relatively recent version of `lm-evaluation-harness`, so make sure you have the latest version installed.\n\n```\ngit clone --depth 1 https://github.com/EleutherAI/lm-evaluation-harness\ncd lm-evaluation-harness\npip install -e .\n```\n\n\nThen, install the necessary dependencies for RULER:\n```sh\npip install lm_eval[\"ruler\"]\n```\nand run evaluation by (e.g., 32k contexts):\n```sh\n$ accelerate launch -m evals.harness \\\n    --output_path $OUTPUT \\\n    --tasks niah_single_1,niah_single_2,niah_single_3,niah_multikey_1,niah_multikey_2,niah_multikey_3,niah_multiquery,niah_multivalue,ruler_vt,ruler_cwe,ruler_fwe,ruler_qa_hotpot,ruler_qa_squad \\\n    --model_args pretrained=$MODEL,dtype=bfloat16,max_length=32768,trust_remote_code=True \\\n    --metadata='{\"max_seq_lengths\":[4096,8192,16384,32768]}' \\\n    --batch_size 2 \\\n    --show_config  \\\n    --trust_remote_code\n```\n\nIf a GPU can't load a full copy of the model, please refer to [this link](https://github.com/EleutherAI/lm-evaluation-harness?tab=readme-ov-file#multi-gpu-evaluation-with-hugging-face-accelerate) for FSDP settings.\n\n\u003e [!Tip]\n\u003e If you are using `lm-evaluation-harness` as an external library and can't find (almost) any tasks available, before calling `lm_eval.evaluate()` or `lm_eval.simple_evaluate()`, simply run the following to load the library's stock tasks!\n```py\n\u003e\u003e\u003e from lm_eval.tasks import TaskManager; TaskManager().initialize_tasks()\n```\n\n## Benchmarks\n\nWe 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.\nThese tests were conducted on a single H100 80GB GPU, as illustrated in the following graph\n```py\n# you might have to first install `fla` to enable its import via `pip install -e .`\n$ python benchmark_retention.py\nPerformance:\n         T  chunk_fwd  parallel_fwd  flash_fwd  chunk_fwdbwd  parallel_fwdbwd  flash_fwdbwd\n0    128.0   0.264032      0.243536   0.083488      1.301856         1.166784      0.320704\n1    256.0   0.273472      0.252848   0.094304      1.345872         1.300608      0.807936\n2    512.0   0.303600      0.278896   0.098112      1.503168         1.433184      0.857216\n3   1024.0   0.357248      0.367360   0.156528      1.773552         2.303424      1.160864\n4   2048.0   0.454624      0.605616   0.340928      2.283728         4.483360      1.955936\n5   4096.0   0.638960      1.378016   1.004992      3.374720        12.271215      4.813776\n6   8192.0   1.012352      4.201344   3.625008      5.581808        40.833618     15.023697\n7  16384.0   1.748512     14.489664  13.710080     10.191552       153.093765     54.336864\n```\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"500\" alt=\"image\" src=\"https://github.com/user-attachments/assets/c2607015-63af-43d1-90d1-ad5fe1670a03\"\u003e\n\u003c/div\u003e\n\n\n## Citation\nIf you find this repository helpful, please cite our work:\n```bib\n@software{yang2024fla,\n  title  = {FLA: A Triton-Based Library for Hardware-Efficient Implementations of Linear Attention Mechanism},\n  author = {Yang, Songlin and Zhang, Yu},\n  url    = {https://github.com/fla-org/flash-linear-attention},\n  month  = jan,\n  year   = {2024}\n}\n\n@misc{zhang2025kda,\n    title         = {Kimi Linear: An Expressive, Efficient Attention Architecture},\n    author        = {Zhang, Yu  and Lin, Zongyu  and Yao, Xingcheng  and Hu, Jiaxi  and Meng, Fanqing  and Liu, Chengyin  and Men, Xin  and Yang, Songlin  and Li, Zhiyuan  and Li, Wentao  and Lu, Enzhe  and Liu, Weizhou  and Chen, Yanru  and Xu, Weixin  and Yu, Longhui  and Wang, Yejie  and Fan, Yu  and Zhong, Longguang  and Yuan, Enming  and Zhang, Dehao  and Zhang, Yizhi  and T. Liu, Y.  and Wang, Haiming  and Fang, Shengjun  and He, Weiran  and Liu, Shaowei  and Li, Yiwei  and Su, Jianlin  and Qiu, Jiezhong  and Pang, Bo  and Yan, Junjie  and Jiang, Zhejun  and Huang, Weixiao  and Yin, Bohong  and You, Jiacheng  and Wei, Chu  and Wang, Zhengtao  and Hong, Chao  and Chen, Yutian  and Chen, Guanduo  and Wang, Yucheng  and Zheng, Huabin  and Wang, Feng  and Liu, Yibo  and Dong, Mengnan  and Zhang, Zheng  and Pan, Siyuan  and Wu, Wenhao  and Wu, Yuhao  and Guan, Longyu  and Tao, Jiawen  and Fu, Guohong  and Xu, Xinran  and Wang, Yuzhi  and Lai, Guokun  and Wu, Yuxin  and Zhou, Xinyu  and Yang, Zhilin  and Du, Yulun},\n    year          = {2025},\n    eprint        = {2510.26692},\n    archivePrefix = {arXiv},\n    primaryClass  = {cs.CL}\n}\n\n@inproceedings{yang2025path,\n  title     = {PaTH Attention: Position Encoding via Accumulating Householder Transformations},\n  author    = {Yang, Songlin  and Shen, Yikang and Wen, Kaiyue and Tan, Shawn  and Mishra, Mayank  and Ren, Liliang  and Panda, Rameswar  and Kim, Yoon},\n  booktitle = {Proceedings of NeurIPS},\n  year      = {2025}\n}\n\n@inproceedings{yang2024gdn,\n  title     = {Gated Delta Networks: Improving Mamba2 with Delta Rule},\n  author    = {Yang, Songlin  and Kautz, Jan  and Hatamizadeh, Ali},\n  booktitle = {Proceedings of ICLR},\n  year      = {2025}\n}\n\n@inproceedings{yang2024deltanet,\n  title     = {Parallelizing Linear Transformers with the Delta Rule over Sequence Length},\n  author    = {Yang, Songlin and Wang, Bailin and Zhang, Yu and Shen, Yikang and Kim, Yoon},\n  booktitle = {Proceedings of NeurIPS},\n  year      = {2024}\n}\n\n@inproceedings{zhang2024gsa,\n  title     = {Gated Slot Attention for Efficient Linear-Time Sequence Modeling},\n  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},\n  booktitle = {Proceedings of NeurIPS},\n  year      = {2024}\n}\n\n@inproceedings{qin2024hgrn2,\n  title     = {HGRN2: Gated Linear RNNs with State Expansion},\n  author    = {Qin, Zhen and Yang, Songlin and Sun, Weixuan and Shen, Xuyang and Li, Dong and Sun, Weigao and Zhong, Yiran},\n  booktitle = {Proceedings of COLM},\n  year      = {2024}\n}\n\n@inproceedings{yang2024gla,\n  title     = {Gated Linear Attention Transformers with Hardware-Efficient Training},\n  author    = {Yang, Songlin and Wang, Bailin and Shen, Yikang and Panda, Rameswar and Kim, Yoon},\n  booktitle = {Proceedings of ICML},\n  year      = {2024}\n}\n```\n\n## Star History\n\n[![Stargazers repo roster for @fla-org/flash-linear-attention](https://bytecrank.com/nastyox/reporoster/php/stargazersSVG.php?user=fla-org\u0026repo=flash-linear-attention)](https://github.com/fla-org/flash-linear-attention/stargazers)\n\n[![Star History Chart](https://api.star-history.com/svg?repos=fla-org/flash-linear-attention\u0026type=Date)](https://star-history.com/#fla-org/flash-linear-attention\u0026Date)\n\n## Acknowledgements\n\nWe extend our gratitude to [Bitdeer](https://www.bitdeer.com/) and [Moonshot AI](https://www.moonshot.ai/) for their support in maintaining and powering our project infrastructure.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffla-org%2Fflash-linear-attention","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffla-org%2Fflash-linear-attention","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffla-org%2Fflash-linear-attention/lists"}