flashtopk 0.1.0__py3-none-any.whl

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.
flashtopk/__init__.py ADDED
@@ -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."""
@@ -0,0 +1,281 @@
1
+ # Copyright (c) 2026 the FlashTopK authors. Licensed under the Apache License, Version 2.0.
2
+ """What the kernels of every architecture share: the indexer's shape, the tiling the host side plans with, and PTX
3
+ helpers. Every float operation names its rounding, so no compiler choice (contraction, fast math) can change a bit."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import cutlass
8
+ import cutlass.cute as cute
9
+ from cutlass import Float32, Int32
10
+ from cutlass._mlir.dialects import arith, llvm, math
11
+ from cutlass.cutlass_dsl import dsl_user_op
12
+
13
+ NUM_HEADS = 32
14
+ HEAD_DIM = 128
15
+ NEXT_N = 8 # query rows of a scan tile
16
+ BLOCK_KV = 128 # keys of a KV block: KV splits and the pruning mask are counted in these
17
+ PRUNE_BLOCK_Q = 16 # query rows of a row-split pruning tile (SM90, SM100 16-col & FP8 24-col)
18
+ PRUNE_COLS = 16 # default columns of the pruning operand
19
+ PRUNE_COLS_24 = 24 # tighter 24-column pruning operand (SM100: 22 retained + 2 agg; 16-row FP8, 8-row BF16)
20
+ REFINE_BLOCK_Q = 8 # query rows of a refine tile
21
+
22
+
23
+ def prune_block_q(cols: int = PRUNE_COLS, bf16: bool = False) -> int:
24
+ """Query rows per SM100 pruning tile (8 for BF16 24-col key-split, 16 for row-split modes)."""
25
+ return REFINE_BLOCK_Q if (cols == PRUNE_COLS_24 and bf16) else PRUNE_BLOCK_Q
26
+
27
+
28
+ @dsl_user_op
29
+ def store_global_b32(address, value, *, loc=None, ip=None) -> None:
30
+ llvm.inline_asm(
31
+ None,
32
+ [cutlass.Int64(address).ir_value(loc=loc, ip=ip), Int32(value).ir_value(loc=loc, ip=ip)],
33
+ "st.global.b32 [$0], $1;",
34
+ "l,r",
35
+ has_side_effects=True,
36
+ is_align_stack=False,
37
+ asm_dialect=llvm.AsmDialect.AD_ATT,
38
+ loc=loc,
39
+ ip=ip,
40
+ )
41
+
42
+
43
+ @dsl_user_op
44
+ def store_global_v4_b32(address, v0, v1, v2, v3, *, loc=None, ip=None) -> None:
45
+ """One 16-byte global vector store through a raw byte address."""
46
+ llvm.inline_asm(
47
+ None,
48
+ [
49
+ cutlass.Int64(address).ir_value(loc=loc, ip=ip),
50
+ Int32(v0).ir_value(loc=loc, ip=ip),
51
+ Int32(v1).ir_value(loc=loc, ip=ip),
52
+ Int32(v2).ir_value(loc=loc, ip=ip),
53
+ Int32(v3).ir_value(loc=loc, ip=ip),
54
+ ],
55
+ "st.global.v4.b32 [$0], {$1, $2, $3, $4};",
56
+ "l,r,r,r,r",
57
+ has_side_effects=True,
58
+ is_align_stack=False,
59
+ asm_dialect=llvm.AsmDialect.AD_ATT,
60
+ loc=loc,
61
+ ip=ip,
62
+ )
63
+
64
+
65
+ @dsl_user_op
66
+ def atomic_add_global_i32(address, value, *, loc=None, ip=None) -> Int32:
67
+ return Int32(
68
+ llvm.inline_asm(
69
+ Int32.mlir_type,
70
+ [cutlass.Int64(address).ir_value(loc=loc, ip=ip), Int32(value).ir_value(loc=loc, ip=ip)],
71
+ "atom.global.add.u32 $0, [$1], $2;",
72
+ "=r,l,r",
73
+ has_side_effects=True,
74
+ is_align_stack=False,
75
+ asm_dialect=llvm.AsmDialect.AD_ATT,
76
+ loc=loc,
77
+ ip=ip,
78
+ )
79
+ )
80
+
81
+
82
+ @dsl_user_op
83
+ def select_i32(predicate, true_value, false_value, *, loc=None, ip=None):
84
+ return Int32(
85
+ arith.select(
86
+ cutlass.Boolean(predicate).ir_value(loc=loc, ip=ip),
87
+ Int32(true_value).ir_value(loc=loc, ip=ip),
88
+ Int32(false_value).ir_value(loc=loc, ip=ip),
89
+ loc=loc,
90
+ ip=ip,
91
+ )
92
+ )
93
+
94
+
95
+ @dsl_user_op
96
+ def ctz_u32(x, *, loc=None, ip=None) -> Int32:
97
+ """Count trailing zeros of nonzero uint32 x (2 PTX ops: brev + clz)."""
98
+ return Int32(
99
+ llvm.inline_asm(
100
+ Int32.mlir_type,
101
+ [cutlass.Uint32(x).ir_value(loc=loc, ip=ip)],
102
+ "{ .reg .b32 r; brev.b32 r, $1; clz.b32 $0, r; }",
103
+ "=r,r",
104
+ has_side_effects=False,
105
+ is_align_stack=False,
106
+ asm_dialect=llvm.AsmDialect.AD_ATT,
107
+ loc=loc,
108
+ ip=ip,
109
+ )
110
+ )
111
+
112
+
113
+ @dsl_user_op
114
+ def fp32_to_i32_bits(value, *, loc=None, ip=None) -> Int32:
115
+ return Int32(llvm.bitcast(Int32.mlir_type, Float32(value).ir_value(loc=loc, ip=ip), loc=loc, ip=ip))
116
+
117
+
118
+ @dsl_user_op
119
+ def abs_f32(value, *, loc=None, ip=None) -> Float32:
120
+ return Float32(math.absf(Float32(value).ir_value(loc=loc, ip=ip), loc=loc, ip=ip))
121
+
122
+
123
+ def _f32_asm(op, *values, loc=None, ip=None) -> Float32:
124
+ operands = ",".join(["=f"] + ["f"] * len(values))
125
+ args = ", ".join(f"${i + 1}" for i in range(len(values)))
126
+ return Float32(
127
+ llvm.inline_asm(
128
+ Float32.mlir_type,
129
+ [Float32(v).ir_value(loc=loc, ip=ip) for v in values],
130
+ f"{op} $0, {args};",
131
+ operands,
132
+ has_side_effects=False,
133
+ is_align_stack=False,
134
+ asm_dialect=llvm.AsmDialect.AD_ATT,
135
+ loc=loc,
136
+ ip=ip,
137
+ )
138
+ )
139
+
140
+
141
+ @dsl_user_op
142
+ def mul_rn(a, b, *, loc=None, ip=None) -> Float32:
143
+ return _f32_asm("mul.rn.f32", a, b, loc=loc, ip=ip)
144
+
145
+
146
+ @dsl_user_op
147
+ def sub_rn(a, b, *, loc=None, ip=None) -> Float32:
148
+ return _f32_asm("sub.rn.f32", a, b, loc=loc, ip=ip)
149
+
150
+
151
+ @dsl_user_op
152
+ def add_rn(a, b, *, loc=None, ip=None) -> Float32:
153
+ return _f32_asm("add.rn.f32", a, b, loc=loc, ip=ip)
154
+
155
+
156
+ @dsl_user_op
157
+ def div_rn(a, b, *, loc=None, ip=None) -> Float32:
158
+ return _f32_asm("div.rn.f32", a, b, loc=loc, ip=ip)
159
+
160
+
161
+ @dsl_user_op
162
+ def fma_rn(a, b, c, *, loc=None, ip=None) -> Float32:
163
+ return _f32_asm("fma.rn.f32", a, b, c, loc=loc, ip=ip)
164
+
165
+
166
+ @dsl_user_op
167
+ def fmax(a, b, *, loc=None, ip=None) -> Float32:
168
+ return _f32_asm("max.f32", a, b, loc=loc, ip=ip)
169
+
170
+
171
+ @dsl_user_op
172
+ def fmin(a, b, *, loc=None, ip=None) -> Float32:
173
+ return _f32_asm("min.f32", a, b, loc=loc, ip=ip)
174
+
175
+
176
+ @dsl_user_op
177
+ def i32_to_f32_rn(value, *, loc=None, ip=None) -> Float32:
178
+ return Float32(
179
+ llvm.inline_asm(
180
+ Float32.mlir_type,
181
+ [Int32(value).ir_value(loc=loc, ip=ip)],
182
+ "cvt.rn.f32.s32 $0, $1;",
183
+ "=f,r",
184
+ has_side_effects=False,
185
+ is_align_stack=False,
186
+ asm_dialect=llvm.AsmDialect.AD_ATT,
187
+ loc=loc,
188
+ ip=ip,
189
+ )
190
+ )
191
+
192
+
193
+ @dsl_user_op
194
+ def select_f32(predicate, true_value, false_value, *, loc=None, ip=None):
195
+ return Float32(
196
+ arith.select(
197
+ cutlass.Boolean(predicate).ir_value(loc=loc, ip=ip),
198
+ Float32(true_value).ir_value(loc=loc, ip=ip),
199
+ Float32(false_value).ir_value(loc=loc, ip=ip),
200
+ loc=loc,
201
+ ip=ip,
202
+ )
203
+ )
204
+
205
+
206
+ @cute.jit
207
+ def loose_raw_gate(inv, origin, th_bucket) -> Float32:
208
+ """A raw score below which no key passes the bucket gate
209
+ fma(-inv, raw, c0) < th + 1 (c0 = -origin * inv), a little below the exact edge so rounding
210
+ never excludes one; -inf where the bucket map is degenerate, at most FLT_MAX."""
211
+ c0 = mul_rn(-origin, inv)
212
+ o = i32_to_f32_rn(th_bucket + 1)
213
+ valid = (inv > Float32(0.0)) & (inv <= Float32(3.4e38)) & (abs_f32(c0) <= Float32(3.4e38))
214
+ slack = mul_rn(Float32(2.0**-16), fmax(fmax(abs_f32(c0), abs_f32(o)), Float32(1.0)))
215
+ gate = fmin(div_rn(sub_rn(sub_rn(c0, o), slack), inv), Float32(3.4028234663852886e38))
216
+ return select_f32(valid, gate, Float32(float("-inf")))
217
+
218
+
219
+ @dsl_user_op
220
+ def find_nth_set(word, n, *, loc=None, ip=None) -> Int32:
221
+ """The position of the n-th (1-based) set bit of word, from bit 0."""
222
+ return Int32(
223
+ llvm.inline_asm(
224
+ Int32.mlir_type,
225
+ [Int32(word).ir_value(loc=loc, ip=ip), Int32(n).ir_value(loc=loc, ip=ip)],
226
+ "fns.b32 $0, $1, 0, $2;",
227
+ "=r,r,r",
228
+ has_side_effects=False,
229
+ is_align_stack=False,
230
+ asm_dialect=llvm.AsmDialect.AD_ATT,
231
+ loc=loc,
232
+ ip=ip,
233
+ )
234
+ )
235
+
236
+
237
+ @dsl_user_op
238
+ def cp_async_16(smem_addr, gmem_addr, *, loc=None, ip=None) -> None:
239
+ llvm.inline_asm(
240
+ None,
241
+ [Int32(smem_addr).ir_value(loc=loc, ip=ip), cutlass.Int64(gmem_addr).ir_value(loc=loc, ip=ip)],
242
+ "cp.async.cg.shared.global [$0], [$1], 16;",
243
+ "r,l",
244
+ has_side_effects=True,
245
+ is_align_stack=False,
246
+ asm_dialect=llvm.AsmDialect.AD_ATT,
247
+ loc=loc,
248
+ ip=ip,
249
+ )
250
+
251
+
252
+ @dsl_user_op
253
+ def cp_async_4(smem_addr, gmem_addr, *, loc=None, ip=None) -> None:
254
+ llvm.inline_asm(
255
+ None,
256
+ [Int32(smem_addr).ir_value(loc=loc, ip=ip), cutlass.Int64(gmem_addr).ir_value(loc=loc, ip=ip)],
257
+ "cp.async.ca.shared.global [$0], [$1], 4;",
258
+ "r,l",
259
+ has_side_effects=True,
260
+ is_align_stack=False,
261
+ asm_dialect=llvm.AsmDialect.AD_ATT,
262
+ loc=loc,
263
+ ip=ip,
264
+ )
265
+
266
+
267
+ @dsl_user_op
268
+ def load_global_v4_b32(gmem_addr, *, loc=None, ip=None):
269
+ """A 128-key block's four mask words with one 16-byte load."""
270
+ result = llvm.inline_asm(
271
+ llvm.StructType.get_literal([Int32.mlir_type] * 4),
272
+ [cutlass.Int64(gmem_addr).ir_value(loc=loc, ip=ip)],
273
+ "ld.global.nc.v4.b32 {$0, $1, $2, $3}, [$4];",
274
+ "=r,=r,=r,=r,l",
275
+ has_side_effects=False,
276
+ is_align_stack=False,
277
+ asm_dialect=llvm.AsmDialect.AD_ATT,
278
+ loc=loc,
279
+ ip=ip,
280
+ )
281
+ return tuple(Int32(llvm.extractvalue(Int32.mlir_type, result, [i], loc=loc, ip=ip)) for i in range(4))