{"id":15035682,"url":"https://github.com/nx-ai/xlstm","last_synced_at":"2025-05-13T22:06:39.206Z","repository":{"id":242636644,"uuid":"797795600","full_name":"NX-AI/xlstm","owner":"NX-AI","description":"Official repository of the xLSTM.","archived":false,"fork":false,"pushed_at":"2025-04-07T07:42:18.000Z","size":273,"stargazers_count":1843,"open_issues_count":39,"forks_count":141,"subscribers_count":18,"default_branch":"main","last_synced_at":"2025-04-29T14:03:07.982Z","etag":null,"topics":["deep-learning","deep-learning-architecture","llm","machine-learning","nlp","rnn"],"latest_commit_sha":null,"homepage":"https://www.nx-ai.com/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NX-AI.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-05-08T14:29:53.000Z","updated_at":"2025-04-29T12:52:54.000Z","dependencies_parsed_at":"2024-08-04T10:50:00.777Z","dependency_job_id":"e7760ee0-8a12-4a90-8fc0-1af138571d65","html_url":"https://github.com/NX-AI/xlstm","commit_stats":{"total_commits":40,"total_committers":3,"mean_commits":"13.333333333333334","dds":0.625,"last_synced_commit":"dc16b5143c00d3149040a9296264c4a2c55ce695"},"previous_names":["nx-ai/xlstm"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NX-AI%2Fxlstm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NX-AI%2Fxlstm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NX-AI%2Fxlstm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NX-AI%2Fxlstm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NX-AI","download_url":"https://codeload.github.com/NX-AI/xlstm/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036819,"owners_count":22003654,"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":["deep-learning","deep-learning-architecture","llm","machine-learning","nlp","rnn"],"created_at":"2024-09-24T20:29:11.589Z","updated_at":"2025-05-13T22:06:34.193Z","avatar_url":"https://github.com/NX-AI.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# xLSTM: Extended Long Short-Term Memory\n\n![xLSTM Figure](./res/desc_xlstm_overview.svg)\n\n\u003e Paper: https://arxiv.org/abs/2405.04517\n\u003e\n\u003e Authors: Maximilian Beck, Korbinian Pöppel, Markus Spanring, Andreas Auer, Oleksandra Prudnikova, Michael Kopp, Günter Klambauer, Johannes Brandstetter, Sepp Hochreiter\n\n## About\n\nxLSTM is a new Recurrent Neural Network architecture based on ideas of the original LSTM.\nThrough Exponential Gating with appropriate normalization and stabilization techniques and a new Matrix Memory it overcomes the limitations of the original LSTM \nand shows promising performance on Language Modeling when compared to Transformers or State Space Models.\n\n:rotating_light: We trained a 7B parameter xLSTM Language Model on 2.3T tokens! :rotating_light:\n\nWe refer to the optimized architecture for our xLSTM 7B as xLSTM Large. \n\n## Minimal Installation\n\nCreate a conda environment from the file `environment_pt240cu124.yaml`.\nInstall the model code only (i.e. the module `xlstm`) as package:\n\nFor using the xLSTM Large 7B model install [`mlstm_kernels`](https://github.com/NX-AI/mlstm_kernels) via:\n``` \npip install mlstm_kernels\n```\nThen install the xlstm package via pip: \n```bash\npip install xlstm\n```\nOr clone from github:\n```bash\ngit clone https://github.com/NX-AI/xlstm.git\ncd xlstm\npip install -e .\n```\n\n## Requirements\n\nThis package is based on PyTorch and was tested for versions `\u003e=1.8`. For a well-tested environment, install the `environment_pt240cu124.yaml` as:\n```bash\nconda env create -n xlstm -f environment_pt240cu124.yaml\nconda activate xlstm\n``` \n\nFor the xLSTM Large 7B model we require our [`mlstm_kernels`](https://github.com/NX-AI/mlstm_kernels) package, which provides fast kernels for the xLSTM.\n\n# xLSTM 7B: A Recurrent LLM for Fast and Efficient Inference\n\n\u003e Paper: https://arxiv.org/abs/2503.13427\n\u003e\n\u003e Authors: Maximilian Beck, Korbinian Pöppel, Phillip Lippe, Richard Kurle, Patrick M. Blies, Günter Klambauer, Sebastian Böck, Sepp Hochreiter\n\n![xLSTM Figure](./res/xlstm_7b_poster.svg)\n\nWe have optimized the xLSTM architecture in terms of training throughput and stability. \nThe code for the updated architecture is located in `xlstm/xlstm_large`.\n\nThe model weights are available on Huggingface at https://huggingface.co/NX-AI/xLSTM-7b. \n\n## How to use the xLSTM Large 7B and its architecture\n\nWe provide a standalone single file implementation of the xLSTM Large architecture in [`xlstm/xlstm_large/model.py`](https://github.com/NX-AI/xlstm/blob/main/xlstm/xlstm_large/model.py).\nThis implementation requires our [`mlstm_kernels`](https://github.com/NX-AI/mlstm_kernels) package and other than that has no dependency on the NeurIPS xLSTM architecture implementation.\n\nFor a quick start, we provide a [`demo.ipynb`](https://github.com/NX-AI/xlstm/blob/main/notebooks/xlstm_large/demo.ipynb) notebook for the xLSTM Large architecture at `notebooks/xlstm_large/demo.ipynb`. \n\nIn this notebook we import our config and model class, initialize a random model and perform a forward pass, like so:\n\n```python\nimport torch\nfrom xlstm.xlstm_large.model import xLSTMLargeConfig, xLSTMLarge\n\n# configure the model with TFLA Triton kernels\nxlstm_config = xLSTMLargeConfig(\n    embedding_dim=512,\n    num_heads=4,\n    num_blocks=6,\n    vocab_size=2048,\n    return_last_states=True,\n    mode=\"inference\",\n    chunkwise_kernel=\"chunkwise--triton_xl_chunk\", # xl_chunk == TFLA kernels\n    sequence_kernel=\"native_sequence__triton\",\n    step_kernel=\"triton\",\n)\n# instantiate the model\nxlstm = xLSTMLarge(xlstm_config)\nxlstm = xlstm.to(\"cuda\")\n# create inputs\ninput = torch.randint(0, 2048, (3, 256)).to(\"cuda\")\n# run a forward pass\nout = xlstm(input)\nout.shape[1:] == (256, 2048)\n```\n\n## Recommendation for other hardware\n\nWe have tested our model mostly on NVIDIA GPUs, however our Triton kernels should also run on AMD GPUs. \nFor other platforms, like Apple Metal, we recommend using the native PyTorch implementations for now:\n\n```python \nxlstm_config = xLSTMLargeConfig(\n    embedding_dim=512,\n    num_heads=4,\n    num_blocks=6,\n    vocab_size=2048,\n    return_last_states=True,\n    mode=\"inference\",\n    chunkwise_kernel=\"chunkwise--native_autograd\", # no Triton kernels\n    sequence_kernel=\"native_sequence__native\", # no Triton kernels\n    step_kernel=\"native\", # no Triton kernels\n)\n```\n\n# Models from the xLSTM NeurIPS Paper\n\nThis section explains how to use the models from the xLSTM paper.\n\n## How to use the xLSTM architecture from our NeurIPS paper\n\nFor non language applications or for integrating in other architectures you can use the `xLSTMBlockStack` and for language modeling or other token-based applications you can use the `xLSTMLMModel`.\n\n### Using the sLSTM CUDA kernels\n\nFor the CUDA version of sLSTM, you need Compute Capability \u003e= 8.0, see [https://developer.nvidia.com/cuda-gpus](https://developer.nvidia.com/cuda-gpus). If you have problems with the compilation, please try (thanks to [@zia1138](https://github.com/zia1138) for pointing out):\n```bash\nexport TORCH_CUDA_ARCH_LIST=\"8.0;8.6;9.0\"\n```\n\nFor all kinds of custom setups with torch and CUDA, keep in mind that versions have to match. Also, to make sure the correct CUDA libraries are included you can use the \"XLSTM_EXTRA_INCLUDE_PATHS\" environment variable now to inject different include paths, e.g.:\n\n```bash\nexport XLSTM_EXTRA_INCLUDE_PATHS='/usr/local/include/cuda/:/usr/include/cuda/'\n```\n\nor within python:\n\n```python\nimport os\nos.environ['XLSTM_EXTRA_INCLUDE_PATHS']='/usr/local/include/cuda/:/usr/include/cuda/'\n```\n\nfor standalone, even faster sLSTM kernels, feel free to use the [FlashRNN](https://github.com/NX-AI/flashrnn) library.\n\n### xLSTM Block Stack\n\nThe `xLSTMBLockStack` is meant for use as alternative backbone in existing projects. It is similar to a stack of Transformer blocks, but uses xLSTM blocks:\n\n```python\nimport torch\n\nfrom xlstm import (\n    xLSTMBlockStack,\n    xLSTMBlockStackConfig,\n    mLSTMBlockConfig,\n    mLSTMLayerConfig,\n    sLSTMBlockConfig,\n    sLSTMLayerConfig,\n    FeedForwardConfig,\n)\n\ncfg = xLSTMBlockStackConfig(\n    mlstm_block=mLSTMBlockConfig(\n        mlstm=mLSTMLayerConfig(\n            conv1d_kernel_size=4, qkv_proj_blocksize=4, num_heads=4\n        )\n    ),\n    slstm_block=sLSTMBlockConfig(\n        slstm=sLSTMLayerConfig(\n            backend=\"cuda\",\n            num_heads=4,\n            conv1d_kernel_size=4,\n            bias_init=\"powerlaw_blockdependent\",\n        ),\n        feedforward=FeedForwardConfig(proj_factor=1.3, act_fn=\"gelu\"),\n    ),\n    context_length=256,\n    num_blocks=7,\n    embedding_dim=128,\n    slstm_at=[1],\n\n)\n\nxlstm_stack = xLSTMBlockStack(cfg)\n\nx = torch.randn(4, 256, 128).to(\"cuda\")\nxlstm_stack = xlstm_stack.to(\"cuda\")\ny = xlstm_stack(x)\ny.shape == x.shape\n```\n\nIf you are working with yaml strings / files for configuration you can also use dacite to create the config dataclasses. This is the same as the snippet above:\n\n```python\nfrom omegaconf import OmegaConf\nfrom dacite import from_dict\nfrom dacite import Config as DaciteConfig\nfrom xlstm import xLSTMBlockStack, xLSTMBlockStackConfig\n\nxlstm_cfg = \"\"\" \nmlstm_block:\n  mlstm:\n    conv1d_kernel_size: 4\n    qkv_proj_blocksize: 4\n    num_heads: 4\nslstm_block:\n  slstm:\n    backend: cuda\n    num_heads: 4\n    conv1d_kernel_size: 4\n    bias_init: powerlaw_blockdependent\n  feedforward:\n    proj_factor: 1.3\n    act_fn: gelu\ncontext_length: 256\nnum_blocks: 7\nembedding_dim: 128\nslstm_at: [1]\n\"\"\"\ncfg = OmegaConf.create(xlstm_cfg)\ncfg = from_dict(data_class=xLSTMBlockStackConfig, data=OmegaConf.to_container(cfg), config=DaciteConfig(strict=True))\nxlstm_stack = xLSTMBlockStack(cfg)\n\nx = torch.randn(4, 256, 128).to(\"cuda\")\nxlstm_stack = xlstm_stack.to(\"cuda\")\ny = xlstm_stack(x)\ny.shape == x.shape\n\n```\n\n\n### xLSTM Language Model\n\nThe `xLSTMLMModel` is a wrapper around the `xLSTMBlockStack` that adds the token embedding and lm head.\n\n```python\nfrom omegaconf import OmegaConf\nfrom dacite import from_dict\nfrom dacite import Config as DaciteConfig\nfrom xlstm import xLSTMLMModel, xLSTMLMModelConfig\n\nxlstm_cfg = \"\"\" \nvocab_size: 50304\nmlstm_block:\n  mlstm:\n    conv1d_kernel_size: 4\n    qkv_proj_blocksize: 4\n    num_heads: 4\nslstm_block:\n  slstm:\n    backend: cuda\n    num_heads: 4\n    conv1d_kernel_size: 4\n    bias_init: powerlaw_blockdependent\n  feedforward:\n    proj_factor: 1.3\n    act_fn: gelu\ncontext_length: 256\nnum_blocks: 7\nembedding_dim: 128\nslstm_at: [1]\n\"\"\"\ncfg = OmegaConf.create(xlstm_cfg)\ncfg = from_dict(data_class=xLSTMLMModelConfig, data=OmegaConf.to_container(cfg), config=DaciteConfig(strict=True))\nxlstm_stack = xLSTMLMModel(cfg)\n\nx = torch.randint(0, 50304, size=(4, 256)).to(\"cuda\")\nxlstm_stack = xlstm_stack.to(\"cuda\")\ny = xlstm_stack(x)\ny.shape[1:] == (256, 50304)\n```\n\n\n## Experiments\n\nThe synthetic experiments show-casing the benefits of sLSTM over mLSTM and vice versa best are the Parity task and the Multi-Query Associative Recall task. The Parity task can only be solved with state-tracking capabilities provided by the memory-mixing of sLSTM. The Multi-Query Associative Recall task measures memorization capabilities, where the matrix-memory and state expansion of mLSTM is very beneficial.\nIn combination they do well on both tasks.\n\nTo run each, run the `main.py` in the experiments folder like:\n```\nPYTHONPATH=. python experiments/main.py --config experiments/parity_xlstm01.yaml   # xLSTM[0:1], sLSTM only\nPYTHONPATH=. python experiments/main.py --config experiments/parity_xlstm10.yaml   # xLSTM[1:0], mLSTM only\nPYTHONPATH=. python experiments/main.py --config experiments/parity_xlstm11.yaml   # xLSTM[1:1], mLSTM and sLSTM\n```\n\nNote that the training loop does not contain early stopping or test evaluation.\n\n\n## Citation\n\nIf you use this codebase, or otherwise find our work valuable, please cite the xLSTM paper:\n```\n@inproceedings{beck:24xlstm,\n      title={xLSTM: Extended Long Short-Term Memory}, \n      author={Maximilian Beck and Korbinian Pöppel and Markus Spanring and Andreas Auer and Oleksandra Prudnikova and Michael Kopp and Günter Klambauer and Johannes Brandstetter and Sepp Hochreiter},\n      booktitle = {Thirty-eighth Conference on Neural Information Processing Systems},\n      year={2024},\n      url={https://arxiv.org/abs/2405.04517}, \n}\n\n@article{beck:25xlstm7b,\n  title        = {{xLSTM 7B}: A Recurrent LLM for Fast and Efficient Inference},\n  author       = {Maximilian Beck and Korbinian Pöppel and Phillip Lippe and Richard Kurle and Patrick M. Blies and Günter Klambauer and Sebastian Böck and Sepp Hochreiter},\n  year         = {2025},\n  volume       = {2503.13427},\n  journal      = {arXiv},\n  primaryclass = {cs.LG},\n  url          = {https://arxiv.org/abs/2503.13427}\n}\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnx-ai%2Fxlstm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnx-ai%2Fxlstm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnx-ai%2Fxlstm/lists"}