susun-123 commited on
Commit
8fc4409
·
verified ·
1 Parent(s): f3b846b

k31_topk-5eff1799: K3.1's top-k cubin with its source and a byte-exact build

Browse files
.gitattributes CHANGED
@@ -283,3 +283,4 @@ blobs/ea5169c1256d29618f6bb310eee0cc7c8ebf64d0bb580c56e9ecbc5fbe21de64 filter=lf
283
  blobs/2d9667fe1f7ae595c36803c564cc9cc2a92dcfd9a0c50bb05e23c7bcff663e71 filter=lfs diff=lfs merge=lfs -text
284
  blobs/ae5ff7f2ed88159f8214e07a2e4fa3bad3add4e471a65b4fdf8326fb7f6c376b filter=lfs diff=lfs merge=lfs -text
285
  blobs/b80a4549fabad26bfc8c3c123be15dda42660f87e98748bace4c409cf794dfec filter=lfs diff=lfs merge=lfs -text
 
 
283
  blobs/2d9667fe1f7ae595c36803c564cc9cc2a92dcfd9a0c50bb05e23c7bcff663e71 filter=lfs diff=lfs merge=lfs -text
284
  blobs/ae5ff7f2ed88159f8214e07a2e4fa3bad3add4e471a65b4fdf8326fb7f6c376b filter=lfs diff=lfs merge=lfs -text
285
  blobs/b80a4549fabad26bfc8c3c123be15dda42660f87e98748bace4c409cf794dfec filter=lfs diff=lfs merge=lfs -text
