susun-123 commited on
Commit
1124229
·
verified ·
1 Parent(s): e958d7f

k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908: K3.1 D's fused all-reduces for any batch, with their source and a byte-exact build

Browse files
.gitattributes CHANGED
@@ -285,3 +285,4 @@ blobs/ae5ff7f2ed88159f8214e07a2e4fa3bad3add4e471a65b4fdf8326fb7f6c376b filter=lf
285
  blobs/b80a4549fabad26bfc8c3c123be15dda42660f87e98748bace4c409cf794dfec filter=lfs diff=lfs merge=lfs -text
286
  k31_topk-5eff1799/kernel.cubin filter=lfs diff=lfs merge=lfs -text
287
  k3_ar_fused+NRANKS=8-10e88839/kernel.cubin 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
287
  k3_ar_fused+NRANKS=8-10e88839/kernel.cubin filter=lfs diff=lfs merge=lfs -text
288
+ k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/kernel.cubin filter=lfs diff=lfs merge=lfs -text
k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/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.
k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/build.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Rebuilds kernel.cubin byte for byte: ./build.sh [OUT]
3
+ # Source: github.com/pegainfer-project/kern-k31 a8d49a5, source/k3_ar_fused.cu and source/k3_l2_prefetch.cuh,
4
+ # built as kernels.toml's "k3_ar_fused+ANY_BATCH=1+NRANKS=8".
5
+ # nvcc names anonymous-namespace symbols after the source's absolute path, so the build runs in a
6
+ # fixed directory.
7
+ set -eu
8
+ NVCC=${NVCC:-nvcc}
9
+ SHA=d362b908e3550a4d671e93dc061241a59baa2077d715f7ff4ec7035cbb45a113
10
+ "$NVCC" --version | grep -q 'V13.0.88' || { echo "build.sh: needs nvcc V13.0.88 (CUDA 13.0)" >&2; exit 1; }
11
+ here=$(cd "$(dirname "$0")" && pwd)
12
+ out=$(realpath -m "${1:-kernel.cubin}")
13
+ dir=/tmp/kern-build
14
+ rm -rf "$dir" && mkdir -p "$dir" && cp "$here"/src/* "$dir"/
15
+ (cd "$dir" && "$NVCC" -cubin -arch=sm_103a -DANY_BATCH=1 -DNRANKS=8 -o out.cubin k3_ar_fused.cu)
16
+ echo "$SHA $dir/out.cubin" | sha256sum -c - >/dev/null || { echo "build.sh: sha256 differs from $SHA" >&2; exit 1; }
17
+ cp "$dir/out.cubin" "$out"
18
+ echo "$out: $SHA"
k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/kernel.cubin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d362b908e3550a4d671e93dc061241a59baa2077d715f7ff4ec7035cbb45a113
3
+ size 1304408
k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/src/k3_ar_fused.cu ADDED
@@ -0,0 +1,1229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // A DCP step's two all-reduces with the work on either side of them, on the
2
+ // Lamport one-shot of peer_allreduce_bf16.cu (TensorRT-LLM's allreduce_fusion
3
+ // protocol): every rank pushes its bf16 partial into slot `rank` of every
4
+ // peer's stage, a 16-byte word holding a bf16 -0.0 has not arrived, every
5
+ // rank sums the slots in rank order in f32 and rounds once. Three stages
6
+ // rotate by call, each block keeping the rotation itself (`state`, below).
7
+ //
8
+ // The exchange runs over a row's sixteen-byte vectors. Every block pushes an
9
+ // equal run of all rows' vectors (the two-shot: a vector a thread, over the
10
+ // grid's stride) and re-poisons a share of the previous call's stage; block b
11
+ // then waits for rows b, b + KGRID, .. and runs the epilogue on each,
12
+ // a row per 1024 threads. From TWO_SHOT_ROWS rows a row goes to its owner
13
+ // (row % NRANKS) only, whose row block sums it as the one-shot does; the
14
+ // blocks of the rows a rank does not own first gather its rows' sums to the
15
+ // others (gather_share). A block waits on nothing before its pushes are out,
16
+ // and on no row before its gathers are out: a gather waits only on pushes, a
17
+ // row only on pushes and gathers, so no wait closes a cycle. The blocks past
18
+ // B load the next GEMM's weight `pf` (`pf_bytes`) into L2 while a row block
19
+ // still waits (k3_l2_prefetch.cuh; state[2 * phase] stamps a row's data in,
20
+ // state[7] is the loads' sink); kern_k3_ar_finalize_rms's then the next
21
+ // layer's o_proj weight `pf2` at evict_last, which the kern_k3_ar_attnres_rms
22
+ // after that o_proj puts back to evict_normal (`dm`).
23
+ //
24
+ // kern_k3_ar_attnres_rms_nb<NB>(const bf16* x, u8* lamport, const u64* lamport_peers, i32* state,
25
+ // i32* err, int rank, const bf16* prefix, const bf16* blocks, const f32* sw,
26
+ // const bf16* gamma, bf16* prefix2, bf16* normed, int snapshot, int B,
27
+ // i64 stage_bytes, i64 timeout_ns, const u8* pf, i64 pf_bytes, const u8* dm, i64 dm_bytes)
28
+ // o_proj's partials x [B, H] summed, then k3_residual.cu's K1b (-DLAND_BF16) on the sum
29
+ // with NB snapshots (0..KNB_MAX).
30
+ //
31
+ // kern_k3_ar_finalize_rms(const bf16* fc2, const i32* exp2perm, const f32* wts,
32
+ // const bf16* shared, u8* lamport, const u64* lamport_peers, i32* state, i32* err,
33
+ // int rank, const bf16* gamma, bf16* latent_norm, bf16* shared_sum, int B,
34
+ // i64 stage_bytes, i64 timeout_ns, const u8* pf, i64 pf_bytes, const u8* pf2, i64 pf2_bytes)
35
+ // A row's routed latent partial (k3_moe_prefill.cu's kern_k3_moe_finalize over this
36
+ // rank's experts, bf16) and its shared expert's down partial `shared` [B, H], summed;
37
+ // latent_norm = k3_land.cu's kern_k3_rms(latent sum, gamma), shared_sum the shared sum.
38
+ // fc2 and `shared` are read past griddepcontrol.wait: fc2 releases its dependents before
39
+ // its output is out, and the shared expert's GEMM may run between them as a PDL dependent.
40
+ //
41
+ // grid (KGRID, 1, 1) on every call of a group block (1024, 1, 1)
42
+ // kern_k3_ar_attnres_rms_nb<NB>: dynamic smem KCAND_BYTES (the row's snapshots, below)
43
+ // `err` gets 1 + the rank whose data did not show within `timeout_ns`, then the kernel traps.
44
+ // `lamport` holds the three stages, then NRANKS handshake words (the first call's, below).
45
+ // `state` [8 + 2 * KGRID] starts zeroed: [6] the handshake done, [8 + 2b] block b's stage,
46
+ // [9 + 2b] the shape of the call that wrote the stage it re-poisons next call.
47
+ //
48
+ // The residual rows around them:
49
+ // kern_k3_land_add2_attnres_rms_nb<NB> a layer's closing add, then the next layer's mix and norm:
50
+ // a row a cluster of LAND_CL blocks of 1024 / LAND_CL threads, dynamic
51
+ // smem KCAND_BYTES / LAND_CL; the blocks past LAND_CL * B prefetch `pf`
52
+ // kern_k3_land_gather_attnres_rms_nb<NB>(.., u8* stage, const u64* peers, i32* err, int rank, int phase,
53
+ // i64 timeout_ns, pf, pf_bytes)
54
+ // the same with p1 this rank's KH / NRANKS columns of the row (lat_up's
55
+ // column slice, rows KH / NRANKS apart), gathered over the group first
56
+ // A snapshot count is an entry, not a switch in one: a call runs its own code from the entry on. In
57
+ // the step every call fetches its instructions cold, and one kernel holding all nine counts (390 KB of
58
+ // code) ran the counts far from its entry 5-6 us slower than nb 1.
59
+ // kern_k3_embed_rms(_plan) the step's embedding gather and its first layer's norm
60
+ // (_plan: and the MLA split plan)
61
+ // Every kernel here triggers its dependents at entry (griddepcontrol.launch_dependents): the
62
+ // cuBLAS GEMM after it launches as a programmatic dependent and waits for this grid itself.
63
+ // The all-reduces and the closing add may launch as programmatic dependents themselves: they
64
+ // read the kernel before them's output only past griddepcontrol.wait.
65
+
66
+ #include <cooperative_groups.h>
67
+ #include <cuda_bf16.h>
68
+ #include <cstdint>
69
+ namespace cg = cooperative_groups;
70
+
71
+ // the loads' bytes in flight (k3_l2_prefetch.cuh's 12 MB): past the window's end the grid waits for the ones
72
+ // issued to return, and the exchange's own traffic shares HBM with them
73
+ #define L2_INFLIGHT (8 << 20)
74
+ #include "k3_l2_prefetch.cuh"
75
+
76
+ // how long the loads of the next weight go on past a row's arrival: past that the grid's end waits for them,
77
+ // not for the row epilogue (kern_k3_ar_attnres_rms's attention residual ~1.5 us, the latent norm's ~1 us)
78
+ #ifndef AR_GRACE_NS
79
+ #define AR_GRACE_NS 500
80
+ #endif
81
+ #ifndef FIN_GRACE_NS
82
+ #define FIN_GRACE_NS 500
83
+ #endif
84
+
85
+ #ifndef NRANKS
86
+ #define NRANKS 8
87
+ #endif
88
+ #define KH 7168
89
+ #define KVEC (KH / 8)
90
+ #define KLAT 3584
91
+ #define KLATV (KLAT / 8)
92
+ #define KNB_MAX 8
93
+ #define KEPS 1e-5f
94
+ #define KTHREADS 1024
95
+ #define TOPK 16
96
+ #define KGRID 144 // the exchanges' grid (gen_stage.py's TP_AR_GRID): one 1024-thread block an SM, all resident on 148 SMs
97
+ #ifndef TWO_SHOT_ROWS
98
+ #define TWO_SHOT_ROWS 14
99
+ #endif
100
+ // ANY_BATCH 0 builds for a batch whose pushes fit one pass of the grid (B x a row's vectors <= KGRID x KTHREADS)
101
+ // and whose rows a block each (B <= KGRID), 1 for any batch. gen_stage.py launches the first up to that bound:
102
+ // the second's loops hold registers that spill on the 1024-thread blocks (+0.2 ms a 64-row step).
103
+ #ifndef ANY_BATCH
104
+ #define ANY_BATCH 0
105
+ #endif
106
+
107
+ typedef __nv_bfloat16 bf16_t;
108
+ typedef __nv_bfloat162 bf162_t;
109
+
110
+ // ---------------------------------------------------------------- protocol
111
+ // A wait's deadline counts SM cycles, `timeout_ns` at 2 a ns: %globaltimer is resynced to the host clock
112
+ // early in a process, and its jump fires a deadline with nothing late (k3_dcp.cu's await_all).
113
+ __device__ __forceinline__ long long dl_now() { return clock64(); }
114
+ __device__ __forceinline__ bool dl_past(long long t0, long long timeout_ns) { return dl_now() - t0 > 2 * timeout_ns; }
115
+
116
+ __device__ __forceinline__ uint4 ld_volatile(const uint4* p) {
117
+ uint4 v;
118
+ asm volatile("ld.volatile.global.v4.u32 {%0, %1, %2, %3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p));
119
+ return v;
120
+ }
121
+
122
+ __device__ __forceinline__ bool poisoned(uint32_t w) { return (w & 0xffffu) == 0x8000u || (w >> 16) == 0x8000u; }
123
+ __device__ __forceinline__ bool arrived(uint4 v) {
124
+ return !(poisoned(v.x) || poisoned(v.y) || poisoned(v.z) || poisoned(v.w));
125
+ }
126
+ __device__ __forceinline__ uint32_t unpoison(uint32_t w) {
127
+ if ((w & 0xffffu) == 0x8000u) w &= 0xffff0000u;
128
+ if ((w >> 16) == 0x8000u) w &= 0x0000ffffu;
129
+ return w;
130
+ }
131
+ __device__ __forceinline__ float lo(uint32_t w) { return __uint_as_float(w << 16); }
132
+ __device__ __forceinline__ float hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); }
133
+ __device__ __forceinline__ uint32_t round_bf16(float f) {
134
+ const uint32_t u = __float_as_uint(f);
135
+ if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u;
136
+ return (u + 0x7fffu + ((u >> 16) & 1u)) >> 16;
137
+ }
138
+ __device__ __forceinline__ uint32_t pack2(float a, float b) { return round_bf16(a) | (round_bf16(b) << 16); }
139
+
140
+ // A launch with `pdl` starts while the kernel before it finishes: what does not depend on that kernel
141
+ // (the stage, the snapshots, the weights) is read first, its output only past this wait.
142
+ __device__ __forceinline__ void grid_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }
143
+
144
+ struct Lamport {
145
+ uint4* const* slot; // this rank's slot in every peer's stage (shared memory)
146
+ const uint4* mine; // this rank's stage
147
+ uint4* clear_buf; // the previous call's stage
148
+ long long tot;
149
+ int phase, clear_rows, clear_width; // the previous call's rows and vectors a row
150
+ };
151
+
152
+ // A deadline that passes is a broken group, never a slow one: the kernel records the late
153
+ // rank in `err` and traps, so the run fails instead of summing a slot that never arrived.
154
+ __device__ __forceinline__ void give_up(int* err, int missing) {
155
+ atomicMax(err, missing);
156
+ __threadfence_system();
157
+ __trap();
158
+ }
159
+
160
+ // The first call of a process waits for every peer to have run its once-program (the
161
+ // poisoning of its stages, kern_peer_lamport_init_bf16) before pushing into them: nothing
162
+ // orders one rank's once-program after another's first step, and a push that lands before
163
+ // the peer's poison is lost. Each rank's block 0 sets `ready[rank]` in every peer's
164
+ // handshake words (past the three stages, which the init never touches and nothing
165
+ // rewrites), every block waits for all of its own, and state[6] marks the handshake done.
166
+ __device__ __forceinline__ void lamport_handshake(uint8_t* lamport, const unsigned long long* peers, int* state,
167
+ int* err, int rank, long long stage_bytes, long long timeout_ns) {
168
+ if (threadIdx.x >= NRANKS || *reinterpret_cast<volatile int*>(state + 6)) return;
169
+ const long long at = 3 * stage_bytes;
170
+ if (blockIdx.x == 0)
171
+ reinterpret_cast<volatile int*>(reinterpret_cast<uint8_t*>(peers[threadIdx.x]) + at)[rank] = 1;
172
+ if (threadIdx.x == 0) {
173
+ const volatile int* ready = reinterpret_cast<const volatile int*>(lamport + at);
174
+ const long long t0 = dl_now();
175
+ for (int q = 0; q < NRANKS; ++q)
176
+ while (!ready[q])
177
+ if (dl_past(t0, timeout_ns)) give_up(err, 1 + q);
178
+ }
179
+ }
180
+
181
+ // state[9 + 2 * block]: the call's rows above CLEAR_SHIFT bits, its vectors a row below
182
+ #define CLEAR_SHIFT 12
183
+ // Three stages rotate by call: a call pushes into stage `phase`, and re-poisons the stage of
184
+ // the call before it (whose sums are done everywhere: this call's pushes are in) for the call
185
+ // after next. Every block keeps the rotation itself (state[8 + 2 * block]: the phase, then
186
+ // the vectors to re-poison) and moves it on as it leaves: every call of the group runs the
187
+ // same grid, so no block waits for another to start.
188
+ __device__ __forceinline__ Lamport lamport_open(uint8_t* lamport, const unsigned long long* peers, int* state, int* err,
189
+ int rank, long long tot, long long stage_bytes, long long timeout_ns) {
190
+ __shared__ uint4* s_slot[NRANKS];
191
+ asm volatile("griddepcontrol.launch_dependents;");
192
+ Lamport l;
193
+ l.slot = s_slot;
194
+ l.phase = state[8 + 2 * blockIdx.x];
195
+ l.clear_rows = state[9 + 2 * blockIdx.x] >> CLEAR_SHIFT;
196
+ l.clear_width = state[9 + 2 * blockIdx.x] & ((1 << CLEAR_SHIFT) - 1);
197
+ l.tot = tot;
198
+ if (threadIdx.x < NRANKS)
199
+ s_slot[threadIdx.x] = reinterpret_cast<uint4*>(reinterpret_cast<uint8_t*>(peers[threadIdx.x]) +
200
+ l.phase * stage_bytes) + (long long)rank * tot;
201
+ l.mine = reinterpret_cast<const uint4*>(lamport + l.phase * stage_bytes);
202
+ l.clear_buf = reinterpret_cast<uint4*>(lamport + (l.phase + 2) % 3 * stage_bytes);
203
+ lamport_handshake(lamport, peers, state, err, rank, stage_bytes, timeout_ns);
204
+ __syncthreads();
205
+ return l;
206
+ }
207
+
208
+ // Only the words the previous call wrote: a one-shot's every slot of every row; a two-shot's row q in slot
209
+ // q % NRANKS alone (its owner's sum, or this rank's own push into its own row), and the other slots of the rows
210
+ // this rank owns (the peers' pushes): (B + 7 B / 8) rows' vectors instead of 8 B. The grid's last blocks first:
211
+ // the row blocks are the first, and a small batch's words then fall on blocks that hold no row.
212
+ __device__ __forceinline__ void lamport_clear(const Lamport& l, int rank) {
213
+ const uint4 poison = make_uint4(0x80008000u, 0x80008000u, 0x80008000u, 0x80008000u);
214
+ const int w = l.clear_width, tot = l.clear_rows * w, stride = KGRID * KTHREADS;
215
+ const int first = (KGRID - 1 - (int)blockIdx.x) * KTHREADS + (int)threadIdx.x;
216
+ if (l.clear_rows < TWO_SHOT_ROWS) {
217
+ for (int i = first; i < NRANKS * tot; i += stride) l.clear_buf[i] = poison;
218
+ return;
219
+ }
220
+ for (int i = first; i < tot; i += stride) l.clear_buf[i / w % NRANKS * tot + i] = poison;
221
+ const int own = (l.clear_rows - rank + NRANKS - 1) / NRANKS * w;
222
+ for (int i = first; i < (NRANKS - 1) * own; i += stride) {
223
+ const int q = i / own, k = i - q * own, s = q + (q >= rank);
224
+ l.clear_buf[s * tot + (rank + NRANKS * (k / w)) * w + k % w] = poison;
225
+ }
226
+ }
227
+
228
+ // Vector i of a call's `tot` this thread pushes, or -1: runs of PUSH_RUN vectors dealt to the
229
+ // KGRID blocks in order, so a row's pushes leave from several SMs rather than from the one block
230
+ // a row would fill (an SM pushes ~55 GB/s). The grid is a constant: a division by gridDim.x
231
+ // costs the push 0.3 us. The two-shot (from TWO_SHOT_ROWS rows) pushes from the first blocks a
232
+ // vector a thread instead, so the blocks past them start loading the next weight (l2_load_while) at once;
233
+ // past KGRID * KTHREADS vectors the pushes go on at that stride (two_shot_rest).
234
+ #ifndef PUSH_RUN
235
+ #define PUSH_RUN 128
236
+ #endif
237
+ __device__ __forceinline__ int share_per(long long tot) {
238
+ return (((int)tot + PUSH_RUN - 1) / PUSH_RUN + KGRID - 1) / KGRID * PUSH_RUN;
239
+ }
240
+ __device__ __forceinline__ long long share(long long tot, int B) {
241
+ if (B >= TWO_SHOT_ROWS) {
242
+ const int i = (int)blockIdx.x * KTHREADS + (int)threadIdx.x;
243
+ return i < (int)tot ? i : -1;
244
+ }
245
+ const int per = share_per(tot);
246
+ const int i = per * (int)blockIdx.x + (int)threadIdx.x;
247
+ return (int)threadIdx.x < per && i < (int)tot ? i : -1;
248
+ }
249
+
250
+ // Whether q is one of block b's rows b, b + KGRID, ..
251
+ __device__ __forceinline__ bool block_row(int q, int b, int B) { return q < B && (ANY_BATCH || q == b); }
252
+
253
+ // The two-shot's vectors past share()'s first pass: i + KGRID * KTHREADS, + 2 KGRID * KTHREADS, ..
254
+ #define PUSH_STRIDE (KGRID * KTHREADS)
255
+ __device__ __forceinline__ long long two_shot_rest() {
256
+ return (long long)blockIdx.x * KTHREADS + threadIdx.x + PUSH_STRIDE;
257
+ }
258
+
259
+ __device__ __forceinline__ uint4 unpoison4(uint4 v) {
260
+ return make_uint4(unpoison(v.x), unpoison(v.y), unpoison(v.z), unpoison(v.w));
261
+ }
262
+
263
+ __device__ __forceinline__ void lamport_push(const Lamport& l, long long i, uint4 v) {
264
+ v = unpoison4(v);
265
+ #pragma unroll
266
+ for (int q = 0; q < NRANKS; ++q) l.slot[q][i] = v;
267
+ }
268
+
269
+ // The rank-order f32 sum of vector i over the slots, rounded once.
270
+ __device__ __forceinline__ uint4 lamport_sum(const Lamport& l, long long i, long long timeout_ns, int& fail) {
271
+ uint4 vals[NRANKS];
272
+ long long t0 = 0;
273
+ while (true) {
274
+ int missing = 0;
275
+ #pragma unroll
276
+ for (int r = 0; r < NRANKS; ++r) {
277
+ vals[r] = ld_volatile(l.mine + (long long)r * l.tot + i);
278
+ if (missing == 0 && !arrived(vals[r])) missing = 1 + r;
279
+ }
280
+ if (missing == 0) break;
281
+ if (t0 == 0) {
282
+ t0 = dl_now();
283
+ } else if (dl_past(t0, timeout_ns)) {
284
+ fail = missing;
285
+ break;
286
+ }
287
+ }
288
+ float acc[8];
289
+ acc[0] = lo(vals[0].x), acc[1] = hi(vals[0].x), acc[2] = lo(vals[0].y), acc[3] = hi(vals[0].y);
290
+ acc[4] = lo(vals[0].z), acc[5] = hi(vals[0].z), acc[6] = lo(vals[0].w), acc[7] = hi(vals[0].w);
291
+ #pragma unroll
292
+ for (int r = 1; r < NRANKS; ++r) {
293
+ acc[0] += lo(vals[r].x), acc[1] += hi(vals[r].x), acc[2] += lo(vals[r].y), acc[3] += hi(vals[r].y);
294
+ acc[4] += lo(vals[r].z), acc[5] += hi(vals[r].z), acc[6] += lo(vals[r].w), acc[7] += hi(vals[r].w);
295
+ }
296
+ return make_uint4(pack2(acc[0], acc[1]), pack2(acc[2], acc[3]), pack2(acc[4], acc[5]), pack2(acc[6], acc[7]));
297
+ }
298
+
299
+ // Vector i of slot q alone: a two-shot's gathered sum.
300
+ __device__ __forceinline__ uint4 lamport_one(const Lamport& l, int q, long long i, long long timeout_ns, int& fail) {
301
+ long long t0 = 0;
302
+ const uint4* p = l.mine + (long long)q * l.tot + i;
303
+ while (true) {
304
+ const uint4 v = ld_volatile(p);
305
+ if (arrived(v)) return v;
306
+ if (t0 == 0) {
307
+ t0 = dl_now();
308
+ } else if (dl_past(t0, timeout_ns)) {
309
+ fail = 1 + q;
310
+ return v;
311
+ }
312
+ }
313
+ }
314
+
315
+ // Vector i of a row's sum: the one-shot's sum of the slots, or a two-shot's (`owner` of the row): the
316
+ // owner sums the slots in rank order as the one-shot does, keeps -0.0 as +0.0 (as it is sent) and gathers
317
+ // the sum into every peer's slot `rank`; the others read the owner's slot.
318
+ __device__ __forceinline__ uint4 lamport_get(const Lamport& l, bool two, int owner, int rank, long long i,
319
+ long long timeout_ns, int& fail) {
320
+ if (two && owner != rank) return lamport_one(l, owner, i, timeout_ns, fail);
321
+ const uint4 v = lamport_sum(l, i, timeout_ns, fail);
322
+ return two ? unpoison4(v) : v;
323
+ }
324
+
325
+ // Two-shot: the sums of this rank's rows (row % NRANKS == rank) gathered to the other ranks for the rows it does
326
+ // not own, an equal run of the owned vectors each (RW a row) by row b's block, before it waits for any row: the
327
+ // gather leaves from ~7B/8 SMs instead of B/8. The owner's row block sums its row again for itself.
328
+ template <int RW>
329
+ __device__ __forceinline__ void gather_share(const Lamport& l, int rank, int B, int b, long long timeout_ns,
330
+ int& fail) {
331
+ const int nown = (B - rank + NRANKS - 1) / NRANKS, m = B - nown;
332
+ const int per = (nown * RW + m - 1) / m, g = (b - (b - rank + NRANKS - 1) / NRANKS) * per + (int)threadIdx.x;
333
+ if ((int)threadIdx.x >= per || g >= nown * RW) return;
334
+ const long long i = (long long)(rank + NRANKS * (g / RW)) * RW + g % RW;
335
+ const uint4 v = unpoison4(lamport_sum(l, i, timeout_ns, fail));
336
+ #pragma unroll 1
337
+ for (int q = 0; q < NRANKS; ++q)
338
+ if (q != rank) l.slot[q][i] = v;
339
+ }
340
+
341
+ // The word l2_load_while stops on (the first row block's arrival stamp): one a phase, state[2 * phase]; the
342
+ // call of phase p zeroes phase p + 1's for the call after it, so no grid-wide count clears it at the end.
343
+ __device__ __forceinline__ unsigned* l2_stamp(int* state, const Lamport& l) {
344
+ if (blockIdx.x == 0 && threadIdx.x == 0) state[2 * ((l.phase + 1) % 3)] = 0;
345
+ return reinterpret_cast<unsigned*>(state) + 2 * l.phase;
346
+ }
347
+
348
+ __device__ __forceinline__ void lamport_close(const Lamport& l, int* state, int* err, int fail, int B, int width) {
349
+ if (fail) give_up(err, fail);
350
+ if (threadIdx.x == 0) {
351
+ state[8 + 2 * blockIdx.x] = (l.phase + 1) % 3;
352
+ state[9 + 2 * blockIdx.x] = B << CLEAR_SHIFT | width;
353
+ if (blockIdx.x == 0) state[6] = 1;
354
+ }
355
+ }
356
+
357
+ // ---------------------------------------------------------------- row math (k3_residual.cu)
358
+ struct V8 {
359
+ unsigned w[4];
360
+ };
361
+ __device__ __forceinline__ V8 ldv(const void* p) {
362
+ const uint4 t = *(const uint4*)p;
363
+ V8 v;
364
+ v.w[0] = t.x, v.w[1] = t.y, v.w[2] = t.z, v.w[3] = t.w;
365
+ return v;
366
+ }
367
+ __device__ __forceinline__ V8 asv(uint4 t) {
368
+ V8 v;
369
+ v.w[0] = t.x, v.w[1] = t.y, v.w[2] = t.z, v.w[3] = t.w;
370
+ return v;
371
+ }
372
+ __device__ __forceinline__ void stv(void* p, const V8& v) { *(uint4*)p = make_uint4(v.w[0], v.w[1], v.w[2], v.w[3]); }
373
+ __device__ __forceinline__ bf162_t as_bf162(unsigned u) {
374
+ return __halves2bfloat162(__ushort_as_bfloat16((unsigned short)(u & 0xffffu)),
375
+ __ushort_as_bfloat16((unsigned short)(u >> 16)));
376
+ }
377
+ __device__ __forceinline__ unsigned from_bf162(bf162_t h) {
378
+ return (unsigned)(unsigned short)__bfloat16_as_ushort(__low2bfloat16(h)) |
379
+ ((unsigned)(unsigned short)__bfloat16_as_ushort(__high2bfloat16(h)) << 16);
380
+ }
381
+ __device__ __forceinline__ float2 bf2f(unsigned u) { return __bfloat1622float2(as_bf162(u)); }
382
+ __device__ __forceinline__ unsigned f2bf(float2 f) { return from_bf162(__float22bfloat162_rn(f)); }
383
+
384
+ __device__ __forceinline__ float warp_sum(float v) {
385
+ #pragma unroll
386
+ for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
387
+ return v;
388
+ }
389
+
390
+ // k3_residual.cu's attnres_rms_row, as a short chain: thread t < KVEC holds vector t of the
391
+ // row and starts the copies of its vector of candidates 0..NB-1 into shared memory (`cand`,
392
+ // [KNB_MAX][KVEC] sixteen-byte vectors) and its sw / gamma into registers at entry; every
393
+ // candidate's sum of squares and dot with sw goes through one block reduction (the
394
+ // snapshots' before the all-reduce's poll, which they do not need), each thread runs the
395
+ // softmax over the totals, mixes in f32 and rounds to bf16 as attnres_rms_row does, and the
396
+ // mix's sum of squares is one more reduction. The candidate count is a template argument.
397
+ #define KCAND_BYTES (KNB_MAX * KVEC * 16)
398
+ #define RED_LD 33
399
+
400
+ struct RowSmem {
401
+ float red[3][32 * RED_LD]; // one per reduction of a row: no barrier between them
402
+ };
403
+
404
+ struct RowRegs {
405
+ float swv[8];
406
+ V8 g;
407
+ };
408
+
409
+ template <int NB>
410
+ __device__ __forceinline__ RowRegs row_prefetch(const bf16_t* __restrict__ blk_row, const float* __restrict__ sw,
411
+ const bf16_t* __restrict__ gamma, uint4* cand, int t) {
412
+ RowRegs r;
413
+ #pragma unroll
414
+ for (int j = 0; j < 8; ++j) r.swv[j] = 0.f;
415
+ r.g.w[0] = 0u, r.g.w[1] = 0u, r.g.w[2] = 0u, r.g.w[3] = 0u;
416
+ if (t < KVEC) {
417
+ #pragma unroll
418
+ for (int c = 0; c < NB; ++c) {
419
+ const unsigned dst = (unsigned)__cvta_generic_to_shared(cand + c * KVEC + t);
420
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" ::"r"(dst), "l"(blk_row + (size_t)c * KH + t * 8));
421
+ }
422
+ if (NB > 0) {
423
+ const float4* sp4 = (const float4*)(sw + t * 8);
424
+ const float4 a = sp4[0], b = sp4[1];
425
+ r.swv[0] = a.x; r.swv[1] = a.y; r.swv[2] = a.z; r.swv[3] = a.w;
426
+ r.swv[4] = b.x; r.swv[5] = b.y; r.swv[6] = b.z; r.swv[7] = b.w;
427
+ }
428
+ r.g = ldv(gamma + t * 8);
429
+ }
430
+ asm volatile("cp.async.commit_group;");
431
+ return r;
432
+ }
433
+
434
+ __host__ __device__ constexpr int pow2_at_least(int n) { return n <= 1 ? 1 : 2 * pow2_at_least((n + 1) / 2); }
435
+ __host__ __device__ constexpr int log2_of(int n) { return n <= 1 ? 0 : 1 + log2_of(n / 2); }
436
+
437
+ // Recursive halving over the warp: N values in, lane l out with the warp's total of value
438
+ // l >> (5 - log2 N) in v[0] (N <= 32), N - 1 + 5 - log2 N shuffles.
439
+ template <int N, int O>
440
+ __device__ __forceinline__ void halve(float* v, int lane) {
441
+ if constexpr (N > 1) {
442
+ const bool up = lane & O;
443
+ #pragma unroll
444
+ for (int j = 0; j < N / 2; ++j) {
445
+ const float send = up ? v[j] : v[j + N / 2], keep = up ? v[j + N / 2] : v[j];
446
+ v[j] = keep + __shfl_xor_sync(0xffffffffu, send, O);
447
+ }
448
+ } else {
449
+ v[0] += __shfl_xor_sync(0xffffffffu, v[0], O);
450
+ }
451
+ if constexpr (O > 1) halve<(N > 1 ? N / 2 : 1), O / 2>(v, lane);
452
+ }
453
+
454
+ #ifndef BS_SMALL
455
+ #define BS_SMALL 8
456
+ #endif
457
+ // Every thread of the 32-warp block gets the block's totals of its N values: the warps'
458
+ // totals meet in `red` behind one barrier, and every warp sums them itself.
459
+ template <int N>
460
+ __device__ __forceinline__ void block_sum(float (&v)[N], float* red, int t) {
461
+ constexpr int SH = 5 - log2_of(N);
462
+ const int lane = t & 31, warp = t >> 5;
463
+ halve<N, 16>(v, lane);
464
+ if ((lane & ((1 << SH) - 1)) == 0) red[(lane >> SH) * RED_LD + warp] = v[0];
465
+ __syncthreads();
466
+ if constexpr (N <= BS_SMALL) {
467
+ #pragma unroll
468
+ for (int j = 0; j < N; ++j) v[j] = red[j * RED_LD + lane];
469
+ halve<N, 16>(v, lane);
470
+ const float mine = v[0];
471
+ #pragma unroll
472
+ for (int j = 0; j < N; ++j) v[j] = __shfl_sync(0xffffffffu, mine, j << SH);
473
+ } else {
474
+ // warp w sums value w, the totals behind one more barrier: N x 5 shuffles a block, not 32 x 3N
475
+ if (warp < N) {
476
+ float x = red[warp * RED_LD + lane];
477
+ #pragma unroll
478
+ for (int o = 16; o > 0; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o);
479
+ if (lane == 0) red[warp * RED_LD + 32] = x;
480
+ }
481
+ __syncthreads();
482
+ #pragma unroll
483
+ for (int j = 0; j < N; ++j) v[j] = red[j * RED_LD + 32];
484
+ }
485
+ }
486
+
487
+ // block_sum over a row split into CL slices of SW warps on a cluster of CL blocks (the slices aligned to
488
+ // 32 vectors): each warp's first stage goes into its row-wide warp slot in every block's `red` (the
489
+ // slots past the row from the blocks' spare warps, zero), and once its own `red` holds all of them
490
+ // every block runs block_sum's second stage over the row's 32 slots: the same sums in the same order
491
+ // as one 1024-thread block. With a `bar`, the slots go out by st.async, each completing its bytes on the
492
+ // receiving block's mbarrier (armed with cluster_sum_bytes before a cluster barrier, phase 0): a block
493
+ // waits for its own bytes, not for a cluster barrier's round trip. Without, DSMEM stores and the
494
+ // cluster barrier: st.async a value is slower once a warp sends more than a few (32 values: +0.8 us).
495
+ template <int N, int CL, int SW>
496
+ constexpr unsigned cluster_sum_bytes = CL * (SW + 1) * N * 4;
497
+
498
+ __device__ __forceinline__ unsigned smem_u32(const void* p) { return (unsigned)__cvta_generic_to_shared(p); }
499
+
500
+ __device__ __forceinline__ void bar_arm(unsigned long long* bar, unsigned bytes) {
501
+ asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" ::"r"(smem_u32(bar)));
502
+ asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) : "memory");
503
+ }
504
+
505
+ template <int N, int CL, int SW, int W>
506
+ __device__ __forceinline__ void cluster_block_sum(float (&v)[N], float* red, unsigned long long* bar, int t) {
507
+ static_assert(CL * (SW + 1) == 32, "a row's 32 warp slots: SW a block, one zero slot a block");
508
+ constexpr int SH = 5 - log2_of(N);
509
+ cg::cluster_group cl = cg::this_cluster();
510
+ const int lane = t & 31, warp = t >> 5, me = cl.block_rank();
511
+ halve<N, 16>(v, lane);
512
+ const int slot = warp < SW ? me * SW + warp : CL * SW + me;
513
+ if (bar) {
514
+ if (warp <= SW && (lane & ((1 << SH) - 1)) == 0) {
515
+ const unsigned at = smem_u32(red + (lane >> SH) * RED_LD + slot), b = smem_u32(bar);
516
+ const unsigned x = __float_as_uint(warp < SW ? v[0] : 0.f);
517
+ #pragma unroll
518
+ for (int q = 0; q < CL; ++q) {
519
+ unsigned ra, rb;
520
+ asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(at), "r"(q));
521
+ asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(rb) : "r"(b), "r"(q));
522
+ asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.b32 [%0], %1, [%2];" ::"r"(ra), "r"(x),
523
+ "r"(rb) : "memory");
524
+ }
525
+ }
526
+ asm volatile(
527
+ "{\n .reg .pred p;\n WAIT_%=:\n mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], 0;\n"
528
+ " @!p bra WAIT_%=;\n}" ::"r"(smem_u32(bar))
529
+ : "memory");
530
+ } else {
531
+ if (warp <= SW && (lane & ((1 << SH) - 1)) == 0) {
532
+ #pragma unroll
533
+ for (int q = 0; q < CL; ++q) cl.map_shared_rank(red, q)[(lane >> SH) * RED_LD + slot] = warp < SW ? v[0] : 0.f;
534
+ }
535
+ cl.sync();
536
+ }
537
+ if constexpr (N <= BS_SMALL) {
538
+ #pragma unroll
539
+ for (int j = 0; j < N; ++j) v[j] = red[j * RED_LD + lane];
540
+ halve<N, 16>(v, lane);
541
+ const float mine = v[0];
542
+ #pragma unroll
543
+ for (int j = 0; j < N; ++j) v[j] = __shfl_sync(0xffffffffu, mine, j << SH);
544
+ } else {
545
+ for (int j = warp; j < N; j += W) {
546
+ float x = red[j * RED_LD + lane];
547
+ #pragma unroll
548
+ for (int o = 16; o > 0; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o);
549
+ if (lane == 0) red[j * RED_LD + 32] = x;
550
+ }
551
+ __syncthreads();
552
+ #pragma unroll
553
+ for (int j = 0; j < N; ++j) v[j] = red[j * RED_LD + 32];
554
+ }
555
+ }
556
+
557
+ // candidate x's sum of squares and dot with sw over this thread's eight
558
+ __device__ __forceinline__ void partial(const V8& x, const float* swv, float& sq, float& dp) {
559
+ sq = 0.f, dp = 0.f;
560
+ #pragma unroll
561
+ for (int j = 0; j < 4; ++j) {
562
+ const float2 f = bf2f(x.w[j]);
563
+ sq += f.x * f.x; sq += f.y * f.y;
564
+ dp += f.x * swv[2 * j]; dp += f.y * swv[2 * j + 1];
565
+ }
566
+ }
567
+
568
+ __device__ __forceinline__ V8 cand_at(const uint4* cand, int c, int t) {
569
+ V8 x;
570
+ x.w[0] = 0u, x.w[1] = 0u, x.w[2] = 0u, x.w[3] = 0u;
571
+ if (t < KVEC) x = asv(cand[c * KVEC + t]);
572
+ return x;
573
+ }
574
+
575
+ // Candidates 0..C-1 of the row (the snapshots, then the prefix `pv` when C = NB + 1): their
576
+ // totals, sq in tot[2c], dot in tot[2c + 1].
577
+ template <int NB, int C>
578
+ __device__ __forceinline__ void row_scores(const uint4* cand, const RowRegs& r, const V8& pv, float (&tot)[2 * C],
579
+ float* red, int t) {
580
+ constexpr int N = pow2_at_least(2 * C);
581
+ float v[N];
582
+ #pragma unroll
583
+ for (int j = 0; j < N; ++j) v[j] = 0.f;
584
+ if (NB > 0) asm volatile("cp.async.wait_all;" ::: "memory");
585
+ #pragma unroll
586
+ for (int c = 0; c < C; ++c) partial(c < NB ? cand_at(cand, c, t) : pv, r.swv, v[2 * c], v[2 * c + 1]);
587
+ block_sum<N>(v, red, t);
588
+ #pragma unroll
589
+ for (int j = 0; j < 2 * C; ++j) tot[j] = v[j];
590
+ }
591
+
592
+ __device__ __forceinline__ float score_of(float sq, float dp) { return dp * rsqrtf(sq * (1.0f / (float)KH) + KEPS); }
593
+
594
+ // The softmax's p_c = e_c / den: lane c divides, the warp broadcasts (k3_residual.cu's attnres_rms_row), not
595
+ // C divisions a thread: a row's epilogue on one SM of 1024 threads is issue-bound past a few snapshots.
596
+ template <int C>
597
+ __device__ __forceinline__ void softmax_div(float (&e)[C], float den, int lane) {
598
+ static_assert(C <= 32, "a candidate a lane");
599
+ float mine = e[0];
600
+ #pragma unroll
601
+ for (int c = 1; c < C; ++c) mine = lane == c ? e[c] : mine;
602
+ mine = mine / den;
603
+ #pragma unroll
604
+ for (int c = 0; c < C; ++c) e[c] = __shfl_sync(0xffffffffu, mine, c);
605
+ }
606
+
607
+ // The softmax over the candidates' scores, the mix, its rms, the output.
608
+ template <int NB>
609
+ __device__ __forceinline__ void row_mix_norm(const uint4* cand, const RowRegs& r, const V8& pv, float (&sc)[NB + 1],
610
+ bf16_t* __restrict__ normed_row, int t, RowSmem& s) {
611
+ const bool act = (t < KVEC);
612
+ V8 mixed = pv;
613
+ if constexpr (NB > 0) {
614
+ float mx = -3.0e38f, den = 0.f;
615
+ #pragma unroll
616
+ for (int c = 0; c <= NB; ++c) mx = fmaxf(mx, sc[c]);
617
+ #pragma unroll
618
+ for (int c = 0; c <= NB; ++c) den += (sc[c] = __expf(sc[c] - mx));
619
+ softmax_div(sc, den, t & 31);
620
+ float acc[8];
621
+ #pragma unroll
622
+ for (int j = 0; j < 8; ++j) acc[j] = 0.f;
623
+ #pragma unroll
624
+ for (int c = 0; c <= NB; ++c) {
625
+ const float p = sc[c];
626
+ const V8 x = c < NB ? cand_at(cand, c, t) : pv;
627
+ #pragma unroll
628
+ for (int j = 0; j < 4; ++j) {
629
+ const float2 f = bf2f(x.w[j]);
630
+ acc[2 * j] += p * f.x;
631
+ acc[2 * j + 1] += p * f.y;
632
+ }
633
+ }
634
+ #pragma unroll
635
+ for (int j = 0; j < 4; ++j) mixed.w[j] = f2bf(make_float2(acc[2 * j], acc[2 * j + 1]));
636
+ }
637
+ float sq[1] = {0.f};
638
+ if (act) {
639
+ #pragma unroll
640
+ for (int j = 0; j < 4; ++j) {
641
+ const float2 f = bf2f(mixed.w[j]);
642
+ sq[0] += f.x * f.x; sq[0] += f.y * f.y;
643
+ }
644
+ }
645
+ block_sum<1>(sq, s.red[2], t);
646
+ const float rr = rsqrtf(sq[0] * (1.0f / (float)KH) + KEPS);
647
+ if (act) {
648
+ V8 o;
649
+ #pragma unroll
650
+ for (int j = 0; j < 4; ++j) {
651
+ float2 f = bf2f(mixed.w[j]);
652
+ f.x *= rr; f.y *= rr;
653
+ o.w[j] = from_bf162(__hmul2(__float22bfloat162_rn(f), as_bf162(r.g.w[j])));
654
+ }
655
+ stv(normed_row + t * 8, o);
656
+ }
657
+ }
658
+
659
+ // The snapshots' scores (sc[0..NB)), which need no prefix row: before the poll or the grid wait.
660
+ template <int NB>
661
+ __device__ __forceinline__ void row_snap_scores(const uint4* cand, const RowRegs& r, float (&sc)[NB + 1], RowSmem& s,
662
+ int t) {
663
+ if constexpr (NB > 0) {
664
+ float snap[2 * NB];
665
+ V8 none;
666
+ none.w[0] = 0u, none.w[1] = 0u, none.w[2] = 0u, none.w[3] = 0u;
667
+ row_scores<NB, NB>(cand, r, none, snap, s.red[0], t);
668
+ #pragma unroll
669
+ for (int c = 0; c < NB; ++c) sc[c] = score_of(snap[2 * c], snap[2 * c + 1]);
670
+ }
671
+ }
672
+
673
+ // The prefix row's score (sc[NB]), the mix, the norm.
674
+ template <int NB>
675
+ __device__ __forceinline__ void row_prefix_finish(const uint4* cand, const RowRegs& r, const V8& pv, float (&sc)[NB + 1],
676
+ bf16_t* __restrict__ normed_row, int t, RowSmem& s) {
677
+ if constexpr (NB > 0) {
678
+ float pvs[2] = {0.f, 0.f};
679
+ if (t < KVEC) partial(pv, r.swv, pvs[0], pvs[1]);
680
+ block_sum<2>(pvs, s.red[1], t);
681
+ sc[NB] = score_of(pvs[0], pvs[1]);
682
+ }
683
+ row_mix_norm<NB>(cand, r, pv, sc, normed_row, t, s);
684
+ }
685
+
686
+ // The whole routine once the prefix row `pv` is known: every candidate scored in one reduction.
687
+ template <int NB>
688
+ __device__ __forceinline__ void row_finish(const uint4* cand, const RowRegs& r, const V8& pv,
689
+ bf16_t* __restrict__ normed_row, int t, RowSmem& s) {
690
+ float tot[2 * NB + 2], sc[NB + 1];
691
+ row_scores<NB, NB + 1>(cand, r, pv, tot, s.red[0], t);
692
+ #pragma unroll
693
+ for (int c = 0; c <= NB; ++c) sc[c] = score_of(tot[2 * c], tot[2 * c + 1]);
694
+ row_mix_norm<NB>(cand, r, pv, sc, normed_row, t, s);
695
+ }
696
+
697
+ #define NB_ENTRIES(entry) entry(0) entry(1) entry(2) entry(3) entry(4) entry(5) entry(6) entry(7) entry(8)
698
+
699
+ // ---------------------------------------------------------------- attention all-reduce + K1b
700
+ template <int NB>
701
+ __device__ __forceinline__ void ar_attnres_rms(const uint4* __restrict__ x, uint8_t* lamport,
702
+ const unsigned long long* lamport_peers, int* state, int* err, int rank,
703
+ const bf16_t* __restrict__ prefix, const bf16_t* __restrict__ blocks,
704
+ const float* __restrict__ sw, const bf16_t* __restrict__ gamma,
705
+ bf16_t* __restrict__ prefix2, bf16_t* __restrict__ normed, int snapshot,
706
+ int B, long long stage_bytes, long long timeout_ns,
707
+ const uint8_t* __restrict__ pf, long long pf_bytes,
708
+ const uint8_t* __restrict__ dm, long long dm_bytes, uint4* cand,
709
+ RowSmem& s) {
710
+ const int t = threadIdx.x, b = blockIdx.x;
711
+ const bool row = b < B, act = t < KVEC;
712
+ const size_t off = (size_t)b * KH + t * 8;
713
+ const long long tot = (long long)B * KVEC, i = share(tot, B);
714
+ RowRegs r;
715
+ V8 pr;
716
+ pr.w[0] = 0u, pr.w[1] = 0u, pr.w[2] = 0u, pr.w[3] = 0u;
717
+ if (row) {
718
+ r = row_prefetch<NB>(blocks + (size_t)b * KNB_MAX * KH, sw, gamma, cand, t);
719
+ if (act && !snapshot) pr = ldv(prefix + off);
720
+ }
721
+ const Lamport l = lamport_open(lamport, lamport_peers, state, err, rank, tot, stage_bytes, timeout_ns);
722
+ grid_wait();
723
+ const uint4 v = i >= 0 ? x[i] : make_uint4(0u, 0u, 0u, 0u);
724
+ const bool two = B >= TWO_SHOT_ROWS; // as kern_k3_ar_finalize_rms's
725
+ if (i >= 0) {
726
+ if (two)
727
+ l.slot[(i / KVEC) % NRANKS][i] = unpoison4(v);
728
+ else
729
+ lamport_push(l, i, v);
730
+ }
731
+ if (ANY_BATCH && two)
732
+ for (long long j = two_shot_rest(); j < tot; j += PUSH_STRIDE) l.slot[(j / KVEC) % NRANKS][j] = unpoison4(x[j]);
733
+ lamport_clear(l, rank);
734
+ unsigned* const stamp = l2_stamp(state, l);
735
+ l2_load_while(pf, pf_bytes, B, stamp, AR_GRACE_NS, state + 7);
736
+ l2_demote(dm, dm_bytes, B);
737
+
738
+ int fail = 0;
739
+ for (int q = b; block_row(q, b, B); q += KGRID) {
740
+ if (two && q == b) // every gather out before the first row's wait
741
+ for (int g = b; block_row(g, b, B); g += KGRID)
742
+ if (g % NRANKS != rank) gather_share<KVEC>(l, rank, B, g, timeout_ns, fail);
743
+ const size_t at = (size_t)q * KH + t * 8;
744
+ if (ANY_BATCH && q != b) { // a row past the grid's first: the last row's reads of cand and s done first
745
+ __syncthreads();
746
+ r = row_prefetch<NB>(blocks + (size_t)q * KNB_MAX * KH, sw, gamma, cand, t);
747
+ if (act && !snapshot) pr = ldv(prefix + at);
748
+ }
749
+ float sc[NB + 1];
750
+ row_snap_scores<NB>(cand, r, sc, s, t);
751
+ V8 pv;
752
+ pv.w[0] = 0u, pv.w[1] = 0u, pv.w[2] = 0u, pv.w[3] = 0u;
753
+ if (act) {
754
+ const long long i = (long long)q * KVEC + t;
755
+ const int owner = q % NRANKS;
756
+ const V8 lp = asv(lamport_get(l, two, owner, rank, i, timeout_ns, fail));
757
+ l2_arrive(stamp);
758
+ if (snapshot) {
759
+ pv = lp;
760
+ } else {
761
+ #pragma unroll
762
+ for (int j = 0; j < 4; ++j) {
763
+ const float2 rf = bf2f(pr.w[j]), lf = bf2f(lp.w[j]);
764
+ pv.w[j] = f2bf(make_float2(rf.x + lf.x, rf.y + lf.y));
765
+ }
766
+ }
767
+ stv(prefix2 + at, pv);
768
+ }
769
+ row_prefix_finish<NB>(cand, r, pv, sc, normed + (size_t)q * KH, t, s);
770
+ }
771
+ lamport_close(l, state, err, fail, B, KVEC);
772
+ }
773
+
774
+ #define AR_ATTNRES_ENTRY(NB) \
775
+ extern "C" __global__ void __launch_bounds__(KTHREADS, 1) kern_k3_ar_attnres_rms_nb##NB( \
776
+ const uint4* __restrict__ x, uint8_t* lamport, const unsigned long long* lamport_peers, int* state, int* err, \
777
+ int rank, const bf16_t* __restrict__ prefix, const bf16_t* __restrict__ blocks, const float* __restrict__ sw, \
778
+ const bf16_t* __restrict__ gamma, bf16_t* __restrict__ prefix2, bf16_t* __restrict__ normed, int snapshot, \
779
+ int B, long long stage_bytes, long long timeout_ns, const uint8_t* __restrict__ pf, long long pf_bytes, \
780
+ const uint8_t* __restrict__ dm, long long dm_bytes) { \
781
+ extern __shared__ uint4 cand[]; \
782
+ __shared__ RowSmem s; \
783
+ ar_attnres_rms<NB>(x, lamport, lamport_peers, state, err, rank, prefix, blocks, sw, gamma, prefix2, normed, \
784
+ snapshot, B, stage_bytes, timeout_ns, pf, pf_bytes, dm, dm_bytes, cand, s); \
785
+ }
786
+ NB_ENTRIES(AR_ATTNRES_ENTRY)
787
+
788
+ // ---------------------------------------------------------------- K1d
789
+ // k3_residual.cu's K1c on bf16 partials then K1a: hidden = bf16(prefix2 + p1 + (two ? p2 : 0))
790
+ // written (and snapshotted into blocks[b, nb] when `snapshot`), then normed = rms(attnres(
791
+ // blocks, hidden, nb), gamma): a layer's closing add fused into the next layer's mix.
792
+ // A row over a cluster of LAND_CL blocks of 1024 / LAND_CL threads, each a slice of LV vectors, its
793
+ // reductions the 1024-thread block's over DSMEM (a row on one SM is bound by its arithmetic and
794
+ // barriers, ~0.4 us a snapshot).
795
+ #define LAND_CL 4
796
+ #define LV (KVEC / LAND_CL)
797
+ #define LT (KTHREADS / LAND_CL)
798
+
799
+ struct LandSmem {
800
+ float red[2][32 * RED_LD];
801
+ unsigned long long bar; // the norm's (cluster_block_sum)
802
+ };
803
+
804
+ // The gather of p1's column slices: vector v of row b sits in slot b * KVEC + v of a stage, written only by
805
+ // its owner (v / GVEC_OWN), so a stage holds a row once. Row b's cluster pushes this rank's GVEC_OWN vectors
806
+ // into the NRANKS - 1 peers' stages a store a thread, then every thread waits for its own vector, takes it and
807
+ // re-poisons the slot. A bf16 -0.0 goes as +0.0 (the all-reduces' rule), this rank's own vectors too, so every
808
+ // rank lands the same row. Two stages alternate by call (`phase`, the generator's count): a peer comes round
809
+ // to a stage again two calls on, past an all-reduce that waited for this rank's re-poison. The first call
810
+ // needs no handshake: the attention all-reduce before it has seen every member through its once-program,
811
+ // which poisons the stages.
812
+ #define GVEC_OWN (KVEC / NRANKS)
813
+ #define LAND_ROWS_MAX 256 // gen_stage.py's D_SEQS_MAX: a stage's rows
814
+ static_assert(KVEC % NRANKS == 0 && (NRANKS - 1) * GVEC_OWN <= KTHREADS, "a push a thread of the row's cluster");
815
+
816
+ struct Gather {
817
+ uint8_t* stage;
818
+ const unsigned long long* peers;
819
+ int* err;
820
+ int rank, phase;
821
+ long long timeout_ns;
822
+ };
823
+
824
+ __device__ __forceinline__ void gather_push(const Gather& g, const bf16_t* __restrict__ p1, int b, int k) {
825
+ if (k >= (NRANKS - 1) * GVEC_OWN) return;
826
+ const int j = k % GVEC_OWN, q = k / GVEC_OWN, peer = q + (q >= g.rank);
827
+ const uint4 v = unpoison4(*reinterpret_cast<const uint4*>(p1 + ((size_t)b * GVEC_OWN + j) * 8));
828
+ const long long slot = (long long)g.phase * LAND_ROWS_MAX * KVEC + (long long)b * KVEC + g.rank * GVEC_OWN + j;
829
+ reinterpret_cast<uint4*>(g.peers[peer])[slot] = v;
830
+ }
831
+
832
+ __device__ __forceinline__ V8 gather_take(const Gather& g, const bf16_t* __restrict__ p1, int b, int vi) {
833
+ const int owner = vi / GVEC_OWN;
834
+ uint4 x;
835
+ if (owner == g.rank) {
836
+ x = unpoison4(*reinterpret_cast<const uint4*>(p1 + ((size_t)b * GVEC_OWN + vi - owner * GVEC_OWN) * 8));
837
+ } else {
838
+ uint4* slot = reinterpret_cast<uint4*>(g.stage) + (long long)g.phase * LAND_ROWS_MAX * KVEC + (long long)b * KVEC + vi;
839
+ x = ld_volatile(slot);
840
+ const long long t0 = dl_now();
841
+ while (!arrived(x)) {
842
+ if (dl_past(t0, g.timeout_ns)) give_up(g.err, 1 + owner);
843
+ x = ld_volatile(slot);
844
+ }
845
+ *slot = make_uint4(0x80008000u, 0x80008000u, 0x80008000u, 0x80008000u);
846
+ }
847
+ return asv(x);
848
+ }
849
+
850
+ template <int NB, bool GATHER>
851
+ __device__ __forceinline__ void land_add2_attnres_rms(const bf16_t* __restrict__ p1, const bf16_t* __restrict__ p2,
852
+ const bf16_t* __restrict__ prefix2, bf16_t* __restrict__ hidden,
853
+ int two, bf16_t* __restrict__ blocks, const float* __restrict__ sw,
854
+ const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed,
855
+ int snapshot, uint4* cand, LandSmem& s, const Gather& gat) {
856
+ const int b = blockIdx.x / LAND_CL, t = threadIdx.x, v0 = (blockIdx.x % LAND_CL) * LV;
857
+ const bool act = t < LV;
858
+ const size_t off = (size_t)b * KH + (v0 + t) * 8;
859
+ const bf16_t* blk_row = blocks + (size_t)b * KNB_MAX * KH;
860
+ float swv[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
861
+ V8 g, pr;
862
+ g.w[0] = g.w[1] = g.w[2] = g.w[3] = 0u;
863
+ pr = g;
864
+ if (act) {
865
+ #pragma unroll
866
+ for (int c = 0; c < NB; ++c) {
867
+ const unsigned dst = (unsigned)__cvta_generic_to_shared(cand + c * LV + t);
868
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" ::"r"(dst), "l"(blk_row + (size_t)c * KH + (v0 + t) * 8));
869
+ }
870
+ if (NB > 0) {
871
+ const float4* sp4 = (const float4*)(sw + (v0 + t) * 8);
872
+ const float4 a = sp4[0], c = sp4[1];
873
+ swv[0] = a.x; swv[1] = a.y; swv[2] = a.z; swv[3] = a.w;
874
+ swv[4] = c.x; swv[5] = c.y; swv[6] = c.z; swv[7] = c.w;
875
+ }
876
+ g = ldv(gamma + (v0 + t) * 8);
877
+ pr = ldv(prefix2 + off);
878
+ }
879
+ asm volatile("cp.async.commit_group;");
880
+ // the norm's mbarrier, armed before the scores' cluster barrier: no slot of the norm is sent before it
881
+ if (NB > 0 && t == 0) {
882
+ bar_arm(&s.bar, cluster_sum_bytes<1, LAND_CL, LV / 32>);
883
+ asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
884
+ }
885
+ grid_wait();
886
+ if constexpr (GATHER) gather_push(gat, p1, b, (blockIdx.x % LAND_CL) * LT + t);
887
+ V8 pv = pr;
888
+ if (act) {
889
+ const V8 a = GATHER ? gather_take(gat, p1, b, v0 + t) : ldv(p1 + off);
890
+ V8 c;
891
+ if (two) c = ldv(p2 + off);
892
+ #pragma unroll
893
+ for (int j = 0; j < 4; ++j) {
894
+ const float2 rf = bf2f(pr.w[j]), l1 = bf2f(a.w[j]);
895
+ float x = rf.x + l1.x, y = rf.y + l1.y;
896
+ if (two) {
897
+ const float2 l2 = bf2f(c.w[j]);
898
+ x += l2.x;
899
+ y += l2.y;
900
+ }
901
+ pv.w[j] = f2bf(make_float2(x, y));
902
+ }
903
+ stv(hidden + off, pv);
904
+ if (snapshot && NB < KNB_MAX) stv(blocks + ((size_t)b * KNB_MAX + NB) * KH + (v0 + t) * 8, pv);
905
+ }
906
+ const auto cand_v = [&](int c) {
907
+ V8 x;
908
+ x.w[0] = x.w[1] = x.w[2] = x.w[3] = 0u;
909
+ if (act) x = asv(cand[c * LV + t]);
910
+ return x;
911
+ };
912
+ V8 mixed = pv;
913
+ if constexpr (NB > 0) {
914
+ constexpr int N = pow2_at_least(2 * NB + 2);
915
+ float v[N];
916
+ #pragma unroll
917
+ for (int j = 0; j < N; ++j) v[j] = 0.f;
918
+ asm volatile("cp.async.wait_all;" ::: "memory");
919
+ if (act) {
920
+ #pragma unroll
921
+ for (int c = 0; c <= NB; ++c) partial(c < NB ? cand_v(c) : pv, swv, v[2 * c], v[2 * c + 1]);
922
+ }
923
+ cluster_block_sum<N, LAND_CL, LV / 32, LT / 32>(v, s.red[0], nullptr, t);
924
+ float sc[NB + 1], mx = -3.0e38f, den = 0.f;
925
+ #pragma unroll
926
+ for (int c = 0; c <= NB; ++c) mx = fmaxf(mx, sc[c] = score_of(v[2 * c], v[2 * c + 1]));
927
+ #pragma unroll
928
+ for (int c = 0; c <= NB; ++c) den += (sc[c] = __expf(sc[c] - mx));
929
+ float acc[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
930
+ #pragma unroll
931
+ for (int c = 0; c <= NB; ++c) {
932
+ const float p = sc[c] / den;
933
+ const V8 x = c < NB ? cand_v(c) : pv;
934
+ #pragma unroll
935
+ for (int j = 0; j < 4; ++j) {
936
+ const float2 f = bf2f(x.w[j]);
937
+ acc[2 * j] += p * f.x;
938
+ acc[2 * j + 1] += p * f.y;
939
+ }
940
+ }
941
+ #pragma unroll
942
+ for (int j = 0; j < 4; ++j) mixed.w[j] = f2bf(make_float2(acc[2 * j], acc[2 * j + 1]));
943
+ }
944
+ float sq[1] = {0.f};
945
+ if (act) {
946
+ #pragma unroll
947
+ for (int j = 0; j < 4; ++j) {
948
+ const float2 f = bf2f(mixed.w[j]);
949
+ sq[0] += f.x * f.x; sq[0] += f.y * f.y;
950
+ }
951
+ }
952
+ cluster_block_sum<1, LAND_CL, LV / 32, LT / 32>(sq, s.red[1], NB > 0 ? &s.bar : nullptr, t);
953
+ const float rr = rsqrtf(sq[0] * (1.0f / (float)KH) + KEPS);
954
+ if (act) {
955
+ V8 o;
956
+ #pragma unroll
957
+ for (int j = 0; j < 4; ++j) {
958
+ float2 f = bf2f(mixed.w[j]);
959
+ f.x *= rr; f.y *= rr;
960
+ o.w[j] = from_bf162(__hmul2(__float22bfloat162_rn(f), as_bf162(g.w[j])));
961
+ }
962
+ stv(normed + off, o);
963
+ }
964
+ }
965
+
966
+ // the idle blocks' hints after lat_up (the kernel before) is done: not on top of its own weight stream
967
+ #define LAND_ENTRY(NB) \
968
+ extern "C" __global__ void __launch_bounds__(LT, 1) kern_k3_land_add2_attnres_rms_nb##NB( \
969
+ const bf16_t* __restrict__ p1, const bf16_t* __restrict__ p2, const bf16_t* __restrict__ prefix2, \
970
+ bf16_t* __restrict__ hidden, int two, bf16_t* __restrict__ blocks, const float* __restrict__ sw, \
971
+ const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed, int snapshot, int B, \
972
+ const uint8_t* __restrict__ pf, long long pf_bytes) { \
973
+ extern __shared__ uint4 cand[]; \
974
+ __shared__ LandSmem s; \
975
+ asm volatile("griddepcontrol.launch_dependents;"); \
976
+ if ((int)blockIdx.x >= LAND_CL * B) return grid_wait(), l2_prefetch(pf, pf_bytes, LAND_CL * B); \
977
+ land_add2_attnres_rms<NB, false>(p1, p2, prefix2, hidden, two, blocks, sw, gamma, normed, snapshot, cand, s, \
978
+ Gather{}); \
979
+ }
980
+ NB_ENTRIES(LAND_ENTRY)
981
+
982
+ #define GATHER_ENTRY(NB) \
983
+ extern "C" __global__ void __launch_bounds__(LT, 1) kern_k3_land_gather_attnres_rms_nb##NB( \
984
+ const bf16_t* __restrict__ p1, const bf16_t* __restrict__ p2, const bf16_t* __restrict__ prefix2, \
985
+ bf16_t* __restrict__ hidden, int two, bf16_t* __restrict__ blocks, const float* __restrict__ sw, \
986
+ const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed, int snapshot, int B, uint8_t* stage, \
987
+ const unsigned long long* peers, int* err, int rank, int phase, long long timeout_ns, \
988
+ const uint8_t* __restrict__ pf, long long pf_bytes) { \
989
+ extern __shared__ uint4 cand[]; \
990
+ __shared__ LandSmem s; \
991
+ asm volatile("griddepcontrol.launch_dependents;"); \
992
+ if ((int)blockIdx.x >= LAND_CL * B) return grid_wait(), l2_prefetch(pf, pf_bytes, LAND_CL * B); \
993
+ land_add2_attnres_rms<NB, true>(p1, p2, prefix2, hidden, two, blocks, sw, gamma, normed, snapshot, cand, s, \
994
+ Gather{stage, peers, err, rank, phase, timeout_ns}); \
995
+ }
996
+ NB_ENTRIES(GATHER_ENTRY)
997
+
998
+ // ---------------------------------------------------------------- MoE finalize + all-reduce + latent rms
999
+ // A row's exchange: the latent's KLATV vectors, then the shared expert's KVEC.
1000
+ #define ROWV (KLATV + KVEC)
1001
+ // a block's one-shot push share is one vector a thread
1002
+ static_assert(((TWO_SHOT_ROWS * ROWV + PUSH_RUN - 1) / PUSH_RUN + KGRID - 1) / KGRID * PUSH_RUN <= KTHREADS,
1003
+ "a push share past KTHREADS");
1004
+
1005
+ // kern_k3_moe_finalize's column vector h of a row, its top-k (exp2perm, wts) in shared memory, or past the
1006
+ // first push pass in global memory
1007
+ __device__ __forceinline__ uint4 finalize(const bf16_t* __restrict__ fc2, const int* e2p, const float* w16, int h) {
1008
+ float acc[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
1009
+ #pragma unroll
1010
+ for (int k = 0; k < TOPK; ++k) {
1011
+ const int p = e2p[k];
1012
+ if (p < 0) continue;
1013
+ const float w = w16[k];
1014
+ const uint4 u = reinterpret_cast<const uint4*>(fc2 + (long long)p * KLAT)[h];
1015
+ const __nv_bfloat162* v = reinterpret_cast<const __nv_bfloat162*>(&u);
1016
+ #pragma unroll
1017
+ for (int j = 0; j < 4; ++j) {
1018
+ const float2 f = __bfloat1622float2(v[j]);
1019
+ acc[2 * j] += w * f.x;
1020
+ acc[2 * j + 1] += w * f.y;
1021
+ }
1022
+ }
1023
+ uint4 o;
1024
+ __nv_bfloat162* ov = reinterpret_cast<__nv_bfloat162*>(&o);
1025
+ #pragma unroll
1026
+ for (int j = 0; j < 4; ++j) ov[j] = __floats2bfloat162_rn(acc[2 * j], acc[2 * j + 1]);
1027
+ return o;
1028
+ }
1029
+
1030
+ extern "C" __global__ void __launch_bounds__(KTHREADS, 1) kern_k3_ar_finalize_rms(
1031
+ const bf16_t* __restrict__ fc2, const int* __restrict__ exp2perm, const float* __restrict__ wts,
1032
+ const uint4* __restrict__ shared, uint8_t* lamport, const unsigned long long* lamport_peers, int* state, int* err,
1033
+ int rank, const bf16_t* __restrict__ gamma, bf16_t* __restrict__ latent_norm, uint4* __restrict__ shared_sum, int B,
1034
+ long long stage_bytes, long long timeout_ns, const uint8_t* __restrict__ pf, long long pf_bytes,
1035
+ const uint8_t* __restrict__ pf2, long long pf2_bytes) {
1036
+ __shared__ float red[32 * RED_LD];
1037
+ const int t = threadIdx.x, b = blockIdx.x;
1038
+ const long long tot = (long long)B * ROWV, i = share(tot, B);
1039
+ const int row = (int)(i / ROWV), c = (int)(i % ROWV);
1040
+ // the top-k of the (at most two) rows this block's share spans, written by moe_front
1041
+ __shared__ int s_e2p[2][TOPK];
1042
+ __shared__ float s_w[2][TOPK];
1043
+ const int row0 = (B >= TWO_SHOT_ROWS ? b * KTHREADS : share_per(tot) * b) / ROWV;
1044
+ if (t < 2 * TOPK && row0 + t / TOPK < B) {
1045
+ s_e2p[t / TOPK][t % TOPK] = exp2perm[(row0 + t / TOPK) * TOPK + t % TOPK];
1046
+ s_w[t / TOPK][t % TOPK] = wts[(row0 + t / TOPK) * TOPK + t % TOPK];
1047
+ }
1048
+ const Lamport l = lamport_open(lamport, lamport_peers, state, err, rank, tot, stage_bytes, timeout_ns);
1049
+ grid_wait();
1050
+ uint4 v = i >= 0 && c < KLATV ? finalize(fc2, s_e2p[row - row0], s_w[row - row0], c) : make_uint4(0u, 0u, 0u, 0u);
1051
+ if (i >= 0 && c >= KLATV) v = shared[(long long)row * KVEC + c - KLATV];
1052
+ // From TWO_SHOT_ROWS rows the sum runs as two shots: every row goes to its owner (row % NRANKS) only, the
1053
+ // owner sums it and gathers the sum to the others (gather_share), 2 x 7/8 of a partial out of each rank
1054
+ // instead of 7.
1055
+ const bool two = B >= TWO_SHOT_ROWS;
1056
+ if (i >= 0) {
1057
+ if (two)
1058
+ l.slot[row % NRANKS][i] = unpoison4(v);
1059
+ else
1060
+ lamport_push(l, i, v);
1061
+ }
1062
+ if (ANY_BATCH && two)
1063
+ for (long long j = two_shot_rest(); j < tot; j += PUSH_STRIDE) {
1064
+ const int rj = (int)(j / ROWV), cj = (int)(j % ROWV);
1065
+ const uint4 u = cj < KLATV ? finalize(fc2, exp2perm + rj * TOPK, wts + rj * TOPK, cj)
1066
+ : shared[(long long)rj * KVEC + cj - KLATV];
1067
+ l.slot[rj % NRANKS][j] = unpoison4(u);
1068
+ }
1069
+ lamport_clear(l, rank);
1070
+ unsigned* const stamp = l2_stamp(state, l);
1071
+ l2_load_while(pf, pf_bytes, B, stamp, FIN_GRACE_NS, state + 7);
1072
+ l2_load_while<true>(pf2, pf2_bytes, B, stamp, FIN_GRACE_NS, state + 7);
1073
+
1074
+ int fail = 0;
1075
+ for (int q = b; block_row(q, b, B); q += KGRID) {
1076
+ if (two && q == b) // every gather out before the first row's wait
1077
+ for (int g = b; block_row(g, b, B); g += KGRID)
1078
+ if (g % NRANKS != rank) gather_share<ROWV>(l, rank, B, g, timeout_ns, fail);
1079
+ const long long base = (long long)q * ROWV;
1080
+ const int owner = q % NRANKS;
1081
+ // Two-shot, the block waits for its gathers, then for the row's shared half, before any thread polls the
1082
+ // next thing: warps that run ahead spin on slots still empty, and their polls slow everyone's (10.5 -> 9.0 us
1083
+ // at 36 rows; one-shot the second wait costs 0.2-0.4, so not there). The barrier also keeps a row past the
1084
+ // grid's first off the last row's `red`.
1085
+ if (two) __syncthreads();
1086
+ const auto summed = [&](long long i) { return lamport_get(l, two, owner, rank, i, timeout_ns, fail); };
1087
+ if (t < KVEC) shared_sum[(long long)q * KVEC + t] = summed(base + KLATV + t);
1088
+ if (two) __syncthreads();
1089
+ l2_arrive(stamp);
1090
+ // kern_k3_rms at h = KLAT: vector t of the row, its squares serially, a warp
1091
+ // butterfly, then the 32 warp slots (zero past the row) by another, in every warp
1092
+ uint4 x = make_uint4(0u, 0u, 0u, 0u), g;
1093
+ float sum = 0.f;
1094
+ if (t < KLATV) {
1095
+ x = summed(base + t);
1096
+ g = reinterpret_cast<const uint4*>(gamma)[t];
1097
+ const V8 v = asv(x);
1098
+ #pragma unroll
1099
+ for (int j = 0; j < 4; ++j) {
1100
+ const float2 f = bf2f(v.w[j]);
1101
+ sum += f.x * f.x;
1102
+ sum += f.y * f.y;
1103
+ }
1104
+ }
1105
+ float tot[1] = {sum};
1106
+ block_sum<1>(tot, red, t);
1107
+ const float rs = rsqrtf(tot[0] / (float)KLAT + 1e-5f);
1108
+ if (t < KLATV) {
1109
+ const V8 v = asv(x), gv = asv(g);
1110
+ V8 o;
1111
+ #pragma unroll
1112
+ for (int j = 0; j < 4; ++j) {
1113
+ const float2 f = bf2f(v.w[j]);
1114
+ o.w[j] = from_bf162(__hmul2(__floats2bfloat162_rn(f.x * rs, f.y * rs), as_bf162(gv.w[j])));
1115
+ }
1116
+ stv(latent_norm + (long long)q * KLAT + t * 8, o);
1117
+ }
1118
+ }
1119
+ lamport_close(l, state, err, fail, B, ROWV);
1120
+ }
1121
+
1122
+ // ---------------------------------------------------------------- embedding + K1a of the first layer
1123
+ // hidden = embed[ids[b]] (written, and snapshot 0 of blocks), normed = rms(hidden, gamma): the
1124
+ // gather and the first layer's attnres_rms with no snapshot to mix (nb = 0, the mix is the row).
1125
+ // kern_k3_embed_rms_plan also writes row b's MLA split count: kern's k3_mla_split_plan.cu sizes
1126
+ // splits to fill one wave of clusters; here the batch fills the 1 to MLA_WAVES waves of the least
1127
+ // modelled time (one wave of 48 rows held one split a row on 96 of 152 SMs). The plan needs only
1128
+ // every row's tile count: block B works it out for every row while the row blocks gather and norm.
1129
+ // kern_k3_embed_rms(const i64* ids, const bf16* table, bf16* hidden, bf16* blocks,
1130
+ // const bf16* gamma, bf16* normed, int B) grid (B, 1, 1)
1131
+ // kern_k3_embed_rms_plan(..., const i32* seq_lens, i32* block_split_kvs, int split_max, int B)
1132
+ // grid (B + 1, 1, 1)
1133
+ // block (1024, 1, 1)
1134
+ #define MLA_TILE 128
1135
+ // A wave of n 2-CTA clusters runs a tile in ~1.46 us a cluster up to ~53 clusters; past that the GPU runs ~36
1136
+ // tiles a us (96 heads, bf16 MMA padded to 128 rows: the tensor pipes and HBM both near their limit); a
1137
+ // split also writes and the exchange reads back its f32 partial, ~2 tiles of traffic. So a wave of n
1138
+ // clusters at `longest` tiles a split costs (longest + 2) * max(53, n). A batch fills up to MLA_WAVES.
1139
+ #define MLA_SATURATE 53
1140
+ #define MLA_SPLIT_TILES 2
1141
+ #define MLA_WAVES 3
1142
+
1143
+ __device__ __forceinline__ int warp_sum_i(int v) {
1144
+ #pragma unroll
1145
+ for (int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
1146
+ return v;
1147
+ }
1148
+ __device__ __forceinline__ int warp_max_i(int v) {
1149
+ #pragma unroll
1150
+ for (int o = 16; o; o >>= 1) v = max(v, __shfl_xor_sync(0xffffffffu, v, o));
1151
+ return v;
1152
+ }
1153
+ // kern's k3_mla_split_plan.cu: `per` tiles a split over `budget` clusters, a row's splits from it (32-bit: a
1154
+ // batch's tiles are at most 64 x 2560)
1155
+ __device__ __forceinline__ int split_per(int total, int budget) {
1156
+ budget = max(budget, 1);
1157
+ return max((total + budget - 1) / budget, 1);
1158
+ }
1159
+ __device__ __forceinline__ int row_splits(int tiles, int per, int split_max) {
1160
+ return min(max((tiles + per - 1) / per, 1), split_max);
1161
+ }
1162
+
1163
+ // the gathered row, its stores, then the norm (nb = 0)
1164
+ __device__ __forceinline__ V8 embed_row(const long long* __restrict__ ids, const bf16_t* __restrict__ table, int b,
1165
+ int t) {
1166
+ V8 pv;
1167
+ pv.w[0] = 0u, pv.w[1] = 0u, pv.w[2] = 0u, pv.w[3] = 0u;
1168
+ if (t < KVEC) pv = ldv(table + ids[b] * KH + t * 8);
1169
+ return pv;
1170
+ }
1171
+ __device__ __forceinline__ void embed_rms(const V8& pv, bf16_t* __restrict__ hidden, bf16_t* __restrict__ blocks,
1172
+ const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed, int b,
1173
+ int t) {
1174
+ __shared__ RowSmem s;
1175
+ const RowRegs r = row_prefetch<0>(blocks, nullptr, gamma, nullptr, t);
1176
+ if (t < KVEC) {
1177
+ stv(hidden + (size_t)b * KH + t * 8, pv);
1178
+ stv(blocks + (size_t)b * KNB_MAX * KH + t * 8, pv);
1179
+ }
1180
+ row_finish<0>(nullptr, r, pv, normed + (size_t)b * KH, t, s);
1181
+ }
1182
+
1183
+ extern "C" __global__ void __launch_bounds__(KTHREADS, 1) kern_k3_embed_rms(
1184
+ const long long* __restrict__ ids, const bf16_t* __restrict__ table, bf16_t* __restrict__ hidden,
1185
+ bf16_t* __restrict__ blocks, const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed, int B) {
1186
+ asm volatile("griddepcontrol.launch_dependents;");
1187
+ if (blockIdx.x >= B) return;
1188
+ embed_rms(embed_row(ids, table, blockIdx.x, threadIdx.x), hidden, blocks, gamma, normed, blockIdx.x, threadIdx.x);
1189
+ }
1190
+
1191
+ extern "C" __global__ void __launch_bounds__(KTHREADS, 1) kern_k3_embed_rms_plan(
1192
+ const long long* __restrict__ ids, const bf16_t* __restrict__ table, bf16_t* __restrict__ hidden,
1193
+ bf16_t* __restrict__ blocks, const bf16_t* __restrict__ gamma, bf16_t* __restrict__ normed,
1194
+ const int* __restrict__ seq_lens, int* __restrict__ block_split_kvs, int split_max, int B) {
1195
+ asm volatile("griddepcontrol.launch_dependents;");
1196
+ const int b = blockIdx.x, t = threadIdx.x;
1197
+ if (b < B) return embed_rms(embed_row(ids, table, b, t), hidden, blocks, gamma, normed, b, t);
1198
+ if (t < 32) { // block B: every row's plan, its tile count read once (B <= 64: two a lane)
1199
+ int tiles[2];
1200
+ #pragma unroll
1201
+ for (int k = 0; k < 2; ++k) tiles[k] = t + 32 * k < B ? (seq_lens[t + 32 * k] + MLA_TILE - 1) / MLA_TILE : 0;
1202
+ const int total = warp_sum_i(tiles[0] + tiles[1]);
1203
+ unsigned nsm;
1204
+ asm("mov.u32 %0, %%nsmid;" : "=r"(nsm));
1205
+ const int clusters = nsm / 2;
1206
+ // `per` tiles a split such that the batch fills W waves of clusters, the W of the least modelled time
1207
+ long long best_cost = 0;
1208
+ int best = 0;
1209
+ for (int w = 1; w <= MLA_WAVES; ++w) {
1210
+ const int per = split_per(total, w * clusters - B);
1211
+ int splits = 0, longest = 0;
1212
+ #pragma unroll
1213
+ for (int k = 0; k < 2; ++k)
1214
+ if (t + 32 * k < B) {
1215
+ const int sp = row_splits(tiles[k], per, split_max);
1216
+ splits += sp;
1217
+ longest = max(longest, (tiles[k] + sp - 1) / sp);
1218
+ }
1219
+ splits = warp_sum_i(splits);
1220
+ longest = warp_max_i(longest);
1221
+ long long cost = 0;
1222
+ for (int n = splits; n > 0; n -= clusters) cost += (long long)(longest + MLA_SPLIT_TILES) * max(MLA_SATURATE, min(n, clusters));
1223
+ if (w == 1 || cost < best_cost) best = per, best_cost = cost;
1224
+ }
1225
+ #pragma unroll
1226
+ for (int k = 0; k < 2; ++k)
1227
+ if (t + 32 * k < B) block_split_kvs[t + 32 * k] = row_splits(tiles[k], best, split_max);
1228
+ }
1229
+ }
k3_ar_fused+ANY_BATCH=1+NRANKS=8-d362b908/src/k3_l2_prefetch.cuh ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The next GEMM's weight pulled into L2 by a kernel's idle blocks (blockIdx.x >= B, the blocks that hold no
2
+ // row), so the cuBLAS GEMM after it reads its weight from L2 instead of HBM.
3
+ //
4
+ // l2_prefetch: a prefetch.global.L2 a 128-byte line. It never holds the block, but the GEMM after it runs as if
5
+ // only about half the bytes were in L2 (qkvg after 16 us of hints: 13.5 us, against 10.1 after real loads of
6
+ // the same bytes and 17.2 cold; work/h/pf_pair.cu). For a kernel that is over in a few microseconds.
7
+ // l2_load_while: real loads (ld.global.L2::128B, one 128-byte line a lane) until `grace_ns` after a row block's
8
+ // data is in, then stop: for a kernel whose row blocks wait on peers. The first row block in stamps
9
+ // `arrived` (l2_arrive: the global timer's low 32 bits, odd, so never 0), so the loads go on under the row's epilogue for `grace_ns` and
10
+ // drain in what is left of it; the member that arrives last, which waits the least, loads the least. The
11
+ // warps that load keep ~L2_INFLIGHT bytes in flight.
12
+ #pragma once
13
+ #include <cstdint>
14
+
15
+ #ifndef L2_INFLIGHT
16
+ #define L2_INFLIGHT (12 << 20)
17
+ #endif
18
+
19
+ __device__ __forceinline__ void l2_prefetch(const uint8_t* w, long long bytes, int B) {
20
+ if ((int)blockIdx.x < B) return;
21
+ const long long step = (long long)(gridDim.x - B) * blockDim.x * 128;
22
+ for (long long o = ((long long)(blockIdx.x - B) * blockDim.x + threadIdx.x) * 128; o < bytes; o += step)
23
+ asm volatile("prefetch.global.L2 [%0];" ::"l"(w + o));
24
+ }
25
+
26
+ // `sink` keeps the loads alive (ptxas drops a load nobody reads): written only if the xor of the words
27
+ // loaded is a constant, so in practice never.
28
+ __device__ __forceinline__ unsigned l2_now() {
29
+ unsigned t;
30
+ asm volatile("mov.u32 %0, %%globaltimer_lo;" : "=r"(t));
31
+ return t | 1u;
32
+ }
33
+
34
+ // `last`: the lines go in at evict_last, so a weight read a few kernels later outlives the traffic between
35
+ // (l2_demote puts them back once their GEMM has run; an evict_last line nobody demotes holds L2 for good).
36
+ template <bool last = false>
37
+ __device__ __forceinline__ void l2_load_while(const uint8_t* w, long long bytes, int B,
38
+ const unsigned* arrived, int grace_ns, int* sink) {
39
+ if ((int)blockIdx.x < B) return;
40
+ const int nb = gridDim.x - B, lane = threadIdx.x & 31;
41
+ const int warps = min((int)(blockDim.x >> 5), (L2_INFLIGHT / (32 * 128) + nb - 1) / nb);
42
+ if ((int)(threadIdx.x >> 5) >= warps) return;
43
+ const long long lines = bytes >> 7, round = (long long)nb * warps * 32;
44
+ unsigned long long pol = 0;
45
+ if (last) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol));
46
+ unsigned acc = 0;
47
+ for (long long l = ((long long)(blockIdx.x - B) * warps + (threadIdx.x >> 5)) * 32 + lane; l < lines; l += round) {
48
+ int done = 0;
49
+ if (lane == 0) {
50
+ const unsigned at = *reinterpret_cast<const volatile unsigned*>(arrived);
51
+ done = at && (int)(l2_now() - at) > grace_ns;
52
+ }
53
+ if (__shfl_sync(0xffffffffu, done, 0)) break;
54
+ unsigned v;
55
+ if (last)
56
+ asm volatile("ld.global.L2::cache_hint.L2::128B.b32 %0, [%1], %2;" : "=r"(v) : "l"(w + (l << 7)), "l"(pol));
57
+ else
58
+ asm volatile("ld.global.L2::128B.b32 %0, [%1];" : "=r"(v) : "l"(w + (l << 7)));
59
+ acc ^= v;
60
+ }
61
+ if (acc == 0x5f3759dfu) *sink = (int)acc;
62
+ }
63
+
64
+ __device__ __forceinline__ void l2_demote(const uint8_t* w, long long bytes, int B) {
65
+ if ((int)blockIdx.x < B) return;
66
+ const long long step = (long long)(gridDim.x - B) * blockDim.x * 128;
67
+ for (long long o = ((long long)(blockIdx.x - B) * blockDim.x + threadIdx.x) * 128; o < bytes; o += step)
68
+ asm volatile("applypriority.global.L2::evict_normal [%0], 128;" ::"l"(w + o));
69
+ }
70
+
71
+ __device__ __forceinline__ void l2_arrive(unsigned* arrived) {
72
+ if (threadIdx.x == 0 && !*reinterpret_cast<volatile unsigned*>(arrived)) atomicCAS(arrived, 0u, l2_now());
73
+ }
74
+
75
+ // `blocks_done` counts the blocks through; the grid's last zeroes it and `arrived` for the next call.
76
+ __device__ __forceinline__ void l2_close(unsigned* arrived, int* blocks_done) {
77
+ __syncthreads();
78
+ if (threadIdx.x == 0 && atomicAdd(blocks_done, 1) == (int)gridDim.x - 1) *arrived = 0, *blocks_done = 0;
79
+ }