{"id":26632885,"url":"https://github.com/sustcsonglin/flash-linear-attention","last_synced_at":"2025-03-24T15:03:16.111Z","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 in Torch and Triton","archived":false,"fork":false,"pushed_at":"2025-03-22T08:28:44.000Z","size":3121,"stargazers_count":2143,"open_issues_count":25,"forks_count":135,"subscribers_count":27,"default_branch":"main","last_synced_at":"2025-03-22T09:25:22.170Z","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}},"created_at":"2023-12-20T06:50:18.000Z","updated_at":"2025-03-22T08:28:48.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":1,"template":false,"template_full_name":null,"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","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245294764,"owners_count":20591900,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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-03-24T15:01:55.168Z","updated_at":"2025-03-24T15:03:16.100Z","avatar_url":"https://github.com/fla-org.png","language":"Python","funding_links":[],"categories":["Input-dependent gating.","📖Contents"],"sub_categories":["📖Non Transformer Architecture ([©️back👆🏻](#paperlist))"],"readme":"\u003cdiv align=\"center\"\u003e\n\n# :boom: 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. **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\n## News\n\n- **$\\texttt{[2025-03]}$:** We have changed the default `initializer_range` to the magic :whale: 0.006, leading to great improvements across all models.\n- **$\\texttt{[2025-02]}$:** :whale: Add NSA implementations to `fla`. See kernels [here](fla/ops/nsa).\n- **$\\texttt{[2025-01]}$:** :fire: 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]}$:** :tada: 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]}$:** :tada: Add Gated DeltaNet implementation to `fla` ([paper](https://arxiv.org/abs/2412.06464)).\n- **$\\texttt{[2024-12]}$:** :rocket: `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]}$:** :boom: `fla` now provides a flexible way for training hybrid models.\n- **$\\texttt{[2024-10]}$:** :fire: 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]}$:** :tada: Add GSA implementation to `fla` ([paper](https://arxiv.org/abs/2409.07146)).\n- **$\\texttt{[2024-05]}$:** :tada: Add DeltaNet implementation to `fla` ([paper](https://arxiv.org/abs/2102.11174)).\n- **$\\texttt{[2024-05]}$:** :boom: `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]}$:** :boom: 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          | Title                                                                                                     |                       Paper                        |                                              Code                                               |                                               `fla` impl                                               |\n| :--- | :------ | :------------- | :-------------------------------------------------------------------------------------------------------- | :------------------------------------------------: | :---------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: |\n| 2023 |         | RetNet         | Retentive network: a successor to transformer for large language models                                   |      [link](https://arxiv.org/abs/2307.08621)      |                  [official](https://github.com/microsoft/torchscale/tree/main)                  | [code](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                                      |      [link](https://arxiv.org/abs/2312.06635)      |                  [official](https://github.com/berlino/gated_linear_attention)                  |         [code](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                            |      [link](https://arxiv.org/abs/2402.18668)      |                        [official](https://github.com/HazyResearch/based)                        |        [code](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                          |      [link](https://arxiv.org/abs/2402.10644)      |                        [official](https://github.com/corl-team/rebased/)                        |       [code](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                                   |      [link](https://arxiv.org/abs/2406.06484)      | [official](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/delta_net.py) |      [code](https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/delta_net.py)       |\n| 2022 | ACL     | ABC            | Attention with Bounded-memory Control                                                                     |      [link](https://arxiv.org/abs/2110.02488)      |                                                                                                 |         [code](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                                       | [link](https://openreview.net/forum?id=P1TCHxJwLB) |                         [official](https://github.com/OpenNLPLab/HGRN)                          |         [code](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                                                             |      [link](https://arxiv.org/abs/2404.07904)      |                         [official](https://github.com/OpenNLPLab/HGRN2)                         |        [code](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                                    |      [link](https://arxiv.org/abs/2404.05892)      |                           [official](https://github.com/RWKV/RWKV-LM)                           |        [code](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                           |      [link](https://arxiv.org/abs/2405.21022)      |                       [official](https://github.com/OpenNLPLab/LightNet)                        |       [code](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                 |      [link](https://arxiv.org/abs/2406.07522)      |                         [official](https://github.com/microsoft/Samba)                          |          [code](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 |      [link](https://arxiv.org/abs/2405.21060)      |                        [official](https://github.com/state-spaces/mamba)                        |         [code](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                                          |      [link](https://arxiv.org/abs/2409.07146)      |     [official](https://github.com/fla-org/flash-linear-attention/tree/main/fla/models/gsa)      |           [code](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                                                    |      [link](https://arxiv.org/abs/2412.06464)      |                       [official](https://github.com/NVlabs/GatedDeltaNet)                       |      [code](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/gated_delta_rule)      |\n| 2025 |         | RWKV7          |                                                                                                           |                                                    |                [official](https://github.com/BlinkDL/RWKV-LM/tree/main/RWKV-v7)                 |           [code](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                         |      [link](https://arxiv.org/abs/2502.11089)      |                                                                                                 |            [code](https://github.com/fla-org/flash-linear-attention/tree/main/fla/ops/nsa)             |\n\n## Installation\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- [causal-conv1d](https://github.com/Dao-AILab/causal-conv1d) \u003e=1.4.0\n\nYou can install `fla` with pip:\n```sh\npip install flash-linear-attention\n```\nAs `fla` is actively developed now, for the latest features and updates, an alternative way is to install the package from source\n```sh\n# uninstall `fla` first to ensure a successful upgrade\npip uninstall flash-linear-attention \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\n## Usage\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): FusedRMSNormSwishGate(512, eps=1e-05)\n  (rotary): RotaryEmbedding()\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.02,\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.48.2\",\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): FusedRMSNormSwishGate(512, eps=1e-06)\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        )\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 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### 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  '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    \"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  \"hidden_act\": \"silu\",\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.45.0\",\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): MambaMixer(\n          (conv1d): Conv1d(4608, 4608, kernel_size=(4,), stride=(1,), padding=(3,), groups=4608)\n          (act): SiLU()\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): SambaMLP(\n          (gate_proj): Linear(in_features=2304, out_features=12288, bias=False)\n          (down_proj): Linear(in_features=6144, out_features=2304, bias=False)\n          (act_fn): SiLU()\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()\n        )\n        (mlp_norm): RMSNorm(2304, eps=1e-05)\n        (mlp): SambaMLP(\n          (gate_proj): Linear(in_features=2304, out_features=12288, bias=False)\n          (down_proj): Linear(in_features=6144, out_features=2304, bias=False)\n          (act_fn): SiLU()\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 [:fire: `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$ PATH='fla-hub/gla-1.3B-100B'\n$ python -m evals.harness --model hf \\\n    --model_args pretrained=$PATH,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$ PATH='fla-hub/gla-1.3B-100B'\n$ accelerate launch -m evals.harness --model hf \\\n    --model_args pretrained=$PATH,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\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@inproceedings{yang2024gdn,\n  title     = {Gated Delta Networks: Improving Mamba2 with Delta Rule},\n  author    = {Songlin Yang and Jan Kautz and Ali Hatamizadeh},\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\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\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsustcsonglin%2Fflash-linear-attention","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsustcsonglin%2Fflash-linear-attention","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsustcsonglin%2Fflash-linear-attention/lists"}