286
+ k31_topk-5eff1799/kernel.cubin filter=lfs diff=lfs merge=lfs -text
k31_topk-5eff1799/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
k31_topk-5eff1799/build.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Rebuilds kernel.cubin byte for byte: ./build.sh [OUT]
3
+ # Source: github.com/pegainfer-project/kern-k31 a8d49a5, source/k31_topk.cu.
4
+ # nvcc names anonymous-namespace symbols after the source's absolute path, so the build runs in a
5
+ # fixed directory; anywhere else gives the same SASS under another sha256.
6
+ set -eu
7
+ NVCC=${NVCC:-nvcc}
8
+ SHA=5eff17997d5c4bf1ef419e25c3994dd127fbaabd19c2b7ab2064c43cddee97d5
9
+ "$NVCC" --version | grep -q 'V13.0.88' || { echo "build.sh: needs nvcc V13.0.88 (CUDA 13.0)" >&2; exit 1; }
10
+ here=$(cd "$(dirname "$0")" && pwd)
11
+ out=$(realpath -m "${1:-kernel.cubin}")
12
+ dir=/tmp/kern-build
13
+ rm -rf "$dir" && mkdir -p "$dir" && cp "$here"/src/* "$dir"/
14
+ (cd "$dir" && "$NVCC" -cubin -arch=sm_103a -std=c++17 -O3 -o out.cubin k31_topk.cu)
15
+ echo "$SHA $dir/out.cubin" | sha256sum -c - >/dev/null || { echo "build.sh: sha256 differs from $SHA" >&2; exit 1; }
16
+ cp "$dir/out.cubin" "$out"
17
+ echo "$out: $SHA"
k31_topk-5eff1799/kernel.cubin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5eff17997d5c4bf1ef419e25c3994dd127fbaabd19c2b7ab2064c43cddee97d5
3
+ size 409136
k31_topk-5eff1799/src/k31_topk.cu ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // K3.1's indexer top-k: each row's 2048 largest bf16 logits among its first `lens[r]`, as positions in
2
+ // ascending order, -1 past min(lens, 2048). The set is the exact top 2048 that vLLM's
3
+ // top_k_per_row_prefill selects; where equal logits straddle the cut, the smaller positions are taken.
4
+ // Unlike vLLM's kernel, whose output order follows its shared-memory atomics, the result is the same
5
+ // bytes on every run.
6
+ //
7
+ // extern "C" __global__ void k31_topk(const bf16* logits, int stride, const int* lens, int* out);
8
+ // extern "C" __global__ void k31_topk_held(...the same...);
9
+ // grid (rows), block NT, dynamic smem k31_topk_smem (a __device__ int of the module)
10
+ //
11
+ // k31_topk is for P's thousands of rows. k31_topk_held is for D's few rows, each latency-bound: a
12
+ // row of at most HELD_MAX is read once into registers, and from there a histogram finds the cut
13
+ // value and bitmaps of the row place the 2048 (held, below); a longer row takes P's route.
14
+ //
15
+ // A logit is ranked by its key, the bits of the float it widens to ordered as the float is, read in
16
+ // digits: bits 31..20, 19..8, 7..0. A digit's 4096-bin histogram over the keys that share the digits
17
+ // above it finds the bin holding the cut. Once that bin holds at most CAP keys, one read takes every
18
+ // position above it and keeps the bin's (key, position) pairs in shared memory, where a radix select
19
+ // by key and then by position settles the cut.
20
+ //
21
+ // A row of at least SAMPLE_MIN is first tried on a sample: its ends whole and an eighth of the rest in
22
+ // chunks spread evenly, weighted to the row, puts a threshold where 1.5x 2048 keys are expected above
23
+ // it, and one read keeps every key at or above it. The threshold is the bottom of the first digit's
24
+ // bin when the bin and all above it are expected to fit 3/4 of CAP (a bf16 key has 16 bits, so that
25
+ // bin is 16 values wide), the second digit's cut otherwise. When the kept count lands in
26
+ // [2048, CAP], that is the row: one read and an eighth. Otherwise (a sample that misleads) the row
27
+ // takes the exact route above, a read a digit plus the one that collects; a cut inside one exact key
28
+ // held by more than CAP positions takes the ties in position order on one more read.
29
+ //
30
+ // The 2048 positions leave in ascending order: through a bitmap of the row for a row of at most
31
+ // BITMAP_MAX, a radix sort past it.
32
+ #include <cub/cub.cuh>
33
+ #include <cuda_bf16.h>
34
+
35
+ typedef __nv_bfloat16 bf16;
36
+
37
+ __device__ __forceinline__ float4 widen(uint2 v) {
38
+ return make_float4(__uint_as_float(v.x << 16), __uint_as_float(v.x & 0xffff0000u), __uint_as_float(v.y << 16),
39
+ __uint_as_float(v.y & 0xffff0000u));
40
+ }
41
+ // four logits at p (8-byte aligned) widened, through the read-only path or plainly
42
+ __device__ __forceinline__ float4 ld4v(const bf16* p) { return widen(__ldg(reinterpret_cast<const uint2*>(p))); }
43
+ __device__ __forceinline__ float4 ld4(const bf16* p) { return widen(*reinterpret_cast<const uint2*>(p)); }
44
+ __device__ __forceinline__ float lv(const bf16* row, unsigned i) { return __bfloat162float(row[i]); }
45
+
46
+ #define TK 2048
47
+ #define NT 512
48
+ #define BINS 4096
49
+ #define CAP 6144
50
+ #define BPT (BINS / NT)
51
+ #define UNROLL 4
52
+ #define SAMPLE_CHUNK 1024 // logits a sample chunk
53
+ #define SAMPLE_FRAC 8 // the sample is about 1 / SAMPLE_FRAC of the row
54
+ #define HEAD 1024
55
+ #define TAIL 8192
56
+ #define SAMPLE_MIN 32768
57
+
58
+ __device__ __forceinline__ unsigned okey(float x) {
59
+ const unsigned b = __float_as_uint(x + 0.0f); // -0 taken as +0
60
+ return b ^ ((b & 0x80000000u) ? 0xffffffffu : 0x80000000u);
61
+ }
62
+
63
+ // The float whose key k is.
64
+ __device__ __forceinline__ float unkey(unsigned k) {
65
+ return __uint_as_float(k ^ ((k & 0x80000000u) ? 0x80000000u : 0xffffffffu));
66
+ }
67
+
68
+ using Scan = cub::BlockScan<unsigned, NT>;
69
+ using Sort = cub::BlockRadixSort<int, NT, TK / NT>;
70
+
71
+ #define BITMAP_MAX 262144 // rows up to this long order their 2048 by a bitmap, longer ones by a sort
72
+
73
+ #define HELD_MAX 32768
74
+
75
+ struct Smem {
76
+ union {
77
+ unsigned hist[BINS];
78
+ unsigned tie[CAP];
79
+ // held's: the histogram, then each warp's 32 words of digits
80
+ unsigned bits[BITMAP_MAX / 32];
81
+ typename Sort::TempStorage sort;
82
+ } u;
83
+ typename Scan::TempStorage scan;
84
+ unsigned h256[256];
85
+ unsigned wsum[8];
86
+ int sel[TK];
87
+ unsigned ckey[CAP];
88
+ unsigned cpos[CAP];
89
+ unsigned nsel, ncand, ntie, cut, above, count, digit, gt;
90
+ };
91
+ extern "C" __device__ const int k31_topk_smem = sizeof(Smem);
92
+
93
+ // The digits a level reads: key >> SHIFT & 0xfff among the keys whose bits above FSHIFT match.
94
+ __constant__ const int SHIFT[3] = {20, 8, 0};
95
+ __constant__ const int FSHIFT[3] = {32, 20, 8};
96
+
97
+ __device__ __forceinline__ bool in_play(unsigned k, int level, unsigned fpre) {
98
+ return level == 0 || k >> FSHIFT[level] == fpre;
99
+ }
100
+
101
+ // The key prefix at SHIFT[level] of a bin.
102
+ __device__ __forceinline__ unsigned prefix_of(int level, unsigned fpre, unsigned bin) {
103
+ const int w = FSHIFT[level] - SHIFT[level];
104
+ return level == 0 ? bin : fpre << w | (bin & ((1u << w) - 1));
105
+ }
106
+
107
+ // Thread t < 256 owns bin 255 - t of h256: the digit holding the rem-th largest (rem >= 1) and the
108
+ // count strictly above it, into s.digit / s.gt. Every thread calls it.
109
+ __device__ __forceinline__ void cut256(Smem& s, unsigned rem) {
110
+ const int t = threadIdx.x;
111
+ if (t < 256) {
112
+ const unsigned h = s.h256[255 - t];
113
+ unsigned c = h;
114
+ #pragma unroll
115
+ for (int o = 1; o < 32; o <<= 1) {
116
+ const unsigned y = __shfl_up_sync(0xffffffffu, c, o);
117
+ if ((t & 31) >= o) c += y;
118
+ }
119
+ if ((t & 31) == 31) s.wsum[t >> 5] = c;
120
+ asm volatile("bar.sync 1, 256;");
121
+ for (int w = 0; w < (t >> 5); ++w) c += s.wsum[w];
122
+ if (c >= rem && c - h < rem) s.digit = 255 - t, s.gt = c - h;
123
+ }
124
+ __syncthreads();
125
+ }
126
+
127
+ // The rem-th largest (rem in [1, m]) of v[0, m) and how many lie above it, by 8-bit passes over the
128
+ // low `low` bits; every v shares the bits of `base` above them.
129
+ __device__ __forceinline__ void select_smem(Smem& s, const unsigned* v, unsigned m, unsigned rem, unsigned& thr,
130
+ unsigned& gt, int low, unsigned base) {
131
+ const int top = (low + 7) / 8 * 8 - 8;
132
+ unsigned mask = top + 8 >= 32 ? 0u : ~0u << (top + 8), prefix = base & mask;
133
+ gt = 0;
134
+ for (int shift = top; shift >= 0; shift -= 8) {
135
+ for (int i = threadIdx.x; i < 256; i += NT) s.h256[i] = 0;
136
+ __syncthreads();
137
+ for (unsigned i = threadIdx.x; i < m; i += NT)
138
+ if ((v[i] & mask) == prefix) atomicAdd(&s.h256[(v[i] >> shift) & 255], 1u);
139
+ __syncthreads();
140
+ cut256(s, rem);
141
+ prefix |= s.digit << shift, mask |= 255u << shift;
142
+ gt += s.gt, rem -= s.gt;
143
+ __syncthreads();
144
+ }
145
+ thr = prefix;
146
+ }
147
+
148
+ // The four logits at i (fewer at the row's end, the rest -inf).
149
+ __device__ __forceinline__ void load4(const bf16* row, unsigned i, unsigned n, float x[4]) {
150
+ if (i + 3 < n) {
151
+ const float4 v = ld4(row + i);
152
+ x[0] = v.x, x[1] = v.y, x[2] = v.z, x[3] = v.w;
153
+ } else {
154
+ #pragma unroll
155
+ for (int j = 0; j < 4; ++j) x[j] = i + j < n ? lv(row, i + j) : -INFINITY;
156
+ }
157
+ }
158
+
159
+ // f(x[4], i) for the four logits at i. Whole tiles issue UNROLL unguarded loads of each thread before
160
+ // any is used (a guard between them would serialize them); the tail goes four logits a thread.
161
+ template <class F>
162
+ __device__ __forceinline__ void each4(const bf16* row, unsigned n, F f) {
163
+ constexpr unsigned TILE = NT * 4 * UNROLL;
164
+ const unsigned full = n / TILE * TILE;
165
+ for (unsigned base = 0; base < full; base += TILE) {
166
+ float4 v[UNROLL];
167
+ #pragma unroll
168
+ for (int u = 0; u < UNROLL; ++u)
169
+ v[u] = ld4v(row + base + (u * NT + threadIdx.x) * 4);
170
+ #pragma unroll
171
+ for (int u = 0; u < UNROLL; ++u) {
172
+ const float x[4] = {v[u].x, v[u].y, v[u].z, v[u].w};
173
+ f(x, base + (u * NT + threadIdx.x) * 4);
174
+ }
175
+ }
176
+ for (unsigned i = full + threadIdx.x * 4; i < n; i += NT * 4) {
177
+ float x[4];
178
+ load4(row, i, n, x);
179
+ f(x, i);
180
+ }
181
+ }
182
+
183
+ // The sample: the head (HEAD logits) and the tail (TAIL) whole, weight 1, and the interior's chunks
184
+ // spread evenly at 1 / SAMPLE_FRAC, weighted up to the interior's length; weights in 1/16ths. Indexer
185
+ // logits crowd the ends (the first tokens, the recent window), so an unweighted sample overcounts.
186
+ struct Sample {
187
+ unsigned chunks, interior, w16;
188
+ };
189
+
190
+ __device__ __forceinline__ Sample sample_of(unsigned n) {
191
+ const unsigned len = n - HEAD - TAIL, interior = max(2u, len / (SAMPLE_CHUNK * SAMPLE_FRAC));
192
+ return {(HEAD + TAIL) / SAMPLE_CHUNK + interior, interior,
193
+ (unsigned)((16ull * len + interior * SAMPLE_CHUNK / 2) / (interior * SAMPLE_CHUNK))};
194
+ }
195
+
196
+ // f(x[4], i, weight) over the sample, a thread's loads issued four at a time.
197
+ template <class F>
198
+ __device__ __forceinline__ void each_sample(const bf16* row, unsigned n, Sample m, F f) {
199
+ constexpr unsigned PER = SAMPLE_CHUNK / 4, ENDS = (HEAD + TAIL) / SAMPLE_CHUNK, STEP = NT / PER;
200
+ const auto at = [&](unsigned c) {
201
+ return c == 0 ? 0
202
+ : c < ENDS ? ((n - TAIL) & ~3u) + (c - 1) * SAMPLE_CHUNK
203
+ : HEAD + (unsigned)((unsigned long long)(c - ENDS) * (n - HEAD - TAIL - SAMPLE_CHUNK) /
204
+ (m.interior - 1)) & ~3u;
205
+ };
206
+ for (unsigned c0 = threadIdx.x / PER; c0 < m.chunks; c0 += 4 * STEP) {
207
+ float x[4][4];
208
+ unsigned i[4];
209
+ #pragma unroll
210
+ for (int u = 0; u < 4; ++u) {
211
+ const unsigned c = c0 + u * STEP;
212
+ i[u] = c < m.chunks ? at(c) + threadIdx.x % PER * 4 : n;
213
+ load4(row, i[u], n, x[u]);
214
+ }
215
+ #pragma unroll
216
+ for (int u = 0; u < 4; ++u)
217
+ if (i[u] < n) f(x[u], i[u], c0 + u * STEP < ENDS ? 16u : m.w16);
218
+ }
219
+ }
220
+
221
+ // One level's histogram over `scan` (the row, each key weight 1, or the sample).
222
+ template <class Over>
223
+ __device__ __forceinline__ void histogram(Smem& s, Over scan, unsigned n, int level, unsigned fpre) {
224
+ for (int i = threadIdx.x; i < BINS; i += NT) s.u.hist[i] = 0;
225
+ __syncthreads();
226
+ const int sh = SHIFT[level];
227
+ scan([&](const float* x, unsigned i, unsigned w) {
228
+ #pragma unroll
229
+ for (int j = 0; j < 4; ++j) {
230
+ const unsigned k = okey(x[j]);
231
+ if (i + j < n && in_play(k, level, fpre)) atomicAdd(&s.u.hist[k >> sh & 0xfff], w);
232
+ }
233
+ });
234
+ __syncthreads();
235
+ }
236
+
237
+ // The bin where the count from the top first reaches `want` (at most the histogram's total), into
238
+ // s.cut, with the count above it and its own into s.above / s.count.
239
+ __device__ __forceinline__ void cut_bin(Smem& s, unsigned want) {
240
+ const int t = threadIdx.x;
241
+ unsigned c[BPT], sum = 0;
242
+ #pragma unroll
243
+ for (int k = 0; k < BPT; ++k) c[k] = s.u.hist[BINS - 1 - BPT * t - k], sum += c[k];
244
+ __syncthreads();
245
+ unsigned ab;
246
+ Scan(s.scan).ExclusiveSum(sum, ab);
247
+ #pragma unroll
248
+ for (int k = 0; k < BPT; ++k) {
249
+ if (ab < want && ab + c[k] >= want) s.cut = BINS - 1 - BPT * t - k, s.above = ab, s.count = c[k];
250
+ ab += c[k];
251
+ }
252
+ __syncthreads();
253
+ }
254
+
255
+ #define CU 2 // 16-byte loads a thread a collect tile
256
+
257
+ // Positions whose key >> sh is above `hi` into s.sel, those in [lo, hi] into the candidates; s.ncand
258
+ // counts every candidate, CAP or not. Hits are a few percent of a row, so each takes its own atomic.
259
+ // Keying every logit made the read bound by issue: eight logits at a time are ruled out by four pair
260
+ // compares against `lo` as a bf16 rounded down, and only a group with a logit at or above it (or a
261
+ // NaN) is keyed. The next tile's loads leave before this tile is looked at. A row starts 16-byte
262
+ // aligned (`stride` a multiple of 8).
263
+ __device__ __forceinline__ void collect(Smem& s, const bf16* row, unsigned n, int sh, unsigned lo, unsigned hi) {
264
+ if (threadIdx.x == 0) s.nsel = 0, s.ncand = 0;
265
+ __syncthreads();
266
+ const __nv_bfloat162 thr = __bfloat162bfloat162(__float2bfloat16_rd(unkey(lo << sh)));
267
+ constexpr unsigned TILE = NT * 8 * CU;
268
+ const auto load = [&](unsigned base, uint4* v) {
269
+ #pragma unroll
270
+ for (int u = 0; u < CU; ++u) {
271
+ const unsigned i = base + (u * NT + threadIdx.x) * 8;
272
+ v[u] = i < n ? __ldg(reinterpret_cast<const uint4*>(row + i)) : make_uint4(0, 0, 0, 0);
273
+ }
274
+ };
275
+ uint4 cur[CU], nxt[CU];
276
+ load(0, cur);
277
+ for (unsigned base = 0; base < n; base += TILE) {
278
+ if (base + TILE < n) load(base + TILE, nxt);
279
+ #pragma unroll
280
+ for (int u = 0; u < CU; ++u) {
281
+ const unsigned i = base + (u * NT + threadIdx.x) * 8, w[4] = {cur[u].x, cur[u].y, cur[u].z, cur[u].w};
282
+ unsigned below = ~0u;
283
+ #pragma unroll
284
+ for (int q = 0; q < 4; ++q) below &= __hlt2_mask(*reinterpret_cast<const __nv_bfloat162*>(&w[q]), thr);
285
+ if (below == ~0u) continue;
286
+ #pragma unroll
287
+ for (int j = 0; j < 8; ++j) {
288
+ const unsigned k = okey(__uint_as_float(j & 1 ? w[j / 2] & 0xffff0000u : w[j / 2] << 16)), d = k >> sh;
289
+ if (i + j >= n || d < lo) continue;
290
+ if (d > hi) {
291
+ s.sel[atomicAdd(&s.nsel, 1u)] = i + j;
292
+ } else {
293
+ const unsigned c = atomicAdd(&s.ncand, 1u);
294
+ if (c < CAP) s.ckey[c] = k, s.cpos[c] = i + j;
295
+ }
296
+ }
297
+ }
298
+ #pragma unroll
299
+ for (int u = 0; u < CU; ++u) cur[u] = nxt[u];
300
+ }
301
+ __syncthreads();
302
+ }
303
+
304
+ // The candidates' rem largest by key, ties by smallest position, appended to s.sel. Every candidate
305
+ // shares the key bits of `base` above the low `low`, and every position lies below n.
306
+ __device__ __forceinline__ void finish(Smem& s, unsigned rem, unsigned n, int low = 32, unsigned base = 0) {
307
+ const int t = threadIdx.x;
308
+ const unsigned m = s.ncand;
309
+ unsigned kthr, kgt;
310
+ select_smem(s, s.ckey, m, rem, kthr, kgt, low, base);
311
+ if (t == 0) s.ntie = 0;
312
+ __syncthreads();
313
+ for (unsigned i = t; i < m; i += NT) {
314
+ if (s.ckey[i] > kthr) s.sel[atomicAdd(&s.nsel, 1u)] = s.cpos[i];
315
+ else if (s.ckey[i] == kthr) s.u.tie[atomicAdd(&s.ntie, 1u)] = ~s.cpos[i];
316
+ }
317
+ __syncthreads();
318
+ const unsigned e = s.ntie, need = rem - kgt;
319
+ unsigned pthr = 0, pgt;
320
+ if (need < e) select_smem(s, s.u.tie, e, need, pthr, pgt, 32 - __clz(n - 1), ~0u);
321
+ for (unsigned i = t; i < e; i += NT)
322
+ if (need == e || s.u.tie[i] >= pthr) s.sel[atomicAdd(&s.nsel, 1u)] = ~s.u.tie[i];
323
+ __syncthreads();
324
+ }
325
+
326
+ // Every key above `key` and the first `rem` positions holding it, in one in-order read.
327
+ __device__ void ties_in_order(Smem& s, const bf16* row, unsigned n, unsigned key, unsigned rem) {
328
+ const int t = threadIdx.x;
329
+ if (t == 0) s.nsel = 0;
330
+ __syncthreads();
331
+ unsigned taken = 0; // ties taken by earlier tiles
332
+ for (unsigned base = 0; base < n; base += NT * 4) {
333
+ const unsigned i = base + t * 4;
334
+ float x[4];
335
+ load4(row, i, n, x);
336
+ unsigned e = 0;
337
+ #pragma unroll
338
+ for (int j = 0; j < 4; ++j) e += i + j < n && okey(x[j]) == key;
339
+ unsigned off, tot;
340
+ Scan(s.scan).ExclusiveSum(e, off, tot);
341
+ #pragma unroll
342
+ for (int j = 0; j < 4; ++j) {
343
+ const unsigned k = okey(x[j]);
344
+ const bool tie = i + j < n && k == key;
345
+ if ((i + j < n && k > key) || (tie && taken + off < rem)) s.sel[atomicAdd(&s.nsel, 1u)] = i + j;
346
+ off += tie;
347
+ }
348
+ taken += tot;
349
+ __syncthreads();
350
+ }
351
+ }
352
+
353
+ // The sampled route: true when s.sel holds the row's 2048.
354
+ __device__ __forceinline__ bool sampled(Smem& s, const bf16* row, unsigned n) {
355
+ const Sample m = sample_of(n);
356
+ const auto over = [&](auto f) { each_sample(row, n, m, f); };
357
+ const unsigned want = 16 * TK * 3 / 2;
358
+ histogram(s, over, n, 0, 0);
359
+ cut_bin(s, want);
360
+ const unsigned b1 = s.cut, left = want - s.above;
361
+ if (s.above + s.count <= 16 * (CAP * 3 / 4)) {
362
+ collect(s, row, n, 20, b1, 0xfffu);
363
+ } else {
364
+ histogram(s, over, n, 1, b1);
365
+ cut_bin(s, left);
366
+ collect(s, row, n, 8, prefix_of(1, b1, s.cut), 0xffffffu);
367
+ }
368
+ const unsigned kept = s.ncand;
369
+ if (kept < TK || kept > CAP) return false;
370
+ finish(s, TK, n);
371
+ return true;
372
+ }
373
+
374
+
375
+ // D's route's shared memory, over Smem's: the histogram and later the bitmaps, the output slots' marks.
376
+ struct Held {
377
+ unsigned bits[BINS + 32];
378
+ unsigned mark[TK];
379
+ unsigned wsum[NT / 32];
380
+ unsigned cut, above, digit, gt;
381
+ };
382
+ static_assert(sizeof(Held) <= sizeof(Smem), "held's layout fits the module's shared memory");
383
+
384
+ // The exclusive sum of x over the block in thread order; every thread calls it. A warp's total is in
385
+ // h.wsum, so it is free until the next barrier.
386
+ __device__ __forceinline__ unsigned held_scan(Held& h, unsigned x) {
387
+ const unsigned lane = threadIdx.x & 31, w = threadIdx.x >> 5;
388
+ unsigned c = x;
389
+ #pragma unroll
390
+ for (int i = 1; i < 32; i <<= 1) {
391
+ const unsigned y = __shfl_up_sync(0xffffffffu, c, i);
392
+ if (lane >= i) c += y;
393
+ }
394
+ if (lane == 31) h.wsum[w] = c;
395
+ __syncthreads();
396
+ unsigned before = 0;
397
+ #pragma unroll
398
+ for (int i = 0; i < NT / 32; i += 4) {
399
+ const uint4 q = *reinterpret_cast<const uint4*>(h.wsum + i);
400
+ before += (i < w ? q.x : 0) + (i + 1 < w ? q.y : 0) + (i + 2 < w ? q.z : 0) + (i + 3 < w ? q.w : 0);
401
+ }
402
+ return before + c - x;
403
+ }
404
+
405
+ // The position of x's k-th set bit, k below its count.
406
+ __device__ __forceinline__ unsigned nth_bit(unsigned x, unsigned k) {
407
+ unsigned p = 0;
408
+ #pragma unroll
409
+ for (int w = 16; w; w >>= 1) {
410
+ const unsigned c = __popc(x >> p & (1u << w) - 1);
411
+ if (k >= c) k -= c, p += w;
412
+ }
413
+ return p;
414
+ }
415
+
416
+ // D's route for a row of at most HELD_MAX, read once. Warp w holds positions [32 C w, 32 C (w + 1)),
417
+ // lane l the eight from 32 C w + 256 j + 8 l for each j < C / 8, so every read is coalesced. Adding
418
+ // +0 makes -0 +0 and every NaN 0x7fff, as widening and adding +0 does for the key (every NaN keys as
419
+ // 0xffffffff, above +inf), and leaves the rest alone, subnormals too. Each value counts into the
420
+ // 4096-bin histogram of its top 12 bits, the bins read in key order (a negative half's reversed),
421
+ // whose cut bin a 17-slot histogram of the low 4 bits splits to the cut value K. One HSET2 compares
422
+ // two values with K: the row's positions above K and at K become two bitmaps, a byte a group. A scan
423
+ // of their words' counts places each word's taken positions (every one above K, the first `need` at
424
+ // K), and each thread fills four output slots from the words holding them. The 2048 come out
425
+ // ascending with no sort and in balanced work, the same for any ties.
426
+ //
427
+ // A slot past n is read as a NaN and taken back out: from the NaN bin and digit by count, from the
428
+ // bitmaps by position. A row with 2048 NaNs or more cuts at NaN, which no ordered compare finds.
429
+ template <int C>
430
+ __device__ __forceinline__ void held(Held& h, const bf16* row, unsigned n, int* o) {
431
+ constexpr int V = C / 8, W = C / 2;
432
+ const unsigned t = threadIdx.x, pads = NT * C - n;
433
+ const auto at = [&](int j) { return 32 * C * (t >> 5) + 256 * j + 8 * (t & 31); }; // group j's first position
434
+ unsigned a[W];
435
+ #pragma unroll
436
+ for (int j = 0; j < V; ++j) {
437
+ const uint4 v = at(j) < n ? __ldg(reinterpret_cast<const uint4*>(row + at(j))) : make_uint4(~0u, ~0u, ~0u, ~0u);
438
+ a[4 * j] = v.x, a[4 * j + 1] = v.y, a[4 * j + 2] = v.z, a[4 * j + 3] = v.w;
439
+ }
440
+ for (int i = t; i < (BINS + 32) / 4; i += NT) reinterpret_cast<uint4*>(h.bits)[i] = make_uint4(0, 0, 0, 0);
441
+ unsigned* dig = h.bits + BINS;
442
+ // the group straddling n holds real values past it: NaNs from here on
443
+ #pragma unroll
444
+ for (int j = 0; j < V; ++j)
445
+ if (at(j) == (n & ~7u))
446
+ #pragma unroll
447
+ for (int q = 0; q < 4; ++q) {
448
+ const unsigned i = at(j) + 2 * q;
449
+ a[4 * j + q] |= i < n ? (i + 1 < n ? 0u : 0xffff0000u) : ~0u;
450
+ }
451
+ #pragma unroll
452
+ for (int i = 0; i < W; ++i) {
453
+ const __nv_bfloat162 x = __hadd2(*reinterpret_cast<const __nv_bfloat162*>(&a[i]), __bfloat162bfloat162(0.0f));
454
+ a[i] = *reinterpret_cast<const unsigned*>(&x);
455
+ }
456
+ __syncthreads();
457
+ #pragma unroll
458
+ for (int i = 0; i < W; ++i) atomicAdd(&h.bits[a[i] >> 4 & 0xfff], 1u), atomicAdd(&h.bits[a[i] >> 20], 1u);
459
+ __syncthreads();
460
+ {
461
+ // thread t reads key bins 4095 - 8t down to 4088 - 8t: raw bins 2047 - 8t down for t < 256 (the
462
+ // NaN bin first), 8t up for the negative half
463
+ const uint4* h4 = reinterpret_cast<const uint4*>(h.bits);
464
+ const bool pos = t < 256;
465
+ const uint4 x = h4[pos ? (0x7f8 - 8 * t) / 4 + 1 : 2 * t], y = h4[pos ? (0x7f8 - 8 * t) / 4 : 2 * t + 1];
466
+ const unsigned c[8] = {(pos ? x.w : x.x) - (t == 0 ? pads : 0), pos ? x.z : x.y, pos ? x.y : x.z, pos ? x.x : x.w,
467
+ pos ? y.w : y.x, pos ? y.z : y.y, pos ? y.y : y.z, pos ? y.x : y.w};
468
+ unsigned sum = 0;
469
+ #pragma unroll
470
+ for (int k = 0; k < 8; ++k) sum += c[k];
471
+ unsigned ab = held_scan(h, sum);
472
+ #pragma unroll
473
+ for (int k = 0; k < 8; ++k) {
474
+ if (ab < TK && ab + c[k] >= TK) h.cut = BINS - 1 - 8 * t - k, h.above = ab;
475
+ ab += c[k];
476
+ }
477
+ }
478
+ __syncthreads();
479
+ const unsigned rb = h.cut ^ (h.cut & 0x800 ? 0x800 : 0xfff), rem = TK - h.above, neg = rb >> 11;
480
+ // a value's top 12 bits are the cut bin's when (value ^ rb << 4) is below 16: its digit
481
+ #pragma unroll
482
+ for (int i = 0; i < W; ++i) {
483
+ atomicAdd(dig + min((a[i] ^ rb << 4) & 0xffffu, 16u), 1u);
484
+ atomicAdd(dig + min(a[i] >> 16 ^ rb << 4, 16u), 1u);
485
+ }
486
+ __syncthreads();
487
+ if (t < 32) {
488
+ // lane l < 16 holds key digit 15 - l; the count from the top first reaching rem marks the cut
489
+ const unsigned d = 15 - t, r = neg ? 15 - d : d, c0 = t < 16 ? dig[r] - (rb == 0x7ff && r == 15 ? pads : 0) : 0;
490
+ unsigned c = c0;
491
+ #pragma unroll
492
+ for (int i = 1; i < 16; i <<= 1) {
493
+ const unsigned y = __shfl_up_sync(0xffffffffu, c, i);
494
+ if (t >= i) c += y;
495
+ }
496
+ if (t < 16 && c >= rem && c - c0 < rem) h.digit = r, h.gt = c - c0;
497
+ }
498
+ __syncthreads();
499
+ const unsigned K = rb << 4 | h.digit, need = rem - h.gt;
500
+ // above K by an unordered compare (a NaN is above every value), at K by an ordered one; for a NaN K,
501
+ // the unordered compare with +inf finds the NaNs, and nothing is above
502
+ const bool nan = K == 0x7fff;
503
+ const __nv_bfloat162 ka = __bfloat162bfloat162(__ushort_as_bfloat16((unsigned short)(nan ? 0x7f80 : K))),
504
+ kb = __bfloat162bfloat162(__ushort_as_bfloat16((unsigned short)K));
505
+ // the bitmaps over the histogram's words, word q's low value at bit 2q of its group's byte and its
506
+ // high one at 2q + 1
507
+ constexpr unsigned NW = NT * C / 32;
508
+ unsigned *gbits = h.bits, *ebits = gbits + NW, *take = ebits + NW;
509
+ #pragma unroll
510
+ for (int j = 0; j < V; ++j) {
511
+ unsigned g = 0, e = 0;
512
+ #pragma unroll
513
+ for (int q = 0; q < 4; ++q) {
514
+ const __nv_bfloat162 x = *reinterpret_cast<const __nv_bfloat162*>(&a[4 * j + q]);
515
+ const unsigned bit = 1u << 2 * q | 1u << 17 + 2 * q;
516
+ g |= __hgtu2_mask(x, ka) & bit, e |= __heq2_mask(x, kb) & bit;
517
+ }
518
+ const unsigned keep = 0xffu >> 8 - min(max((int)(n - at(j)), 0), 8);
519
+ g = (g | g >> 16) & keep, e = (e | e >> 16) & keep;
520
+ reinterpret_cast<unsigned char*>(gbits)[at(j) / 8] = nan ? 0 : g;
521
+ reinterpret_cast<unsigned char*>(ebits)[at(j) / 8] = nan ? g : e;
522
+ }
523
+ __syncthreads();
524
+ // thread t owns PW words; one scan of their counts places them, the first `need` ties kept
525
+ constexpr int PW = C >= 32 ? C / 32 : 1;
526
+ const bool owns = t * PW < NW;
527
+ unsigned gw[PW], ew[PW], cg = 0, ce = 0;
528
+ #pragma unroll
529
+ for (int i = 0; i < PW; ++i) {
530
+ gw[i] = owns ? gbits[t * PW + i] : 0, ew[i] = owns ? ebits[t * PW + i] : 0;
531
+ cg += __popc(gw[i]), ce += __popc(ew[i]);
532
+ }
533
+ const unsigned pre = held_scan(h, cg | ce << 16), ties = pre >> 16;
534
+ unsigned r = need > ties ? need - ties : 0, q = (pre & 0xffffu) + min(ties, need);
535
+ if (ce > r)
536
+ #pragma unroll
537
+ for (int i = 0; i < PW; ++i) {
538
+ const unsigned c = __popc(ew[i]);
539
+ ew[i] = r >= c ? ew[i] : r ? ew[i] & (1u << nth_bit(ew[i], r)) - 1 : 0;
540
+ r -= min(r, c);
541
+ }
542
+ // a word's owner marks the slot it starts at and each of its slots a multiple of 4: the word and
543
+ // how many of its positions come before the slot
544
+ if (owns)
545
+ #pragma unroll
546
+ for (int i = 0; i < PW; ++i) {
547
+ const unsigned x = gw[i] | ew[i], c = __popc(x), wd = t * PW + i;
548
+ take[wd] = x;
549
+ if (c) h.mark[q] = wd << 5;
550
+ for (unsigned k = (q + 3) & ~3u; k < q + c; k += 4) h.mark[k] = wd << 5 | (k - q);
551
+ q += c;
552
+ }
553
+ __syncthreads();
554
+ // output slots 4t to 4t + 3, a word read again where a slot starts one
555
+ unsigned k = 4 * t, m = h.mark[k], wd = m >> 5, x = take[wd];
556
+ x &= ~0u << nth_bit(x, m & 31);
557
+ int v[4];
558
+ #pragma unroll
559
+ for (int i = 0; i < 4; ++i, ++k) {
560
+ if (!x) m = h.mark[k], wd = m >> 5, x = take[wd];
561
+ v[i] = wd * 32 + __ffs(x) - 1, x &= x - 1;
562
+ }
563
+ reinterpret_cast<int4*>(o)[t] = make_int4(v[0], v[1], v[2], v[3]);
564
+ }
565
+
566
+ // The exact route: a level a read until the cut's bin fits CAP.
567
+ __device__ __forceinline__ void exact(Smem& s, const bf16* row, unsigned n) {
568
+ const auto over = [&](auto f) { each4(row, n, [&](const float* x, unsigned i) { f(x, i, 1u); }); };
569
+ unsigned rem = TK, fpre = 0;
570
+ for (int level = 0; level < 3; ++level) {
571
+ histogram(s, over, n, level, fpre);
572
+ cut_bin(s, rem);
573
+ const unsigned p = prefix_of(level, fpre, s.cut), above = s.above;
574
+ if (s.count <= CAP) {
575
+ collect(s, row, n, SHIFT[level], p, p);
576
+ finish(s, TK - s.nsel, n, SHIFT[level], p << SHIFT[level]);
577
+ return;
578
+ }
579
+ rem -= above, fpre = p;
580
+ }
581
+ ties_in_order(s, row, n, fpre, rem);
582
+ }
583
+
584
+ template <bool HELD>
585
+ __device__ __forceinline__ void topk(const bf16* __restrict__ logits, int stride, const int* __restrict__ lens,
586
+ int* __restrict__ out) {
587
+ // D launches the held build as a programmatic dependent: the next kernel onto the SMs at once, the
588
+ // logits read once the kernel before is done
589
+ asm volatile("griddepcontrol.launch_dependents;");
590
+ asm volatile("griddepcontrol.wait;" ::: "memory");
591
+ extern __shared__ __align__(16) unsigned char raw[];
592
+ Smem& s = *reinterpret_cast<Smem*>(raw);
593
+ const int t = threadIdx.x;
594
+ const bf16* row = logits + (size_t)blockIdx.x * stride;
595
+ const unsigned n = (unsigned)max(lens[blockIdx.x], 0);
596
+ int* o = out + (size_t)blockIdx.x * TK;
597
+ if (n <= TK) {
598
+ for (int i = t; i < TK; i += NT) o[i] = i < (int)n ? i : -1;
599
+ return;
600
+ }
601
+ if (HELD && n <= HELD_MAX) {
602
+ Held& h = *reinterpret_cast<Held*>(raw);
603
+ if (n <= NT * 8) held<8>(h, row, n, o);
604
+ else if (n <= NT * 16) held<16>(h, row, n, o);
605
+ else if (n <= NT * 32) held<32>(h, row, n, o);
606
+ else held<64>(h, row, n, o);
607
+ return;
608
+ }
609
+ if (n < SAMPLE_MIN || !sampled(s, row, n)) exact(s, row, n);
610
+ if (n <= BITMAP_MAX) {
611
+ // ascending: each thread a run of words, its bits' rank from a scan of the runs' counts
612
+ const unsigned words = (n + 31) / 32, per = (words + NT - 1) / NT, w0 = min(t * per, words), w1 = min(w0 + per, words);
613
+ for (unsigned w = t; w < words; w += NT) s.u.bits[w] = 0;
614
+ __syncthreads();
615
+ for (int i = t; i < TK; i += NT) atomicOr(&s.u.bits[s.sel[i] >> 5], 1u << (s.sel[i] & 31));
616
+ __syncthreads();
617
+ unsigned c = 0, at;
618
+ for (unsigned w = w0; w < w1; ++w) c += __popc(s.u.bits[w]);
619
+ Scan(s.scan).ExclusiveSum(c, at);
620
+ for (unsigned w = w0; w < w1; ++w)
621
+ for (unsigned b = s.u.bits[w]; b; b &= b - 1) o[at++] = (int)(w * 32 + __ffs(b) - 1);
622
+ return;
623
+ }
624
+ int k[TK / NT];
625
+ #pragma unroll
626
+ for (int j = 0; j < TK / NT; ++j) k[j] = s.sel[t * (TK / NT) + j];
627
+ __syncthreads();
628
+ Sort(s.u.sort).Sort(k, 0, 32 - __clz(n - 1));
629
+ #pragma unroll
630
+ for (int j = 0; j < TK / NT; ++j) o[t * (TK / NT) + j] = k[j];
631
+ }
632
+
633
+ extern "C" __global__ void __launch_bounds__(NT, 2) k31_topk(const bf16* __restrict__ logits, int stride,
634
+ const int* __restrict__ lens, int* __restrict__ out) {
635
+ topk<false>(logits, stride, lens, out);
636
+ }
637
+
638
+ // Two blocks an SM, within 64 registers a thread, so 256 rows go in one wave on 152 SMs.
639
+ extern "C" __global__ void __launch_bounds__(NT, 2) k31_topk_held(const bf16* __restrict__ logits, int stride,
640
+ const int* __restrict__ lens, int* __restrict__ out) {
641
+ topk<true>(logits, stride, lens, out);
642
+ }