[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-Relaxed-System-Lab--Flash-Sparse-Attention":3,"tool-Relaxed-System-Lab--Flash-Sparse-Attention":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",159636,2,"2026-04-17T23:33:34",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":76,"owner_location":76,"owner_email":77,"owner_twitter":76,"owner_website":76,"owner_url":78,"languages":79,"stars":88,"forks":89,"last_commit_at":90,"license":91,"difficulty_score":92,"env_os":93,"env_gpu":94,"env_ram":93,"env_deps":95,"category_tags":104,"github_topics":105,"view_count":32,"oss_zip_url":76,"oss_zip_packed_at":76,"status":17,"created_at":109,"updated_at":110,"faqs":111,"releases":112},8756,"Relaxed-System-Lab\u002FFlash-Sparse-Attention","Flash-Sparse-Attention","🚀🚀 Efficient implementations of Native Sparse Attention","Flash-Sparse-Attention 是一款专为现代 GPU 设计的高效开源工具，旨在加速大型语言模型中的原生稀疏注意力（NSA）计算。它主要解决了传统 NSA 实现在处理不同分组查询注意力（GQA）规模时，因硬件矩阵维度限制而被迫进行数据填充，从而导致大量无效内存访问和计算冗余的性能瓶颈问题。\n\n该工具特别适合 AI 研究人员和深度学习开发者使用，尤其是那些希望在长序列场景下优化大模型训练与推理效率的技术团队。其核心技术亮点在于创新地重构了内核循环顺序：将原本“先遍历查询令牌”的逻辑改为“先遍历键值块”，并将计算过程解耦为批处理、归约和在线 Softmax 三个独立内核。这种设计不仅有效消除了填充数据带来的资源浪费，还避免了跨块累积结果时的原子操作开销。实测表明，在长上下文任务中，Flash-Sparse-Attention 能显著降低显存占用并提升运行速度，让原生可训练的稀疏注意力技术更易于在主流大模型架构中落地应用。","\u003Cimg width=\"6200\" height=\"1294\" alt=\"github_title\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_0dda15c7bd52.png\" \u002F>\n\n---\n\n\u003Cdiv align=\"center\">\n\n[![arxiv](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FarXiv-2508.18224-b31b1b.svg?style=flat-square)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2508.18224)\n\n\u003C\u002Fdiv>\n\nThis repository provides the official implementation of **\u003Cins>F\u003C\u002Fins>lash \u003Cins>S\u003C\u002Fins>parse \u003Cins>A\u003C\u002Fins>ttention (FSA)**, which includes a novel kernel design that enables efficient Native Sparse Attention (NSA) across a wide range of popular LLMs on modern GPUs.\n\n- [News](#news)\n- [Method](#method)\n- [Advantages](#advantages)\n- [Features](#features)\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Instantiate FSA Module](#instantiate-fsa-module)\n  - [Train with FSA](#train-with-fsa)\n- [Evaluation](#evaluation)\n  - [Benchmark FSA Module](#benchmark-fsa-module)\n  - [Benchmark FSA Selected Attention Module](#benchmark-fsa-selected-attention-module)\n- [Performance](#performance)\n  - [Kernel Performance](#kernel-performance)\n  - [End-to-end Performance](#end-to-end-performance)\n- [Citation](#citation)\n- [Acknowledgments](#acknowledgments)\n\n## News\n\n- **$\\texttt{[2025-09, upcoming]}$:** 🚀 Online profiling module, which seamlessly transitions between NSA and FSA, will be released soon.\n- **$\\texttt{[2025-08]}$:** 💥 Our [Arxiv paper](https:\u002F\u002Fwww.arxiv.org\u002Fabs\u002F2508.18224) is released.\n- **$\\texttt{[2025-08]}$:** 🎈 Beta version of one-step decoding is released, check the code residing in [`fsa_preview`](fsa_preview).\n- **$\\texttt{[2025-08]}$:** 🎉 Open sourced `Flash-Sparse-Attention`, offering an optimized implementation for NSA, broadening the applicability of this novel natively trainable sparse attention technique.\n\n## Method\n\nFor NSA selected attention module, the major system bottleneck, NSA loops over query tokens in the outer loop and loops over KV blocks in the inner loop. To optimize performance, NSA batches query heads that share the same key-value head for more efficient computation. However, when GQA group size is not sufficiently large, NSA selected attention kernel must pad data to satisfy hardware requirements on the matrix dimensions of matrix multiplication. Specifically, for NVIDIA GPUs, the [warp-level matrix multiply-accumulate instructions](https:\u002F\u002Fdocs.nvidia.com\u002Fcuda\u002Fparallel-thread-execution\u002Findex.html#warp-level-matrix-instructions) require that each dimension of a matrix tile executed on a warp must be larger than the specified value (at least 8 on Hopper GPUs). In [Triton](https:\u002F\u002Ftriton-lang.org\u002Fmain\u002F), NSA selected attention kernel must also satisfy that each dimension of a matrix tile executed on a thread block must be at least 16.\n\n\nIn contrast, FSA exchanges the kernel loop order of original NSA kernel design, i.e., FSA loops over KV blocks in the outer loop and loops over query tokens in the inner loop. To optimize performance, FSA decouples the computation into three major kernels: (i) the main kernel batches query tokens that attend to the same KV block and stores the partial results to a buffer, (ii) the reduction kernel accumulates attention results for each query token, and (iii) the online softmax kernel that handles online softmax statistics computation. The key insight behind this arrangement is to effectively reduce unnecessary memory access and computations for the padded data, while avoiding `atomic` additions for accumulating attention results for each query token across KV blocks.\n\nThe concrete computation process comparison between NSA (left) and FSA main kernel (right) can be visualized as follows:\n\n![combine2 (1)](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_615996150e04.png)\n\n\n## Advantages\n\n🚀 The speedup of FSA originates from significantly lowered kernel-level memory access volume and computations.\n\nUnder varied GQA group sizes, NSA hyperparameters block size $B_K=64$ and topk-k value $T=16$, 64K sequence length, 4 KV heads, the execution latency comparisons between NSA and our method are as follows (execution latency of our method is normalized to 1):\n\u003Cimg width=\"4320\" height=\"2592\" alt=\"GQA_comp\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_58c1a64844a9.png\" \u002F>\n\n\n\n## Features\n\nFSA provides an optimized kernel implementation for NSA selected attention module. Without modifying NSA algorithm, FSA provides an efficient Triton-based implementation for GQA group sizes smaller than 8, which is more popular on state-of-the-art large language models (LLMs), on modern high-performance NVIDIA GPUs. For GQA group sizes larger than or equal to 8, FSA usually chooses to fall back to the original NSA implementation for better performance.\n\nFSA is currently well tested with:\n- NVIDIA Ampere or Hopper GPUs (e.g., A100 SXM, H20, H100 PCIe, H100 NVL, H100 SXM, H200 SXM);\n- Datatype of fp16 and bf16;\n- The same head dimension (less than or equal to 256) across query, key, and value;\n- Varied GQA group sizes, ranging from 1 to 16;\n- Training and inference (prefill).\n\n## Installation\n\nThe following requirements should be satisfied:\n- [PyTorch](https:\u002F\u002Fpytorch.org\u002F) >= 2.4\n- [Triton](https:\u002F\u002Fgithub.com\u002Fopenai\u002Ftriton) >=3.0\n- [transformers](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers) >=4.45.0\n- [datasets](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Fdatasets) >=3.3.0\n- [accelerate](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Faccelerate) >= 1.9.0\n- [flash-attn](https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention) ==2.6.3\n\nYou can install dependencies for FSA with:\n```sh\npip install -r requirements.txt\n```\n\n## Usage\n\n### Instantiate FSA Module\n\nWe provide [``FlashSparseAttention``](fsa\u002Fmodule\u002FFSA.py) class for you to use, it can be used as the following example:\n```Python\nimport torch\nfrom fsa.module.fsa import FlashSparseAttention, RopeConfig\n\nFSA = (\n    FlashSparseAttention(\n        hidden_size=4096,\n        num_q_heads=4,\n        num_kv_heads=4,\n        head_dim=128,\n        kernel_size=32,\n        kernel_stride=16,\n        block_size=64,\n        topk=16,\n        init_blocks=1,\n        local_blocks=2,\n        window_size=512,\n        rope_config=RopeConfig(\n            max_position_embeddings=131072,\n            head_dim=128,\n            rope_theta=500000,\n            rope_scaling={\n                \"factor\": 8.0,\n                \"high_freq_factor\": 4.0,\n                \"low_freq_factor\": 1.0,\n                \"original_max_position_embeddings\": 8192,\n                \"rope_type\": \"llama3\",\n            },\n        ),\n    )\n    .cuda()\n    .to(torch.bfloat16)\n)\n# random input\nseqlens = torch.LongTensor([65536, 32768]).int().cuda()\n\ncu_seqlens = torch.cat(\n    [\n        torch.zeros(1, dtype=torch.int32, device=\"cuda\"),\n        torch.cumsum(seqlens, dim=0),\n    ],\n    dim=0,\n).to(torch.int32)\nx = torch.randn(cu_seqlens[-1], 4096, device=\"cuda\", dtype=torch.bfloat16)\n\ny = FSA(x, cu_seqlens)\nloss = (y * torch.randn_like(y)).sum(-1).mean()\nloss.backward()\n```\n\nUnder the hood, the [``FSATopkSparseAttention``](fsa\u002Fops\u002FFSA_topk_sparse_attention.py) class is called, provding the optimized kernels that accelerate the NSA selected attention module.\n\n### Train with FSA\n\nTraining with FSA can be esaily achieved by replacing the attention module. The only thing you may need to handle is to instantiate the FSA module, and compute the ``cu_seqlens`` for FSA. We provide an example on how to insert FSA into a LLM in [``SparseLlamaAttention``](test\u002Ftrain.py).\n\n## Evaluation\n\n### Benchmark FSA Module\n\nWe provide detailed commands in [`scripts\u002Frun_unit_test.sh`](scripts\u002Frun_unit_test.sh) for convenient benchmarking of FSA module. The benchmarking provides correctness comparison of forward and backward outputs, performance comparison, and memory usage comparison.\n\n\n### Benchmark FSA Selected Attention Module\n\nThe optimized NSA selected attention module, which is the major system bottleneck, can be benchmarked through the commands in [``scripts\u002Frun_unit_test_sel_attn.sh``](scripts\u002Frun_unit_test_sel_attn.sh).\n\n> [!Tip]\nTry varied ``gqa``, `seqlen`, `block_size`, `topk` argument in the provided scripts for more comprehensive benchmarking on your machine! Compared to benchmarking the FSA attention module, benchmarking the FSA selected attention module usually provides a higher speedup.\n\n## Performance\n\n### Kernel Performance\n\n> Performance comparison of Triton-based FSA, NSA, and Full Attention (enabled by Flash Attention) kernels under various configurations. The tuple ($64$, $16$) \u002F ($128$, $8$) represents the block size $BK$ and top-k value $Topk$, respectively. For FSA and NSA, the execution latency is composed of compressed, selected, and sliding attention; for Full Attention, the execution latency is the Flash Attention kernel execution latency.\n\n\u003Cimg width=\"4366\" height=\"3057\" alt=\"kernel_perf\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_ef4cbe361ee7.png\" \u002F>\n\n### End-to-end Performance\n\n> End-to-end training (right) and prefill (left) latency of state-of-the-art LLMs with FSA, NSA, or Full Attention.\n\n\u003Cimg width=\"6165\" height=\"3093\" alt=\"e2e_githubpic\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_8f5505b30548.png\" \u002F>\n\n\n## Citation\n\n```\n@article{yan2025flashsparseattentionalternative,\n  title={Flash Sparse Attention: More Efficient Natively Trainable Sparse Attention},\n  author={Yan, Ran and Jiang, Youhe and Yuan, Binhang},\n  journal={arXiv preprint arXiv:2508.18224},\n  year={2025}\n}\n```\n\n## Acknowledgments\n\nNSA paper:\n[Native Sparse Attention](https:\u002F\u002Farxiv.org\u002Fabs\u002F2502.11089)\n\nNSA reference implementation:\n[Native Sparse Attention Triton](https:\u002F\u002Fgithub.com\u002FXunhaoLai\u002Fnative-sparse-attention-triton)\n","\u003Cimg width=\"6200\" height=\"1294\" alt=\"github_title\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_0dda15c7bd52.png\" \u002F>\n\n---\n\n\u003Cdiv align=\"center\">\n\n[![arxiv](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FarXiv-2508.18224-b31b1b.svg?style=flat-square)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2508.18224)\n\n\u003C\u002Fdiv>\n\n本仓库提供了 **\u003Cins>F\u003C\u002Fins>lash \u003Cins>S\u003C\u002Fins>parse \u003Cins>A\u003C\u002Fins>ttention (FSA)** 的官方实现，其中包含一种新颖的内核设计，能够在现代 GPU 上高效地支持多种主流大模型中的原生稀疏注意力（NSA）。\n\n- [新闻](#news)\n- [方法](#method)\n- [优势](#advantages)\n- [特性](#features)\n- [安装](#installation)\n- [使用](#usage)\n  - [实例化 FSA 模块](#instantiate-fsa-module)\n  - [使用 FSA 进行训练](#train-with-fsa)\n- [评估](#evaluation)\n  - [FSA 模块基准测试](#benchmark-fsa-module)\n  - [FSA 稀疏注意力模块基准测试](#benchmark-fsa-selected-attention-module)\n- [性能](#performance)\n  - [内核性能](#kernel-performance)\n  - [端到端性能](#end-to-end-performance)\n- [引用](#citation)\n- [致谢](#acknowledgments)\n\n## 新闻\n\n- **$\\texttt{[2025-09, 即将发布]}$:** 🚀 可在 NSA 和 FSA 之间无缝切换的在线剖析模块即将发布。\n- **$\\texttt{[2025-08]}$:** 💥 我们的 [Arxiv 论文](https:\u002F\u002Fwww.arxiv.org\u002Fabs\u002F2508.18224) 已正式发表。\n- **$\\texttt{[2025-08]}$:** 🎈 一步解码的 Beta 版本已发布，请查看位于 [`fsa_preview`](fsa_preview) 中的代码。\n- **$\\texttt{[2025-08]}$:** 🎉 开源了 `Flash-Sparse-Attention`，提供了一种针对 NSA 的优化实现，进一步拓展了这种可原生训练的新型稀疏注意力技术的应用范围。\n\n## 方法\n\n对于 NSA 稀疏注意力模块而言，其主要的系统瓶颈在于：外层循环遍历查询 token，而内层循环则遍历 KV 块。为了优化性能，NSA 会将共享相同键值头的查询头进行批处理，以提升计算效率。然而，当 GQA 分组大小不够大时，NSA 稀疏注意力内核必须对数据进行填充，以满足硬件对矩阵乘法维度的要求。具体来说，在 NVIDIA GPU 上，[warp 级矩阵乘累加指令](https:\u002F\u002Fdocs.nvidia.com\u002Fcuda\u002Fparallel-thread-execution\u002Findex.html#warp-level-matrix-instructions)要求在 warp 上执行的矩阵分块的每个维度都必须大于指定值（Hopper 架构的 GPU 至少为 8）。而在 [Triton](https:\u002F\u002Ftriton-lang.org\u002Fmain\u002F) 中，NSA 稀疏注意力内核还必须确保线程块上执行的矩阵分块的每个维度至少为 16。\n\n相比之下，FSA 改变了原始 NSA 内核的循环顺序，即外层循环遍历 KV 块，内层循环则遍历查询 token。为了优化性能，FSA 将计算过程拆分为三个主要内核：(i) 主内核将关注同一 KV 块的查询 token 批量处理，并将部分结果存储到缓冲区中；(ii) 归约内核负责累积每个查询 token 的注意力结果；(iii) 在线 softmax 内核则用于处理在线 softmax 统计信息的计算。这一设计的关键在于有效减少了对填充数据的不必要内存访问和计算，同时避免了跨 KV 块对每个查询 token 的注意力结果进行 `atomic` 加法操作。\n\nNSA（左）与 FSA 主内核（右）的具体计算流程对比可以可视化如下：\n\n![combine2 (1)](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_615996150e04.png)\n\n\n## 优势\n\n🚀 FSA 的速度提升源于显著降低的内核级内存访问量和计算量。\n\n在不同的 GQA 分组大小下，NSA 的超参数设置为：KV 块大小 $B_K=64$，topk 值 $T=16$，序列长度为 64K，KV 头数为 4。NSA 与我们方法的执行延迟对比结果如下（我们方法的执行延迟被归一化为 1）：\n\u003Cimg width=\"4320\" height=\"2592\" alt=\"GQA_comp\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_58c1a64844a9.png\" \u002F>\n\n\n\n## 特性\n\nFSA 提供了一种针对 NSA 稀疏注意力模块的优化内核实现。在不改变 NSA 算法的前提下，FSA 基于 Triton 提供了一种高效的实现方案，适用于当前最先进的大型语言模型（LLMs）中更为常见的 GQA 分组大小小于 8 的情况，且运行于现代高性能 NVIDIA GPU 上。而对于 GQA 分组大小大于或等于 8 的情况，FSA 通常会选择回退到原始的 NSA 实现，以获得更好的性能。\n\n目前，FSA 已在以下环境中经过充分测试：\n- NVIDIA Ampere 或 Hopper 架构的 GPU（例如 A100 SXM、H20、H100 PCIe、H100 NVL、H100 SXM、H200 SXM）；\n- 数据类型为 fp16 和 bf16；\n- 查询、键和值的头维度相同（不超过 256）；\n- GQA 分组大小从 1 到 16 不等；\n- 支持训练和推理（预填充阶段）。\n\n## 安装\n\n请确保满足以下依赖条件：\n- [PyTorch](https:\u002F\u002Fpytorch.org\u002F) ≥ 2.4\n- [Triton](https:\u002F\u002Fgithub.com\u002Fopenai\u002Ftriton) ≥ 3.0\n- [transformers](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers) ≥ 4.45.0\n- [datasets](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Fdatasets) ≥ 3.3.0\n- [accelerate](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Faccelerate) ≥ 1.9.0\n- [flash-attn](https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention) == 2.6.3\n\n您可以通过以下命令安装 FSA 的依赖项：\n```sh\npip install -r requirements.txt\n```\n\n## 使用\n\n### 实例化 FSA 模块\n\n我们提供了 [``FlashSparseAttention``](fsa\u002Fmodule\u002FFSA.py) 类供您使用，用法示例如下：\n```Python\nimport torch\nfrom fsa.module.fsa import FlashSparseAttention, RopeConfig\n\nFSA = (\n    FlashSparseAttention(\n        hidden_size=4096,\n        num_q_heads=4,\n        num_kv_heads=4,\n        head_dim=128,\n        kernel_size=32,\n        kernel_stride=16,\n        block_size=64,\n        topk=16,\n        init_blocks=1,\n        local_blocks=2,\n        window_size=512,\n        rope_config=RopeConfig(\n            max_position_embeddings=131072,\n            head_dim=128,\n            rope_theta=500000,\n            rope_scaling={\n                \"factor\": 8.0,\n                \"high_freq_factor\": 4.0,\n                \"low_freq_factor\": 1.0,\n                \"original_max_position_embeddings\": 8192,\n                \"rope_type\": \"llama3\",\n            },\n        ),\n    )\n    .cuda()\n    .to(torch.bfloat16)\n)\n\n# 随机输入\nseqlens = torch.LongTensor([65536, 32768]).int().cuda()\n\ncu_seqlens = torch.cat(\n    [\n        torch.zeros(1, dtype=torch.int32, device=\"cuda\"),\n        torch.cumsum(seqlens, dim=0),\n    ],\n    dim=0,\n).to(torch.int32)\nx = torch.randn(cu_seqlens[-1], 4096, device=\"cuda\", dtype=torch.bfloat16)\n\ny = FSA(x, cu_seqlens)\nloss = (y * torch.randn_like(y)).sum(-1).mean()\nloss.backward()\n```\n\n在底层，调用了 [``FSATopkSparseAttention``](fsa\u002Fops\u002FFSA_topk_sparse_attention.py) 类，该类提供了优化的内核，用于加速 NSA 选择性注意力模块。\n\n### 使用 FSA 进行训练\n\n使用 FSA 进行训练可以通过简单地替换注意力模块来实现。你可能需要做的唯一事情就是实例化 FSA 模块，并为 FSA 计算 ``cu_seqlens``。我们在 [``SparseLlamaAttention``](test\u002Ftrain.py) 中提供了一个示例，说明如何将 FSA 插入到 LLM 中。\n\n## 评估\n\n### FSA 模块基准测试\n\n我们在 [`scripts\u002Frun_unit_test.sh`](scripts\u002Frun_unit_test.sh) 中提供了详细的命令，以便于对 FSA 模块进行便捷的基准测试。该基准测试包括前向和反向输出的正确性比较、性能比较以及内存使用情况的比较。\n\n\n### FSA 选择性注意力模块基准测试\n\n作为系统主要瓶颈的优化 NSA 选择性注意力模块，可以通过 [``scripts\u002Frun_unit_test_sel_attn.sh``](scripts\u002Frun_unit_test_sel_attn.sh) 中的命令进行基准测试。\n\n> [!Tip]\n尝试在提供的脚本中调整不同的 ``gqa``、`seqlen`、`block_size`、`topk` 参数，以在你的机器上进行更全面的基准测试！与基准测试 FSA 注意力模块相比，基准测试 FSA 选择性注意力模块通常能带来更高的加速效果。\n\n## 性能\n\n### 内核性能\n\n> 在各种配置下，基于 Triton 的 FSA、NSA 和全注意力（由 Flash Attention 启用）内核的性能比较。元组 ($64$, $16$) \u002F ($128$, $8$) 分别表示块大小 $BK$ 和 top-k 值 $Topk$。对于 FSA 和 NSA，执行延迟由压缩、选择和滑动注意力组成；而对于全注意力，则是 Flash Attention 内核的执行延迟。\n\n\u003Cimg width=\"4366\" height=\"3057\" alt=\"kernel_perf\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_ef4cbe361ee7.png\" \u002F>\n\n### 端到端性能\n\n> 具有 FSA、NSA 或全注意力的最先进 LLM 的端到端训练（右）和预填充（左）延迟。\n\n\u003Cimg width=\"6165\" height=\"3093\" alt=\"e2e_githubpic\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_readme_8f5505b30548.png\" \u002F>\n\n\n## 引用\n\n```\n@article{yan2025flashsparseattentionalternative,\n  title={Flash Sparse Attention: 更高效的原生可训练稀疏注意力},\n  author={Yan, Ran and Jiang, Youhe and Yuan, Binhang},\n  journal={arXiv 预印本 arXiv:2508.18224},\n  year={2025}\n}\n```\n\n## 致谢\n\nNSA 论文：\n[原生稀疏注意力](https:\u002F\u002Farxiv.org\u002Fabs\u002F2502.11089)\n\nNSA 参考实现：\n[原生稀疏注意力 Triton](https:\u002F\u002Fgithub.com\u002FXunhaoLai\u002Fnative-sparse-attention-triton)","# Flash-Sparse-Attention 快速上手指南\n\nFlash-Sparse-Attention (FSA) 是一种针对原生稀疏注意力（NSA）的高效内核实现，旨在现代 NVIDIA GPU 上加速大语言模型（LLM）的训练与推理，特别优化了小 GQA 组大小场景下的性能。\n\n## 环境准备\n\n在开始之前，请确保您的系统满足以下要求：\n\n*   **硬件**：NVIDIA Ampere 或 Hopper 架构 GPU（如 A100, H100, H20 等）。\n*   **软件依赖**：\n    *   PyTorch >= 2.4\n    *   Triton >= 3.0\n    *   transformers >= 4.45.0\n    *   datasets >= 3.3.0\n    *   accelerate >= 1.9.0\n    *   flash-attn == 2.6.3\n*   **数据类型**：支持 fp16 和 bf16。\n*   **头维度**：Query、Key、Value 的头维度需一致且 \u003C= 256。\n\n> **提示**：国内开发者建议使用清华源或阿里源加速 Python 包安装。\n\n## 安装步骤\n\n1.  克隆仓库（如果尚未克隆）：\n    ```bash\n    git clone https:\u002F\u002Fgithub.com\u002Fyour-repo\u002FFlash-Sparse-Attention.git\n    cd Flash-Sparse-Attention\n    ```\n\n2.  安装依赖项：\n    ```bash\n    pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n    ```\n\n    *如果 `requirements.txt` 未包含所有特定版本约束，也可手动安装核心依赖：*\n    ```bash\n    pip install torch>=2.4 triton>=3.0 transformers>=4.45.0 datasets>=3.3.0 accelerate>=1.9.0 flash-attn==2.6.3 -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n    ```\n\n## 基本使用\n\n以下是实例化 `FlashSparseAttention` 模块并执行一次前向传播与反向传播的最小示例。\n\n```Python\nimport torch\nfrom fsa.module.fsa import FlashSparseAttention, RopeConfig\n\n# 实例化 FSA 模块\nFSA = (\n    FlashSparseAttention(\n        hidden_size=4096,\n        num_q_heads=4,\n        num_kv_heads=4,\n        head_dim=128,\n        kernel_size=32,\n        kernel_stride=16,\n        block_size=64,\n        topk=16,\n        init_blocks=1,\n        local_blocks=2,\n        window_size=512,\n        rope_config=RopeConfig(\n            max_position_embeddings=131072,\n            head_dim=128,\n            rope_theta=500000,\n            rope_scaling={\n                \"factor\": 8.0,\n                \"high_freq_factor\": 4.0,\n                \"low_freq_factor\": 1.0,\n                \"original_max_position_embeddings\": 8192,\n                \"rope_type\": \"llama3\",\n            },\n        ),\n    )\n    .cuda()\n    .to(torch.bfloat16)\n)\n\n# 准备输入数据\n# 模拟两个序列的长度：65536 和 32768\nseqlens = torch.LongTensor([65536, 32768]).int().cuda()\n\n# 计算累积序列长度 (cu_seqlens)\ncu_seqlens = torch.cat(\n    [\n        torch.zeros(1, dtype=torch.int32, device=\"cuda\"),\n        torch.cumsum(seqlens, dim=0),\n    ],\n    dim=0,\n).to(torch.int32)\n\n# 生成随机输入张量\nx = torch.randn(cu_seqlens[-1], 4096, device=\"cuda\", dtype=torch.bfloat16)\n\n# 前向传播\ny = FSA(x, cu_seqlens)\n\n# 模拟损失计算与反向传播\nloss = (y * torch.randn_like(y)).sum(-1).mean()\nloss.backward()\n```\n\n**集成到训练流程：**\n若需在现有 LLM 中使用 FSA，只需将原有的注意力模块替换为 `FlashSparseAttention`，并确保在数据加载阶段正确计算 `cu_seqlens` 传入模型即可。详细集成示例可参考仓库中的 `test\u002Ftrain.py`。","某大模型团队正在训练一款支持 64K 超长上下文的法律文档分析模型，需处理海量卷宗并保证推理实时性。\n\n### 没有 Flash-Sparse-Attention 时\n- **显存带宽浪费严重**：原生稀疏注意力（NSA）在处理小分组查询注意力（GQA）时，为满足 GPU 矩阵乘法维度要求被迫填充大量无效数据，导致内存访问量激增。\n- **计算效率低下**：由于外层循环遍历查询令牌，内层遍历 KV 块，硬件无法有效并行化，导致在 Hopper 架构显卡上算力利用率不足。\n- **原子操作瓶颈**：跨 KV 块累积注意力结果时依赖耗时的 `atomic` 加法操作，成为长序列训练中的主要延迟来源。\n- **训练成本高昂**：上述问题叠加使得长文本训练速度缓慢，单次实验周期长达数周，严重拖慢模型迭代节奏。\n\n### 使用 Flash-Sparse-Attention 后\n- **消除无效计算**：Flash-Sparse-Attention 通过交换循环顺序，将 KV 块置于外循环，彻底避免了为凑齐矩阵维度而进行的无效数据填充，大幅降低内存访问体积。\n- **内核级加速**：采用解耦的三阶段内核设计（主计算、归约、在线 Softmax），完美适配现代 GPU 的 Warp 级指令，显著提升并行计算效率。\n- **移除原子锁**：创新地利用缓冲区存储部分结果后再归约，完全移除了昂贵的 `atomic` 加法操作，解决了长序列下的同步阻塞问题。\n- **端到端性能飞跃**：在 64K 序列长度下，训练与推理延迟显著降低，使原本需要数周的实验缩短至几天完成，极大提升了研发效率。\n\nFlash-Sparse-Attention 通过重构底层算子逻辑，让原生稀疏注意力技术在现代 GPU 上真正实现了“既快又省”，成为长上下文大模型落地的关键加速器。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FRelaxed-System-Lab_Flash-Sparse-Attention_58c1a648.png","Relaxed-System-Lab","Relaxed System Lab","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FRelaxed-System-Lab_4980df17.png","The research lab lead by Binhang Yuan @ CSE HKUST",null,"biyuan@cse.ust.hk","https:\u002F\u002Fgithub.com\u002FRelaxed-System-Lab",[80,84],{"name":81,"color":82,"percentage":83},"Python","#3572A5",94.6,{"name":85,"color":86,"percentage":87},"Shell","#89e051",5.4,747,15,"2026-04-17T12:39:33","Apache-2.0",4,"未说明","必需 NVIDIA GPU (Ampere 或 Hopper 架构，如 A100, H100, H200)，显存大小未明确说明但需支持长序列（如 64K），依赖 CUDA 环境以运行 Triton 和 PyTorch",{"notes":96,"python":93,"dependencies":97},"该工具专为现代高性能 NVIDIA GPU 优化，特别适用于 GQA 组大小小于 8 的场景（此时性能优于原生 NSA 实现）；若 GQA 组大小大于等于 8，通常会自动回退到原始 NSA 实现以获得更好性能。支持 fp16 和 bf16 数据类型，头维度需一致且不超过 256。目前主要经过训练和推理（prefill 阶段）的测试。",[98,99,100,101,102,103],"torch>=2.4","triton>=3.0","transformers>=4.45.0","datasets>=3.3.0","accelerate>=1.9.0","flash-attn==2.6.3",[14,35],[106,107,108],"kernels","large-language-models","machine-learning-systems","2026-03-27T02:49:30.150509","2026-04-18T11:08:45.642134",[],[]]