flashtopk 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. flashtopk-0.1.0/LICENSE +201 -0
  2. flashtopk-0.1.0/NOTICE +19 -0
  3. flashtopk-0.1.0/PKG-INFO +170 -0
  4. flashtopk-0.1.0/README.md +136 -0
  5. flashtopk-0.1.0/flashtopk/__init__.py +15 -0
  6. flashtopk-0.1.0/flashtopk/kernels/__init__.py +3 -0
  7. flashtopk-0.1.0/flashtopk/kernels/common.py +281 -0
  8. flashtopk-0.1.0/flashtopk/kernels/launch.py +825 -0
  9. flashtopk-0.1.0/flashtopk/kernels/prologue.py +232 -0
  10. flashtopk-0.1.0/flashtopk/kernels/prune_sm100.py +1162 -0
  11. flashtopk-0.1.0/flashtopk/kernels/prune_sm90.py +426 -0
  12. flashtopk-0.1.0/flashtopk/kernels/refine_sm100.py +686 -0
  13. flashtopk-0.1.0/flashtopk/kernels/refine_sm90.py +427 -0
  14. flashtopk-0.1.0/flashtopk/kernels/scan_sm100.py +1106 -0
  15. flashtopk-0.1.0/flashtopk/kernels/scan_sm90.py +544 -0
  16. flashtopk-0.1.0/flashtopk/kernels/seed_prep.py +158 -0
  17. flashtopk-0.1.0/flashtopk/kernels/selection.py +1232 -0
  18. flashtopk-0.1.0/flashtopk/kernels/simt.py +329 -0
  19. flashtopk-0.1.0/flashtopk/kernels/triage.py +116 -0
  20. flashtopk-0.1.0/flashtopk/ops.py +30 -0
  21. flashtopk-0.1.0/flashtopk/plan.py +604 -0
  22. flashtopk-0.1.0/flashtopk/recovery.py +106 -0
  23. flashtopk-0.1.0/flashtopk/topk.py +400 -0
  24. flashtopk-0.1.0/flashtopk.egg-info/PKG-INFO +170 -0
  25. flashtopk-0.1.0/flashtopk.egg-info/SOURCES.txt +34 -0
  26. flashtopk-0.1.0/flashtopk.egg-info/dependency_links.txt +1 -0
  27. flashtopk-0.1.0/flashtopk.egg-info/requires.txt +7 -0
  28. flashtopk-0.1.0/flashtopk.egg-info/top_level.txt +1 -0
  29. flashtopk-0.1.0/pyproject.toml +51 -0
  30. flashtopk-0.1.0/setup.cfg +4 -0
  31. flashtopk-0.1.0/tests/test_bounds.py +53 -0
  32. flashtopk-0.1.0/tests/test_exact.py +289 -0
  33. flashtopk-0.1.0/tests/test_properties.py +70 -0
  34. flashtopk-0.1.0/tests/test_reference.py +59 -0
  35. flashtopk-0.1.0/tests/test_reproduce.py +141 -0
  36. flashtopk-0.1.0/tests/test_structure.py +278 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 the FlashTopK authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
flashtopk-0.1.0/NOTICE ADDED
@@ -0,0 +1,19 @@
1
+ FlashTopK
2
+ Copyright 2026 the FlashTopK authors
3
+
4
+ This product includes software derived from the following projects, each licensed under the Apache License,
5
+ Version 2.0:
6
+
7
+ * FlashInfer (https://github.com/flashinfer-ai/flashinfer), Copyright (c) 2025 by FlashInfer team.
8
+ flashtopk/kernels/scan_sm100.py, and through it the pipelines of flashtopk/kernels/prune_sm100.py and
9
+ flashtopk/kernels/refine_sm100.py, are derived from FlashInfer's selective-logits candidate kernel
10
+ (flashinfer/attn_scores/kernels/fp8_paged_mqa_logits.py), itself adapted from TensorRT-LLM.
11
+
12
+ * TensorRT-LLM (https://github.com/NVIDIA/TensorRT-LLM), Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES.
13
+ Its CuTe DSL FP8 paged MQA logits kernel (fp8_paged_mqa_logits.py under tensorrt_llm/_torch/cute_dsl_kernels/),
14
+ by way of FlashInfer.
15
+
16
+ * LiteTopK (https://github.com/Heisenberg-Yin/LiteTopK). The gate calibration (flashtopk/kernels/seed_prep.py) and the
17
+ candidate selection (flashtopk/kernels/selection.py) follow LiteTopK's seed-prep and compact top-k kernels.
18
+
19
+ The score upper bound of key pruning (flashtopk/plan.py) follows DoSA (arXiv 2610.13990, sections 2.2-2.5).
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: flashtopk
3
+ Version: 0.1.0
4
+ Summary: Fast, exact, deterministic fused top-k selection for learned sparse attention
5
+ Author: Tencent Hunyuan
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Tencent-Hunyuan/FlashTopK
8
+ Project-URL: Repository, https://github.com/Tencent-Hunyuan/FlashTopK
9
+ Project-URL: Documentation, https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/api.md
10
+ Project-URL: Issues, https://github.com/Tencent-Hunyuan/FlashTopK/issues
11
+ Keywords: sparse-attention,topk,dsa,cuda,cutlass,triton,llm
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ License-File: NOTICE
27
+ Requires-Dist: torch>=2.6
28
+ Requires-Dist: triton>=3.3
29
+ Requires-Dist: nvidia-cutlass-dsl>=4.5
30
+ Requires-Dist: apache-tvm-ffi
31
+ Provides-Extra: test
32
+ Requires-Dist: pytest; extra == "test"
33
+ Dynamic: license-file
34
+
35
+ ![FlashTopK, Tencent Hy](https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/banner.png)
36
+
37
+ # FlashTopK: Fast Fused Top-k Selection for Sparse Attention Training and Inference
38
+
39
+ <p align="center">
40
+ <a href="https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache%202.0-blue"></a>
41
+ <a href="https://arxiv.org/abs/2610.32057"><img alt="arXiv" src="https://img.shields.io/badge/arXiv-2610.32057-b31b1b"></a>
42
+ </p>
43
+
44
+ FlashTopK is a fast, exact and deterministic fused top-k selection kernel for learned sparse attention, in both training and inference.
45
+
46
+ On a full prefill, FlashTopK is 1.7-3.3x faster than dense scoring + FlashInfer top-k (DeepGEMM / cuDNN scoring) on trained indexers, and 1.2-2.0x faster on untrained indexers.
47
+
48
+ ## News
49
+
50
+ [2026/10] We have released **[HyScale: Scaling Long-Context Training for Learned Sparse Attention](https://arxiv.org/abs/2610.32057)**.
51
+
52
+ ## Highlights
53
+
54
+ - **Fast:** the fastest open-source implementation.
55
+ - **Robust:** stays fast on trained and untrained indexers. Adaptive key pruning decides per call whether to skip keys by a score bound.
56
+ - **Exact:** the true top-k. Rows the sampled threshold misses are rescored on the GPU.
57
+ - **Deterministic:** the same bits on every run. Ties at the k-th score keep the smallest key indices.
58
+ - **CP-compatible:** each row's threshold comes from a strided sample of its own window, so [context parallelism](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/api.md#training-and-context-parallelism) needs no selection from another rank.
59
+
60
+ ## Support
61
+
62
+ | Sparse attention | Models | GPUs | Operands |
63
+ |---|---|---|---|
64
+ | Token-level selection, as in [DeepSeek Sparse Attention (DSA)](https://arxiv.org/abs/2512.02556) | [GLM-5.1](https://huggingface.co/zai-org/GLM-5.1), [GLM-5.2](https://huggingface.co/zai-org/GLM-5.2), [GLM-5.3](https://huggingface.co/zai-org/GLM-5.3), [GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash), [Hy4-preview](https://huggingface.co/tencent/Hy4-preview): indexers of 32 heads × 128 | NVIDIA Hopper (SM90): H800, H20, H100, H200; NVIDIA SM100 and SM103 | FP8 or BF16, `topk` up to 4096 |
65
+
66
+ [Hardware and model support](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/hardware.md) lists which GPUs are tuned.
67
+
68
+ ## Getting started
69
+
70
+ ### Install
71
+
72
+ FlashTopK needs Python 3.10+, PyTorch 2.6+, Triton 3.3+ and CuTe DSL (`nvidia-cutlass-dsl`) 4.5+. SM100 GPUs also need a CUDA 12.8+ driver.
73
+
74
+ ```bash
75
+ pip install flashtopk # torch >= 2.6, triton >= 3.3, nvidia-cutlass-dsl >= 4.5, apache-tvm-ffi
76
+ ```
77
+
78
+ Or install from source:
79
+
80
+ ```bash
81
+ pip install -e .
82
+ pip install -e .[test] # pytest for the test suite
83
+ ```
84
+
85
+ ### Quick start
86
+
87
+ For each query `t`, FlashTopK selects the `topk` keys `s` of its window `[ks[t], ke[t])` with the largest indexer score:
88
+
89
+ ```math
90
+ I_{t,s} = \sigma_s \sum_{h=1}^{H_I} w_{t,h}\,\mathrm{ReLU}\big(\mathbf{q}_{t,h}^{\top}\mathbf{k}_s\big)
91
+ ```
92
+
93
+ Here **q**<sub>t,h</sub> is head h of `q[t]`, **k**<sub>s</sub> is `kv[s]`, w<sub>t,h</sub> is head h's weight in `weights[t]`, σ<sub>s</sub> is `kv_scales[s]` (1 for BF16 keys) and H<sub>I</sub> = 32 is the number of heads. A causal prefill chunk of 4096 queries over 128K FP8 keys:
94
+
95
+ ```python
96
+ import torch
97
+ import flashtopk
98
+
99
+ num_q, seq_len_kv = 4096, 128 * 1024
100
+ q = torch.randn(num_q, 32, 128, device="cuda").to(torch.float8_e4m3fn) # 32 heads of dimension 128
101
+ kv = torch.randn(seq_len_kv, 128, device="cuda").to(torch.float8_e4m3fn) # one key per token
102
+ kv_scales = torch.rand(seq_len_kv, device="cuda") * 0.02 + 0.01 # FP8 keys need per-key scales
103
+ weights = torch.randn(num_q, 32, device="cuda") * 0.1 # per-head weights, float32
104
+
105
+ # The queries are the last num_q tokens: query i sees keys [0, seq_len_kv - num_q + i + 1).
106
+ ke = torch.arange(seq_len_kv - num_q + 1, seq_len_kv + 1, device="cuda", dtype=torch.int32)
107
+ ks = torch.zeros_like(ke)
108
+
109
+ indices = flashtopk.select(q, kv, weights, ks, ke, kv_scales, topk=2048) # [4096, 2048] int32
110
+ ```
111
+
112
+ The first call in a process compiles the kernels it needs, about 15 seconds in all. `Selector.plan()` compiles them up front.
113
+
114
+ ### Usage
115
+
116
+ ```python
117
+ flashtopk.select(q, kv, weights, ks, ke, kv_scales=None, topk=2048, ...) # indices; return_scores=True adds scores
118
+ selector = flashtopk.Selector(topk=2048, dtype=...).plan(max_rows, max_kv) # owns the workspace, compiles up front
119
+ selector.run(q, kv, weights, ks, ke, kv_scales) # select's arguments and outputs
120
+ torch.ops.flashtopk.select(...) # select as a custom op, for torch.compile
121
+ flashtopk.windows_from_cu_seqlens(cu_seqlens_q, cu_seqlens_k) # causal windows of packed sequences
122
+ ```
123
+
124
+ The [API reference](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/api.md) covers every argument, the workspace, `last_info`, configuration and training with context parallelism.
125
+
126
+ ## Performance
127
+
128
+ Speedup of one full prefill (query rows = keys = the sequence length) over dense scoring + FlashInfer top-k on H800, with FP8 or BF16 operands. The [performance report](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/performance.md) has H20 and SM100 as well.
129
+
130
+ ### Trained indexer
131
+
132
+ <p align="center"><img src="https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/performance_trained_h800.png" alt="FlashTopK against public top-k selectors on a trained indexer, H800" width="100%"></p>
133
+
134
+ FlashTopK is the fastest at every length, and its lead grows with the length.
135
+
136
+ ### Untrained indexer
137
+
138
+ <p align="center"><img src="https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/performance_untrained_h800.png" alt="FlashTopK against public top-k selectors on an untrained indexer, H800" width="100%"></p>
139
+
140
+ The score bound skips few keys, so FlashTopK mostly scans; it still leads at every length.
141
+
142
+ The [performance report](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/performance.md) describes the setup and the methods compared. It also has the results on random indexer weights and keys. [`reproduce/`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/reproduce/README.md) provides pinned setup, inputs, comparison benchmarks and scripts to regenerate the figures.
143
+
144
+ ## Roadmap
145
+
146
+ - Block-level learned sparse attention, such as CSA in [DeepSeek-V4](https://arxiv.org/abs/2606.19348) and QSA in [Qwen3.8-Flash-Next](https://arxiv.org/abs/2608.30320).
147
+ - Paged KV cache; today the keys must be contiguous, with one contiguous window per query row.
148
+ - Indexers with other head counts, such as the 64 heads of DeepSeek-V3.2.
149
+
150
+ ## License
151
+
152
+ FlashTopK is released under the Apache License 2.0. See [`LICENSE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/LICENSE) and [`NOTICE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/NOTICE) for details.
153
+
154
+ ## Acknowledgments
155
+
156
+ FlashTopK builds on [FlashInfer](https://github.com/flashinfer-ai/flashinfer) and [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) (the SM100 scan pipeline, which the pruning and refine kernels share), [LiteTopK](https://github.com/Heisenberg-Yin/LiteTopK) (gate calibration and candidate selection) and [DoSA](https://arxiv.org/abs/2610.13990) (the score bound of key pruning). [`NOTICE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/NOTICE) lists the files each part derives from.
157
+
158
+ ## Citation
159
+
160
+ ```bibtex
161
+ @misc{deng2026hyscale,
162
+ title = {HyScale: Scaling Long-Context Training for Learned Sparse Attention},
163
+ author = {Yangshen Deng and Xinjing Huang and Yulong Wang and Yunzhuo Liu and Jun Hu and Shuyong Tan and Chun-Chih Tseng and Mingji Han and Ray Ying and Key Zhang and Luo Mai},
164
+ year = {2026},
165
+ eprint = {2610.32057},
166
+ archivePrefix = {arXiv},
167
+ primaryClass = {cs.AI},
168
+ url = {https://arxiv.org/abs/2610.32057},
169
+ }
170
+ ```
@@ -0,0 +1,136 @@
1
+ ![FlashTopK, Tencent Hy](https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/banner.png)
2
+
3
+ # FlashTopK: Fast Fused Top-k Selection for Sparse Attention Training and Inference
4
+
5
+ <p align="center">
6
+ <a href="https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache%202.0-blue"></a>
7
+ <a href="https://arxiv.org/abs/2610.32057"><img alt="arXiv" src="https://img.shields.io/badge/arXiv-2610.32057-b31b1b"></a>
8
+ </p>
9
+
10
+ FlashTopK is a fast, exact and deterministic fused top-k selection kernel for learned sparse attention, in both training and inference.
11
+
12
+ On a full prefill, FlashTopK is 1.7-3.3x faster than dense scoring + FlashInfer top-k (DeepGEMM / cuDNN scoring) on trained indexers, and 1.2-2.0x faster on untrained indexers.
13
+
14
+ ## News
15
+
16
+ [2026/10] We have released **[HyScale: Scaling Long-Context Training for Learned Sparse Attention](https://arxiv.org/abs/2610.32057)**.
17
+
18
+ ## Highlights
19
+
20
+ - **Fast:** the fastest open-source implementation.
21
+ - **Robust:** stays fast on trained and untrained indexers. Adaptive key pruning decides per call whether to skip keys by a score bound.
22
+ - **Exact:** the true top-k. Rows the sampled threshold misses are rescored on the GPU.
23
+ - **Deterministic:** the same bits on every run. Ties at the k-th score keep the smallest key indices.
24
+ - **CP-compatible:** each row's threshold comes from a strided sample of its own window, so [context parallelism](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/api.md#training-and-context-parallelism) needs no selection from another rank.
25
+
26
+ ## Support
27
+
28
+ | Sparse attention | Models | GPUs | Operands |
29
+ |---|---|---|---|
30
+ | Token-level selection, as in [DeepSeek Sparse Attention (DSA)](https://arxiv.org/abs/2512.02556) | [GLM-5.1](https://huggingface.co/zai-org/GLM-5.1), [GLM-5.2](https://huggingface.co/zai-org/GLM-5.2), [GLM-5.3](https://huggingface.co/zai-org/GLM-5.3), [GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash), [Hy4-preview](https://huggingface.co/tencent/Hy4-preview): indexers of 32 heads × 128 | NVIDIA Hopper (SM90): H800, H20, H100, H200; NVIDIA SM100 and SM103 | FP8 or BF16, `topk` up to 4096 |
31
+
32
+ [Hardware and model support](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/hardware.md) lists which GPUs are tuned.
33
+
34
+ ## Getting started
35
+
36
+ ### Install
37
+
38
+ FlashTopK needs Python 3.10+, PyTorch 2.6+, Triton 3.3+ and CuTe DSL (`nvidia-cutlass-dsl`) 4.5+. SM100 GPUs also need a CUDA 12.8+ driver.
39
+
40
+ ```bash
41
+ pip install flashtopk # torch >= 2.6, triton >= 3.3, nvidia-cutlass-dsl >= 4.5, apache-tvm-ffi
42
+ ```
43
+
44
+ Or install from source:
45
+
46
+ ```bash
47
+ pip install -e .
48
+ pip install -e .[test] # pytest for the test suite
49
+ ```
50
+
51
+ ### Quick start
52
+
53
+ For each query `t`, FlashTopK selects the `topk` keys `s` of its window `[ks[t], ke[t])` with the largest indexer score:
54
+
55
+ ```math
56
+ I_{t,s} = \sigma_s \sum_{h=1}^{H_I} w_{t,h}\,\mathrm{ReLU}\big(\mathbf{q}_{t,h}^{\top}\mathbf{k}_s\big)
57
+ ```
58
+
59
+ Here **q**<sub>t,h</sub> is head h of `q[t]`, **k**<sub>s</sub> is `kv[s]`, w<sub>t,h</sub> is head h's weight in `weights[t]`, σ<sub>s</sub> is `kv_scales[s]` (1 for BF16 keys) and H<sub>I</sub> = 32 is the number of heads. A causal prefill chunk of 4096 queries over 128K FP8 keys:
60
+
61
+ ```python
62
+ import torch
63
+ import flashtopk
64
+
65
+ num_q, seq_len_kv = 4096, 128 * 1024
66
+ q = torch.randn(num_q, 32, 128, device="cuda").to(torch.float8_e4m3fn) # 32 heads of dimension 128
67
+ kv = torch.randn(seq_len_kv, 128, device="cuda").to(torch.float8_e4m3fn) # one key per token
68
+ kv_scales = torch.rand(seq_len_kv, device="cuda") * 0.02 + 0.01 # FP8 keys need per-key scales
69
+ weights = torch.randn(num_q, 32, device="cuda") * 0.1 # per-head weights, float32
70
+
71
+ # The queries are the last num_q tokens: query i sees keys [0, seq_len_kv - num_q + i + 1).
72
+ ke = torch.arange(seq_len_kv - num_q + 1, seq_len_kv + 1, device="cuda", dtype=torch.int32)
73
+ ks = torch.zeros_like(ke)
74
+
75
+ indices = flashtopk.select(q, kv, weights, ks, ke, kv_scales, topk=2048) # [4096, 2048] int32
76
+ ```
77
+
78
+ The first call in a process compiles the kernels it needs, about 15 seconds in all. `Selector.plan()` compiles them up front.
79
+
80
+ ### Usage
81
+
82
+ ```python
83
+ flashtopk.select(q, kv, weights, ks, ke, kv_scales=None, topk=2048, ...) # indices; return_scores=True adds scores
84
+ selector = flashtopk.Selector(topk=2048, dtype=...).plan(max_rows, max_kv) # owns the workspace, compiles up front
85
+ selector.run(q, kv, weights, ks, ke, kv_scales) # select's arguments and outputs
86
+ torch.ops.flashtopk.select(...) # select as a custom op, for torch.compile
87
+ flashtopk.windows_from_cu_seqlens(cu_seqlens_q, cu_seqlens_k) # causal windows of packed sequences
88
+ ```
89
+
90
+ The [API reference](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/api.md) covers every argument, the workspace, `last_info`, configuration and training with context parallelism.
91
+
92
+ ## Performance
93
+
94
+ Speedup of one full prefill (query rows = keys = the sequence length) over dense scoring + FlashInfer top-k on H800, with FP8 or BF16 operands. The [performance report](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/performance.md) has H20 and SM100 as well.
95
+
96
+ ### Trained indexer
97
+
98
+ <p align="center"><img src="https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/performance_trained_h800.png" alt="FlashTopK against public top-k selectors on a trained indexer, H800" width="100%"></p>
99
+
100
+ FlashTopK is the fastest at every length, and its lead grows with the length.
101
+
102
+ ### Untrained indexer
103
+
104
+ <p align="center"><img src="https://raw.githubusercontent.com/Tencent-Hunyuan/FlashTopK/main/assets/performance_untrained_h800.png" alt="FlashTopK against public top-k selectors on an untrained indexer, H800" width="100%"></p>
105
+
106
+ The score bound skips few keys, so FlashTopK mostly scans; it still leads at every length.
107
+
108
+ The [performance report](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/docs/performance.md) describes the setup and the methods compared. It also has the results on random indexer weights and keys. [`reproduce/`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/reproduce/README.md) provides pinned setup, inputs, comparison benchmarks and scripts to regenerate the figures.
109
+
110
+ ## Roadmap
111
+
112
+ - Block-level learned sparse attention, such as CSA in [DeepSeek-V4](https://arxiv.org/abs/2606.19348) and QSA in [Qwen3.8-Flash-Next](https://arxiv.org/abs/2608.30320).
113
+ - Paged KV cache; today the keys must be contiguous, with one contiguous window per query row.
114
+ - Indexers with other head counts, such as the 64 heads of DeepSeek-V3.2.
115
+
116
+ ## License
117
+
118
+ FlashTopK is released under the Apache License 2.0. See [`LICENSE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/LICENSE) and [`NOTICE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/NOTICE) for details.
119
+
120
+ ## Acknowledgments
121
+
122
+ FlashTopK builds on [FlashInfer](https://github.com/flashinfer-ai/flashinfer) and [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) (the SM100 scan pipeline, which the pruning and refine kernels share), [LiteTopK](https://github.com/Heisenberg-Yin/LiteTopK) (gate calibration and candidate selection) and [DoSA](https://arxiv.org/abs/2610.13990) (the score bound of key pruning). [`NOTICE`](https://github.com/Tencent-Hunyuan/FlashTopK/blob/main/NOTICE) lists the files each part derives from.
123
+
124
+ ## Citation
125
+
126
+ ```bibtex
127
+ @misc{deng2026hyscale,
128
+ title = {HyScale: Scaling Long-Context Training for Learned Sparse Attention},
129
+ author = {Yangshen Deng and Xinjing Huang and Yulong Wang and Yunzhuo Liu and Jun Hu and Shuyong Tan and Chun-Chih Tseng and Mingji Han and Ray Ying and Key Zhang and Luo Mai},
130
+ year = {2026},
131
+ eprint = {2610.32057},
132
+ archivePrefix = {arXiv},
133
+ primaryClass = {cs.AI},
134
+ url = {https://arxiv.org/abs/2610.32057},
135
+ }
136
+ ```
@@ -0,0 +1,15 @@
1
+ # Copyright (c) 2026 the FlashTopK authors. Licensed under the Apache License, Version 2.0.
2
+ """FlashTopK: exact, deterministic top-k selection for learned sparse attention.
3
+
4
+ selector = flashtopk.Selector(topk=2048, dtype=torch.float8_e4m3fn).plan(max_rows, max_kv)
5
+ indices = selector.run(q, kv, weights, ks, ke, kv_scales)
6
+
7
+ or flashtopk.select(...) for the same with a cached selector. See topk.py for the score and the output order.
8
+ """
9
+
10
+ from . import ops # registers torch.ops.flashtopk.select
11
+ from .topk import DEFAULT_CHUNK_SIZE, Info, Selector, select, supported, windows_from_cu_seqlens, workspace_bytes
12
+
13
+ __all__ = ["DEFAULT_CHUNK_SIZE", "Info", "Selector", "ops", "select", "supported", "windows_from_cu_seqlens",
14
+ "workspace_bytes"]
15
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ # Copyright (c) 2026 the FlashTopK authors. Licensed under the Apache License, Version 2.0.
2
+ """CuTe DSL kernels: the scan, key pruning (mask and refine), calibration, selection and recovery, for SM90 and
3
+ SM100. ``common`` holds what both architectures share, ``launch`` their host side."""