aetherflow-ai 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. aetherflow/__init__.py +322 -0
  2. aetherflow/agent_api.py +234 -0
  3. aetherflow/backends/__init__.py +69 -0
  4. aetherflow/backends/base.py +74 -0
  5. aetherflow/backends/capabilities.py +286 -0
  6. aetherflow/backends/contracts.py +278 -0
  7. aetherflow/backends/cuda/__init__.py +16 -0
  8. aetherflow/backends/cuda/backend.py +1023 -0
  9. aetherflow/backends/cuda/codegen.py +2874 -0
  10. aetherflow/backends/cuda/cublas.py +428 -0
  11. aetherflow/backends/cuda/cudnn.py +305 -0
  12. aetherflow/backends/cuda/cufft.py +384 -0
  13. aetherflow/backends/cuda/cusparse.py +381 -0
  14. aetherflow/backends/cuda/dialect.py +80 -0
  15. aetherflow/backends/cuda/memory.py +243 -0
  16. aetherflow/backends/device_attention.py +257 -0
  17. aetherflow/backends/device_backend.py +1569 -0
  18. aetherflow/backends/device_conv.py +970 -0
  19. aetherflow/backends/device_elementwise.py +629 -0
  20. aetherflow/backends/device_index.py +230 -0
  21. aetherflow/backends/device_linear.py +1301 -0
  22. aetherflow/backends/device_loss.py +109 -0
  23. aetherflow/backends/device_misc.py +249 -0
  24. aetherflow/backends/device_norm.py +197 -0
  25. aetherflow/backends/device_plan.py +1062 -0
  26. aetherflow/backends/device_pool.py +592 -0
  27. aetherflow/backends/device_reduce.py +512 -0
  28. aetherflow/backends/device_scan.py +457 -0
  29. aetherflow/backends/device_shape.py +108 -0
  30. aetherflow/backends/device_shared.py +1107 -0
  31. aetherflow/backends/device_sparse.py +373 -0
  32. aetherflow/backends/discovery.py +286 -0
  33. aetherflow/backends/hardware.py +784 -0
  34. aetherflow/backends/hip/__init__.py +15 -0
  35. aetherflow/backends/hip/backend.py +567 -0
  36. aetherflow/backends/hip/blas.py +227 -0
  37. aetherflow/backends/hip/codegen.py +109 -0
  38. aetherflow/backends/hip/dialect.py +62 -0
  39. aetherflow/backends/hip/memory.py +418 -0
  40. aetherflow/backends/hip/rtc.py +126 -0
  41. aetherflow/backends/hip/runtime.py +2018 -0
  42. aetherflow/backends/kernel_cache.py +240 -0
  43. aetherflow/backends/reference_backend.py +76 -0
  44. aetherflow/backends/registry.py +224 -0
  45. aetherflow/conformance.py +2791 -0
  46. aetherflow/deploy.py +259 -0
  47. aetherflow/dynamic.py +252 -0
  48. aetherflow/frontend/__init__.py +39 -0
  49. aetherflow/frontend/compat.py +118 -0
  50. aetherflow/frontend/eager.py +345 -0
  51. aetherflow/frontend/module.py +320 -0
  52. aetherflow/frontend/torch_export.py +2047 -0
  53. aetherflow/fuzz.py +1093 -0
  54. aetherflow/gguf.py +693 -0
  55. aetherflow/ir/__init__.py +144 -0
  56. aetherflow/ir/control.py +444 -0
  57. aetherflow/ir/grad.py +240 -0
  58. aetherflow/ir/grad_rules.py +1814 -0
  59. aetherflow/ir/graph.py +370 -0
  60. aetherflow/ir/liveness.py +227 -0
  61. aetherflow/ir/loop.py +437 -0
  62. aetherflow/ir/ops.py +6333 -0
  63. aetherflow/ir/second_order.py +111 -0
  64. aetherflow/ir/serialize.py +180 -0
  65. aetherflow/ir/shape_contract.py +146 -0
  66. aetherflow/ir/types.py +363 -0
  67. aetherflow/ir/verifier.py +130 -0
  68. aetherflow/ir/version.py +196 -0
  69. aetherflow/lower/__init__.py +202 -0
  70. aetherflow/lower/cstyle.py +354 -0
  71. aetherflow/lower/elementwise.py +346 -0
  72. aetherflow/lower/indexing.py +170 -0
  73. aetherflow/lower/kernel.py +448 -0
  74. aetherflow/lower/kernels/__init__.py +262 -0
  75. aetherflow/lower/kernels/attention.py +390 -0
  76. aetherflow/lower/kernels/common.py +95 -0
  77. aetherflow/lower/kernels/conv.py +2927 -0
  78. aetherflow/lower/kernels/elementwise.py +676 -0
  79. aetherflow/lower/kernels/image.py +97 -0
  80. aetherflow/lower/kernels/interpolate.py +381 -0
  81. aetherflow/lower/kernels/misc.py +154 -0
  82. aetherflow/lower/kernels/norm.py +675 -0
  83. aetherflow/lower/kernels/pool.py +650 -0
  84. aetherflow/lower/kernels/reduce.py +891 -0
  85. aetherflow/lower/kernels/scan.py +939 -0
  86. aetherflow/lower/kernels/sparse.py +680 -0
  87. aetherflow/lower/plan.py +884 -0
  88. aetherflow/lower/translate.py +382 -0
  89. aetherflow/models/__init__.py +227 -0
  90. aetherflow/models/cached_attention.py +1133 -0
  91. aetherflow/models/cnn.py +208 -0
  92. aetherflow/models/hf_export.py +363 -0
  93. aetherflow/models/llama.py +875 -0
  94. aetherflow/models/lm.py +2888 -0
  95. aetherflow/models/lm_bpe.py +812 -0
  96. aetherflow/models/lm_text.py +159 -0
  97. aetherflow/models/lm_tools.py +1048 -0
  98. aetherflow/models/lm_unigram.py +794 -0
  99. aetherflow/models/lm_wordpiece.py +429 -0
  100. aetherflow/models/mamba.py +917 -0
  101. aetherflow/models/mamba_reference.py +183 -0
  102. aetherflow/models/mlp.py +84 -0
  103. aetherflow/models/moe.py +158 -0
  104. aetherflow/models/quantize.py +775 -0
  105. aetherflow/models/rnn.py +157 -0
  106. aetherflow/models/snn.py +362 -0
  107. aetherflow/models/speculative.py +426 -0
  108. aetherflow/models/ssm.py +179 -0
  109. aetherflow/models/transformer.py +382 -0
  110. aetherflow/passes/__init__.py +73 -0
  111. aetherflow/passes/autocast.py +180 -0
  112. aetherflow/passes/base.py +92 -0
  113. aetherflow/passes/cse.py +85 -0
  114. aetherflow/passes/dce.py +57 -0
  115. aetherflow/passes/fold.py +158 -0
  116. aetherflow/passes/fusion.py +268 -0
  117. aetherflow/passes/layout.py +261 -0
  118. aetherflow/passes/registry.py +213 -0
  119. aetherflow/passes/simplify.py +42 -0
  120. aetherflow/plugin.py +75 -0
  121. aetherflow/runtime/__init__.py +48 -0
  122. aetherflow/runtime/bf16.py +83 -0
  123. aetherflow/runtime/device_control.py +472 -0
  124. aetherflow/runtime/events.py +251 -0
  125. aetherflow/runtime/executor.py +617 -0
  126. aetherflow/runtime/fp8.py +275 -0
  127. aetherflow/runtime/paged_cache.py +897 -0
  128. aetherflow/runtime/prefix_store.py +508 -0
  129. aetherflow/runtime/reference.py +27 -0
  130. aetherflow/runtime/telemetry.py +596 -0
  131. aetherflow/runtime/trace.py +256 -0
  132. aetherflow/serve/__init__.py +20 -0
  133. aetherflow/serve/openai.py +767 -0
  134. aetherflow/train/__init__.py +154 -0
  135. aetherflow/train/_arrays.py +150 -0
  136. aetherflow/train/amp.py +219 -0
  137. aetherflow/train/bn.py +224 -0
  138. aetherflow/train/checkpoint.py +480 -0
  139. aetherflow/train/data.py +219 -0
  140. aetherflow/train/dataset.py +544 -0
  141. aetherflow/train/distributed.py +394 -0
  142. aetherflow/train/ema.py +143 -0
  143. aetherflow/train/grads.py +293 -0
  144. aetherflow/train/host_collective.py +497 -0
  145. aetherflow/train/lm.py +117 -0
  146. aetherflow/train/loop.py +1860 -0
  147. aetherflow/train/loss.py +105 -0
  148. aetherflow/train/monitor.py +208 -0
  149. aetherflow/train/nccl.py +831 -0
  150. aetherflow/train/optim.py +456 -0
  151. aetherflow/train/parallel.py +1296 -0
  152. aetherflow/train/params.py +220 -0
  153. aetherflow/train/pipeline.py +532 -0
  154. aetherflow/train/recompute.py +344 -0
  155. aetherflow/train/schedule.py +212 -0
  156. aetherflow/train/shard_io.py +685 -0
  157. aetherflow/train/sharded.py +490 -0
  158. aetherflow/train/tensor_parallel.py +527 -0
  159. aetherflow/train/zero.py +847 -0
  160. aetherflow/train/zero2.py +410 -0
  161. aetherflow/train/zero3.py +529 -0
  162. aetherflow/tuning/__init__.py +95 -0
  163. aetherflow/tuning/cost.py +535 -0
  164. aetherflow/tuning/paired.py +991 -0
  165. aetherflow/tuning/policy.py +195 -0
  166. aetherflow/tuning/search.py +290 -0
  167. aetherflow/tuning/signature.py +90 -0
  168. aetherflow/tuning/space.py +124 -0
  169. aetherflow/tuning/store.py +280 -0
  170. aetherflow/weights.py +1271 -0
  171. aetherflow_ai-0.2.0.dist-info/METADATA +578 -0
  172. aetherflow_ai-0.2.0.dist-info/RECORD +175 -0
  173. aetherflow_ai-0.2.0.dist-info/WHEEL +5 -0
  174. aetherflow_ai-0.2.0.dist-info/licenses/LICENSE +201 -0
  175. aetherflow_ai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2874 @@
1
+ """CUDA C 源码生成。
2
+
3
+ 这里生成的是**人类可读的 CUDA C**,不是 PTX,再交给 NVRTC 在运行时编译。
4
+ 选择 NVRTC 而不是提前用 nvcc 编译的原因:不需要在目标机器上安装 CUDA toolkit,
5
+ 插件只要拿到驱动即可工作。
6
+
7
+ 按算子分别生成 f32 与 f16 两种存储类型。f16 的算术仍在 ``float`` 里完成
8
+ (累加、归约、指数都不降精度),只有存储宽度减半——否则误差会以"悄悄降级"
9
+ 的形式出现,而不是以明确的实现边界出现。
10
+
11
+ 模板里的占位符:``%PRELUDE%`` 由 ``render()`` 按 dtype 展开成"归约辅助 +
12
+ 类型转换",``%T%`` 是存储类型,``%LD%`` / ``%ST%`` 是"按存储类型读成 float /
13
+ 把 float 写回存储类型",``%ATOMIC%`` 是"把 float 累加进存储类型"的原子加。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+
20
+ from ...ir.types import DType
21
+ from ...lower import emit
22
+ from ...lower.kernel import Kernel
23
+ from ...lower.kernels import (
24
+ adaptive_avg_pool2d,
25
+ adaptive_avg_pool2d_backward,
26
+ argmax_last,
27
+ argmin_last,
28
+ attention_fwd,
29
+ avgpool2d,
30
+ avgpool2d_backward,
31
+ batch_norm,
32
+ batch_norm_stats,
33
+ concat_copy,
34
+ conv2d_input_grad,
35
+ conv2d_grouped,
36
+ conv2d_implicit,
37
+ conv2d_tiled,
38
+ conv2d_weight_grad,
39
+ cumsum,
40
+ cumprod,
41
+ dropout_mask,
42
+ ew_binary,
43
+ ew_broadcast,
44
+ ew_cast,
45
+ ew_clamp,
46
+ interpolate_bilinear,
47
+ interpolate_bilinear_backward,
48
+ interpolate_nearest,
49
+ interpolate_nearest_backward,
50
+ ew_mod_int,
51
+ ew_step,
52
+ ew_unary,
53
+ ew_where_bcast,
54
+ ew_where_same,
55
+ flip,
56
+ im2col,
57
+ layernorm_last,
58
+ layernorm_residual_last,
59
+ logsumexp_axis,
60
+ maxpool2d,
61
+ maxpool2d_backward,
62
+ maxpool2d_indices,
63
+ reduce_all_last,
64
+ reduce_any_last,
65
+ reduce_max_last,
66
+ reduce_mean_last,
67
+ reduce_sum_last,
68
+ reduce_sum_rows,
69
+ reduce_axis,
70
+ reduce_axis_tiled,
71
+ rmsnorm_last,
72
+ roll,
73
+ rope_apply,
74
+ repeat_interleave,
75
+ scan_linear,
76
+ softmax_axis,
77
+ scan_linear_backward,
78
+ scan_linear_chunk,
79
+ scan_linear_chunk_backward,
80
+ scan_linear_chunk_last,
81
+ scan_linear_chunk_sum,
82
+ scan_linear_chunk_sum_backward,
83
+ scan_linear_last,
84
+ silu_gate,
85
+ softmax_last,
86
+ tril,
87
+ spike_csr,
88
+ spike_csr_serial,
89
+ spike_linear,
90
+ spike_linear_weight_grad,
91
+ spike_offsets,
92
+ sparse_linear,
93
+ sparse_linear_values_grad,
94
+ sparse_linear_weight_grad,
95
+ winograd_input_transform,
96
+ winograd_output_transform,
97
+ winograd_weight_transform,
98
+ winograd_fused,
99
+ )
100
+
101
+ _REDUCE = r"""
102
+ __device__ __forceinline__ float block_reduce_max(float v, float* smem) {
103
+ smem[threadIdx.x] = v;
104
+ __syncthreads();
105
+ for (int s = blockDim.x >> 1; s > 0; s >>= 1) {
106
+ if (threadIdx.x < s) {
107
+ float other = smem[threadIdx.x + s];
108
+ smem[threadIdx.x] = smem[threadIdx.x] > other ? smem[threadIdx.x] : other;
109
+ }
110
+ __syncthreads();
111
+ }
112
+ float r = smem[0];
113
+ __syncthreads();
114
+ return r;
115
+ }
116
+
117
+ __device__ __forceinline__ float block_reduce_sum(float v, float* smem) {
118
+ smem[threadIdx.x] = v;
119
+ __syncthreads();
120
+ for (int s = blockDim.x >> 1; s > 0; s >>= 1) {
121
+ if (threadIdx.x < s) { smem[threadIdx.x] += smem[threadIdx.x + s]; }
122
+ __syncthreads();
123
+ }
124
+ float r = smem[0];
125
+ __syncthreads();
126
+ return r;
127
+ }
128
+
129
+ // Reduce over threadIdx.x for each fixed threadIdx.y: the mirror image of
130
+ // block_reduce_*_y. Used when the reduced dimension is narrow (d_state,
131
+ // n_scales, head_dim ...) so one warp-sized block per row wastes the machine:
132
+ // the block's y dimension packs many rows instead, and each row keeps the
133
+ // exact halving tree block_reduce_sum uses (bit-identical results).
134
+ __device__ __forceinline__ float block_reduce_sum_x(float v, float* smem) {
135
+ const int nx = blockDim.x;
136
+ const int base = threadIdx.y * nx;
137
+ smem[base + threadIdx.x] = v;
138
+ __syncthreads();
139
+ for (int s = nx >> 1; s > 0; s >>= 1) {
140
+ if (threadIdx.x < s) {
141
+ smem[base + threadIdx.x] += smem[base + threadIdx.x + s];
142
+ }
143
+ __syncthreads();
144
+ }
145
+ float r = smem[base];
146
+ __syncthreads();
147
+ return r;
148
+ }
149
+
150
+ // Two-dimensional block reductions: reduce over threadIdx.y for each fixed
151
+ // threadIdx.x. A strided (outer, reduce, inner) reduction reads consecutive
152
+ // inner elements with threadIdx.x, so the reduce axis has to be split across
153
+ // threadIdx.y; the flat block_reduce_* above cannot do that.
154
+ __device__ __forceinline__ float block_reduce_sum_y(float v, float* smem) {
155
+ const int nx = blockDim.x;
156
+ const int tid = threadIdx.y * nx + threadIdx.x;
157
+ smem[tid] = v;
158
+ __syncthreads();
159
+ for (int s = blockDim.y >> 1; s > 0; s >>= 1) {
160
+ if (threadIdx.y < s) { smem[tid] += smem[tid + s * nx]; }
161
+ __syncthreads();
162
+ }
163
+ float r = smem[tid];
164
+ __syncthreads();
165
+ return r;
166
+ }
167
+
168
+ __device__ __forceinline__ float block_reduce_max_y(float v, float* smem) {
169
+ const int nx = blockDim.x;
170
+ const int tid = threadIdx.y * nx + threadIdx.x;
171
+ smem[tid] = v;
172
+ __syncthreads();
173
+ for (int s = blockDim.y >> 1; s > 0; s >>= 1) {
174
+ if (threadIdx.y < s) {
175
+ float other = smem[tid + s * nx];
176
+ smem[tid] = smem[tid] > other ? smem[tid] : other;
177
+ }
178
+ __syncthreads();
179
+ }
180
+ float r = smem[tid];
181
+ __syncthreads();
182
+ return r;
183
+ }
184
+
185
+ __device__ __forceinline__ float block_reduce_min_y(float v, float* smem) {
186
+ const int nx = blockDim.x;
187
+ const int tid = threadIdx.y * nx + threadIdx.x;
188
+ smem[tid] = v;
189
+ __syncthreads();
190
+ for (int s = blockDim.y >> 1; s > 0; s >>= 1) {
191
+ if (threadIdx.y < s) {
192
+ float other = smem[tid + s * nx];
193
+ smem[tid] = smem[tid] < other ? smem[tid] : other;
194
+ }
195
+ __syncthreads();
196
+ }
197
+ float r = smem[tid];
198
+ __syncthreads();
199
+ return r;
200
+ }
201
+
202
+ /* Exclusive prefix sum across the block: returns how many lanes before tid
203
+ carried a non-zero value. The block total is left in smem[blockDim.x], one
204
+ slot past the scan area, so the caller reads it after the trailing barrier.
205
+ Used by spike_csr to write each row's columns in ascending order. */
206
+ __device__ __forceinline__ int block_scan_sum(int v, int* smem) {
207
+ const int tid = threadIdx.x;
208
+ const int n = blockDim.x;
209
+ smem[tid] = v;
210
+ __syncthreads();
211
+ for (int off = 1; off < n; off <<= 1) {
212
+ const int prev = (tid >= off) ? smem[tid - off] : 0;
213
+ __syncthreads();
214
+ smem[tid] += prev;
215
+ __syncthreads();
216
+ }
217
+ const int total = smem[n - 1];
218
+ const int pre = smem[tid] - v;
219
+ if (tid == 0) { smem[n] = total; }
220
+ __syncthreads();
221
+ return pre;
222
+ }
223
+ """
224
+
225
+ # 表达式级辅助函数:不是"按存储宽度读写",而是内核表达式里直接调用的函数,
226
+ # 与 dtype 无关(实参与返回值都是 float)。**不**拼进下面三个 dtype 块,
227
+ # 而由使用方按"每个生成单元恰好一次"追加:``CUDA_DIALECT`` 的每个 dtype 各
228
+ # 追加一次,``_CAST_HELPERS`` / ``_BOOL_HELPERS`` 这类把三块拼在一起的组合
229
+ # 只追加一次。三块各自带一份会让组合方言里 ``af_rem`` 重复定义(NVRTC 报
230
+ # "has already been defined")。
231
+ # NOTE: ASCII only -- this text goes to NVRTC.
232
+ _EXPR_HELPERS = r"""
233
+ // Floor-semantics modulo for floats. fmodf truncates, so its result takes the
234
+ // sign of the dividend; numpy.mod / torch.remainder take the sign of the
235
+ // divisor. Adding one divisor when the signs differ fixes that. NaN and a zero
236
+ // divisor propagate as-is (fmodf returns NaN), matching the IEEE result numpy
237
+ // produces.
238
+ __device__ __forceinline__ float af_rem(float a, float b) {
239
+ float r = fmodf(a, b);
240
+ if (r != 0.f && ((r < 0.f) != (b < 0.f))) { r += b; }
241
+ return r;
242
+ }
243
+ """
244
+
245
+ # f32 的四个辅助函数是恒等映射:模板只写一份,两种 dtype 共用同一份源码结构。
246
+ _F32_HELPERS = r"""
247
+ __device__ __forceinline__ float af_ld_f(float v) { return v; }
248
+ __device__ __forceinline__ float af_st_f(float v) { return v; }
249
+ __device__ __forceinline__ float af_add_f(float* p, float v) { return atomicAdd(p, v); }
250
+ """
251
+
252
+ # f16 存储为 unsigned short。刻意不 include cuda_fp16.h:目标机可能只装了驱动
253
+ # 而没有 toolkit,NVRTC 的 include 路径不可靠;PTX 的 cvt 指令是所有 NVRTC
254
+ # 版本都认识的。算术一律读成 float 再算,只有存取时降回 f16。
255
+ # NOTE: the C source below is fed to NVRTC, which only accepts ASCII -- the
256
+ # comments inside the raw string must stay ASCII even though the Python
257
+ # comments around it are Chinese.
258
+ _F16_HELPERS = r"""
259
+ __device__ __forceinline__ float af_ld_h(unsigned short h) {
260
+ float r;
261
+ asm("cvt.f32.f16 %0, %1;" : "=f"(r) : "h"(h));
262
+ return r;
263
+ }
264
+
265
+ __device__ __forceinline__ unsigned short af_st_h(float v) {
266
+ unsigned short r;
267
+ asm("cvt.rn.f16.f32 %0, %1;" : "=h"(r) : "f"(v));
268
+ return r;
269
+ }
270
+
271
+ // 16-bit has no native atomicAdd; a CAS loop implements it without pulling in
272
+ // cuda_fp16.h. Contention only happens on overlapping windows or repeated ids.
273
+ // sm_52 (Maxwell) also lacks atomicCAS(unsigned short*), which appears only from
274
+ // sm_60 on: widen the CAS to the aligned 32-bit word and mask the target half.
275
+ // The compare value is built from ``assumed`` (not from a fresh load of the
276
+ // word) on purpose: the caller's retry loop adds ``v`` again on a mismatch, so a
277
+ // CAS that succeeded while returning a different value would double-count.
278
+ __device__ __forceinline__ unsigned short af_cas_h(unsigned short* p,
279
+ unsigned short assumed,
280
+ unsigned short v) {
281
+ #if __CUDA_ARCH__ >= 600
282
+ return atomicCAS(p, assumed, v);
283
+ #else
284
+ unsigned long long addr = (unsigned long long)p;
285
+ unsigned int* base = (unsigned int*)(addr & ~2ULL);
286
+ unsigned int shift = (addr & 2ULL) ? 16u : 0u;
287
+ unsigned int mask = (addr & 2ULL) ? 0xFFFF0000u : 0x0000FFFFu;
288
+ unsigned int other = *base & ~mask;
289
+ for (;;) {
290
+ unsigned int assumed32 = other | (((unsigned int)assumed) << shift);
291
+ unsigned int desired = other | (((unsigned int)v) << shift);
292
+ unsigned int prev = atomicCAS(base, assumed32, desired);
293
+ if (prev == assumed32) return assumed;
294
+ unsigned short got = (unsigned short)((prev & mask) >> shift);
295
+ // Another half of the word changed: keep going. The target half moved:
296
+ // report it so the caller recomputes from the fresh value.
297
+ if (got != assumed) return got;
298
+ other = prev & ~mask;
299
+ }
300
+ #endif
301
+ }
302
+
303
+ __device__ __forceinline__ float af_add_h(unsigned short* p, float v) {
304
+ unsigned short old = *p;
305
+ unsigned short assumed;
306
+ do {
307
+ assumed = old;
308
+ old = af_cas_h(p, assumed, af_st_h(af_ld_h(assumed) + v));
309
+ } while (assumed != old);
310
+ return af_ld_h(old);
311
+ }
312
+ """
313
+
314
+ # bf16 同样存成 unsigned short,但存取是**纯位操作**:bf16 就是 f32 的高 16
315
+ # 位,加宽是左移、收窄是高半字的 RNE 舍入。刻意不用 PTX 的 cvt 指令,也不用
316
+ # cuda_bf16.h——cvt 的 bf16 形式要 sm_80,而按位实现从 Maxwell 起都能编;
317
+ # 舍入规则与主机侧 ``runtime.bf16.round_bf16`` 逐条一致(尾数 LSB 为 1 时进位,
318
+ # inf / nan 只截断,截断后尾数清零的 NaN 补 quiet 位)。
319
+ _BF16_HELPERS = r"""
320
+ __device__ __forceinline__ float af_ld_b(unsigned short h) {
321
+ return __uint_as_float(((unsigned int)h) << 16);
322
+ }
323
+
324
+ __device__ __forceinline__ unsigned short af_st_b(float v) {
325
+ unsigned int bits = __float_as_uint(v);
326
+ unsigned int lsb = (bits >> 16) & 1u;
327
+ unsigned int kept = (bits + 0x7FFFu + lsb) >> 16;
328
+ if ((bits & 0x7F800000u) == 0x7F800000u) {
329
+ // inf / nan: adding the bias would carry into the exponent, or wrap a
330
+ // mantissa of all ones into zero. They are already on the bf16 grid.
331
+ kept = bits >> 16;
332
+ if ((bits & 0x007FFFFFu) != 0 && (kept & 0x007Fu) == 0) {
333
+ kept |= 0x0040u;
334
+ }
335
+ }
336
+ return (unsigned short)kept;
337
+ }
338
+
339
+ __device__ __forceinline__ unsigned short af_cas_b(unsigned short* p,
340
+ unsigned short assumed,
341
+ unsigned short v) {
342
+ #if __CUDA_ARCH__ >= 600
343
+ return atomicCAS(p, assumed, v);
344
+ #else
345
+ unsigned long long addr = (unsigned long long)p;
346
+ unsigned int* base = (unsigned int*)(addr & ~2ULL);
347
+ unsigned int shift = (addr & 2ULL) ? 16u : 0u;
348
+ unsigned int mask = (addr & 2ULL) ? 0xFFFF0000u : 0x0000FFFFu;
349
+ unsigned int other = *base & ~mask;
350
+ for (;;) {
351
+ unsigned int assumed32 = other | (((unsigned int)assumed) << shift);
352
+ unsigned int desired = other | (((unsigned int)v) << shift);
353
+ unsigned int prev = atomicCAS(base, assumed32, desired);
354
+ if (prev == assumed32) return assumed;
355
+ unsigned short got = (unsigned short)((prev & mask) >> shift);
356
+ if (got != assumed) return got;
357
+ other = prev & ~mask;
358
+ }
359
+ #endif
360
+ }
361
+
362
+ __device__ __forceinline__ float af_add_b(unsigned short* p, float v) {
363
+ unsigned short old = *p;
364
+ unsigned short assumed;
365
+ do {
366
+ assumed = old;
367
+ old = af_cas_b(p, assumed, af_st_b(af_ld_b(assumed) + v));
368
+ } while (assumed != old);
369
+ return af_ld_b(old);
370
+ }
371
+ """
372
+
373
+ # 占位符:render() 会把它替换成 _REDUCE + 对应 dtype 的辅助函数。
374
+ PRELUDE = "%PRELUDE%"
375
+
376
+ _STORAGE = {
377
+ "f32": ("float", "af_ld_f", "af_st_f", "af_add_f"),
378
+ "f16": ("unsigned short", "af_ld_h", "af_st_h", "af_add_h"),
379
+ "bf16": ("unsigned short", "af_ld_b", "af_st_b", "af_add_b"),
380
+ "bool": ("unsigned char", "af_ld_q", "af_st_q", "af_add_q"),
381
+ }
382
+
383
+ # boolean is stored as one byte with values in {0, 1}: reads widen to float and
384
+ # writes normalise any non-zero value back to 1. That lets the L2 layer emit a
385
+ # comparison result as an ordinary float expression. ``af_add_q`` is a stub --
386
+ # no kernel reduces into a bool -- it only keeps the four-slot storage tuple
387
+ # self-consistent.
388
+ _BOOL_HELPERS = r"""
389
+ __device__ __forceinline__ float af_ld_q(unsigned char v) { return v ? 1.f : 0.f; }
390
+ __device__ __forceinline__ unsigned char af_st_q(float v) { return v != 0.f ? 1 : 0; }
391
+ __device__ __forceinline__ float af_add_q(unsigned char* p, float v) { return 0.f; }
392
+ """
393
+
394
+ _HELPERS = {
395
+ "f32": _F32_HELPERS + _EXPR_HELPERS,
396
+ "f16": _F16_HELPERS + _EXPR_HELPERS,
397
+ "bf16": _BF16_HELPERS + _EXPR_HELPERS,
398
+ "bool": _BOOL_HELPERS,
399
+ }
400
+
401
+
402
+ def _dtype_key(dtype) -> str:
403
+ # ``np.dtype`` 实例有 ``.name``,标量**类型**(``cp.float32``)没有:
404
+ # 它的 ``str`` 是 ``<class 'numpy.float32'>``。两种写法都要认,否则
405
+ # 同一份调用换个写法就编不出内核。
406
+ name = getattr(dtype, "name", None)
407
+ if not isinstance(name, str):
408
+ name = np.dtype(dtype).name
409
+ if name in ("float32", "f32"):
410
+ return "f32"
411
+ if name in ("float16", "f16"):
412
+ return "f16"
413
+ # bf16 在设备上的容器是 uint16(位模式);numpy 侧只可能是这两个写法。
414
+ if name in ("uint16", "bfloat16", "bf16"):
415
+ return "bf16"
416
+ if name in ("bool", "bool_"):
417
+ return "bool"
418
+ raise ValueError(f"CUDA codegen 只支持 f32/f16/bf16/bool,收到 {name}")
419
+
420
+
421
+ def _ir_dtype(dtype) -> DType:
422
+ """运行期的 numpy dtype -> IR 的 DType(L2 用后者认类型)。"""
423
+ key = _dtype_key(dtype)
424
+ return {
425
+ "f32": DType.F32,
426
+ "f16": DType.F16,
427
+ "bf16": DType.BF16,
428
+ "bool": DType.BOOL,
429
+ }[key]
430
+
431
+
432
+ def render(template, dtype, *, f16_helpers: str | None = None, dialect=None) -> str:
433
+ """把内核展开成可交给 NVRTC 的源码。
434
+
435
+ 接受两种输入:
436
+
437
+ - ``str``:按 dtype 参数化的手写模板(历史路径,仍用于对照与回退);
438
+ - ``Kernel``:L2 描述(5.42 之后的生产路径),由 ``lower.emit`` 打印。
439
+
440
+ ``f16_helpers`` / ``dialect`` 是给**别的后端复用同一套内核**留的方言注入点:
441
+ HIP 的 clang 不认 PTX 的 ``cvt`` 约束,必须换掉 f16 的读写实现。
442
+ """
443
+ if isinstance(template, Kernel):
444
+ if dialect is None:
445
+ from .dialect import BOOL_DIALECT, CUDA_DIALECT
446
+
447
+ # bool 的存储是 1 字节 ``unsigned char``,存取走 ``af_ld_q`` /
448
+ # ``af_st_q``;``CUDA_DIALECT`` 里没有这两项。一元逻辑非
449
+ # (``logical_not``)是唯一一个"只拿 dtype 就够"的 bool 内核,
450
+ # 在这里按 dtype 自动选方言,避免每个调用点各写一遍。
451
+ dialect = BOOL_DIALECT if _dtype_key(dtype) == "bool" else CUDA_DIALECT
452
+ return emit(template, dialect, _ir_dtype(dtype))
453
+
454
+ key = _dtype_key(dtype)
455
+ storage, ld, st, add = _STORAGE[key]
456
+ if key == "f16" and f16_helpers is not None:
457
+ helpers = f16_helpers
458
+ else:
459
+ helpers = _HELPERS[key]
460
+ return (
461
+ template.replace("%PRELUDE%", _REDUCE + helpers)
462
+ .replace("%T%", storage)
463
+ .replace("%LD%", ld)
464
+ .replace("%ST%", st)
465
+ .replace("%ATOMIC%", add)
466
+ )
467
+
468
+
469
+ BINARY_FN = {
470
+ "add": "({}) + ({})",
471
+ "sub": "({}) - ({})",
472
+ "mul": "({}) * ({})",
473
+ "div": "({}) / ({})",
474
+ }
475
+
476
+ UNARY_EXPR = {
477
+ "relu": "x > 0.f ? x : 0.f",
478
+ "silu": "x / (1.f + expf(-x))",
479
+ # tanh 近似的 GELU:与 ir/ops.py 的参考实现逐位同式,
480
+ # 常数就是 sqrt(2/pi) 与 0.044715(GPT/BERT 实际使用的定义)
481
+ "gelu": "0.5f * x * (1.f + tanhf(0.7978845608028654f * (x + 0.044715f * x * x * x)))",
482
+ # 自动微分需要的初等函数。与 relu/silu 走同一个一元模板:
483
+ # 反向规则只用这些基本语义组合,所以反向图不需要单独的 kernel。
484
+ "exp": "expf(x)",
485
+ "log": "logf(x)",
486
+ "sqrt": "sqrtf(x)",
487
+ "sin": "sinf(x)",
488
+ "cos": "cosf(x)",
489
+ "neg": "-x",
490
+ "tanh": "tanhf(x)",
491
+ "sigmoid": "1.f / (1.f + expf(-x))",
492
+ "erf": "erff(x)",
493
+ # 嵌套三目与 L2 的 Cond 逐个 token 对齐;0 → 0、NaN 两个比较都为假 → 原样透传。
494
+ "sign": "x > 0.f ? 1.f : x < 0.f ? -1.f : x",
495
+ "round": "nearbyintf(x)",
496
+ "floor": "floorf(x)",
497
+ "ceil": "ceilf(x)",
498
+ }
499
+
500
+ # step 比其他一元算子多一个 kernel 参数(阈值),因此不进 UNARY_EXPR 模板。
501
+ STEP_SRC = (
502
+ PRELUDE
503
+ + r"""
504
+ extern "C" __global__ void ew_step(const %T%* __restrict__ in,
505
+ %T%* __restrict__ out,
506
+ long long n,
507
+ float thr) {
508
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
509
+ long long stride = (long long)gridDim.x * blockDim.x;
510
+ for (; i < n; i += stride) { out[i] = %ST%(%LD%(in[i]) > thr ? 1.f : 0.f); }
511
+ }
512
+ """
513
+ )
514
+
515
+ _BINARY_TMPL = (
516
+ PRELUDE
517
+ + r"""
518
+ extern "C" __global__ void ew_bin(%A_DECL%,
519
+ %B_DECL%,
520
+ %T%* __restrict__ out,
521
+ long long n) {
522
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
523
+ long long stride = (long long)gridDim.x * blockDim.x;
524
+ for (; i < n; i += stride) { out[i] = %ST%(%EXPR%); }
525
+ }
526
+ """
527
+ )
528
+
529
+ _UNARY_TMPL = (
530
+ PRELUDE
531
+ + r"""
532
+ extern "C" __global__ void ew_un(const %T%* __restrict__ in,
533
+ %T%* __restrict__ out,
534
+ long long n) {
535
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
536
+ long long stride = (long long)gridDim.x * blockDim.x;
537
+ for (; i < n; i += stride) { float x = %LD%(in[i]); out[i] = %ST%(%EXPR%); }
538
+ }
539
+ """
540
+ )
541
+
542
+ _BCAST_TMPL = (
543
+ PRELUDE
544
+ + r"""
545
+ extern "C" __global__ void ew_bcast(const %T%* __restrict__ a,
546
+ const %T%* __restrict__ b,
547
+ %T%* __restrict__ out,
548
+ long long n,
549
+ int ndim,
550
+ long long d0, long long d1, long long d2, long long d3,
551
+ long long a0, long long a1, long long a2, long long a3,
552
+ long long b0, long long b1, long long b2, long long b3) {
553
+ long long shape[4] = {d0, d1, d2, d3};
554
+ long long sa[4] = {a0, a1, a2, a3};
555
+ long long sb[4] = {b0, b1, b2, b3};
556
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
557
+ long long step = (long long)gridDim.x * blockDim.x;
558
+ for (; i < n; i += step) {
559
+ long long rem = i, oa = 0, ob = 0;
560
+ for (int d = ndim - 1; d >= 0; --d) {
561
+ long long c = rem % shape[d];
562
+ rem /= shape[d];
563
+ oa += c * sa[d];
564
+ ob += c * sb[d];
565
+ }
566
+ out[i] = %ST%(%EXPR%);
567
+ }
568
+ }
569
+ """
570
+ )
571
+
572
+ SOFTMAX_SRC = (
573
+ PRELUDE
574
+ + r"""
575
+ extern "C" __global__ void softmax_last(const %T%* __restrict__ x,
576
+ %T%* __restrict__ out,
577
+ long long rows, long long cols,
578
+ const float* __restrict__ scale) {
579
+ long long row = blockIdx.x;
580
+ if (row >= rows) { return; }
581
+ const %T%* xr = x + row * cols;
582
+ %T%* orow = out + row * cols;
583
+ const float sc = scale[0];
584
+ __shared__ float smem[1024];
585
+
586
+ float m = -3.4e38f;
587
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
588
+ float v = %LD%(xr[i]) * sc;
589
+ m = v > m ? v : m;
590
+ }
591
+ m = block_reduce_max(m, smem);
592
+
593
+ float s = 0.f;
594
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += expf(%LD%(xr[i]) * sc - m); }
595
+ s = block_reduce_sum(s, smem);
596
+ float inv = 1.f / s;
597
+
598
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
599
+ orow[i] = %ST%(expf(%LD%(xr[i]) * sc - m) * inv);
600
+ }
601
+ }
602
+ """
603
+ )
604
+
605
+ # Fused attention forward. One block per (batch*head, query row); the key axis
606
+ # is streamed in chunks of blockDim.x with an online softmax, so the (S, T)
607
+ # score matrix is never materialized. Only the running row max, the running
608
+ # normalizer and the output accumulator live across chunks.
609
+ #
610
+ # Layout: q (BH, S, D), k (BH, T, D), v (BH, T, E), out (BH, S, E). The mask is
611
+ # either (BH, S, T) or a single (S, T) shared by every (b, h) when mask_shared=1 —
612
+ # the common causal case, which must not be copied into a (BH, S, T) buffer.
613
+ # When has_mask is 0 the pointer is a dummy and never dereferenced.
614
+ #
615
+ # Dropout multiplies the normalized weights, not the denominator:
616
+ # out = sum_i exp(s_i - m) * keep_i * v_i / sum_i exp(s_i - m)
617
+ # which matches ir/ops.py, where dropout acts on the softmax probabilities.
618
+ # The mask is drawn from (seed, (bh*S + s)*T + t) -- the flat index of the
619
+ # probability matrix -- so it is bit-identical to the reference backend.
620
+ ATTENTION_SRC = (
621
+ PRELUDE
622
+ + r"""
623
+ __device__ __forceinline__ unsigned long long attention_rand(unsigned long long seed,
624
+ long long idx) {
625
+ unsigned long long z =
626
+ seed + (unsigned long long)idx * 0x9E3779B97F4A7C15ULL;
627
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
628
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
629
+ return z ^ (z >> 31);
630
+ }
631
+
632
+ extern "C" __global__ void attention_fwd(const %T%* __restrict__ q,
633
+ const %T%* __restrict__ k,
634
+ const %T%* __restrict__ v,
635
+ const %T%* __restrict__ mask,
636
+ %T%* __restrict__ out,
637
+ long long S, long long T,
638
+ long long D, long long E,
639
+ float scale,
640
+ float p_drop, float drop_scale,
641
+ unsigned long long seed,
642
+ int has_mask,
643
+ int mask_shared) {
644
+ // Dynamic shared memory: [w | reduce scratch | accumulator].
645
+ extern __shared__ float smem[];
646
+ float* s_w = smem;
647
+ float* s_red = smem + blockDim.x;
648
+ float* s_acc = smem + 2 * blockDim.x;
649
+
650
+ const long long bh = blockIdx.y;
651
+ const long long s = blockIdx.x;
652
+
653
+ for (long long e = threadIdx.x; e < E; e += blockDim.x) { s_acc[e] = 0.f; }
654
+ __syncthreads();
655
+
656
+ const %T%* qs = q + (bh * S + s) * D;
657
+ const %T%* vbase = v + bh * T * E;
658
+ const %T%* mrow =
659
+ has_mask ? (mask + ((mask_shared ? 0 : bh) * S + s) * T) : nullptr;
660
+
661
+ // Every thread keeps the same m and l: block_reduce_* broadcasts smem[0].
662
+ float m = -3.4e38f;
663
+ float l = 0.f;
664
+
665
+ for (long long t0 = 0; t0 < T; t0 += blockDim.x) {
666
+ const long long t = t0 + threadIdx.x;
667
+ float sc = -3.4e38f;
668
+ if (t < T) {
669
+ const %T%* kt = k + (bh * T + t) * D;
670
+ float dot = 0.f;
671
+ for (long long d = 0; d < D; ++d) { dot += %LD%(qs[d]) * %LD%(kt[d]); }
672
+ sc = dot * scale;
673
+ if (has_mask) { sc += %LD%(mrow[t]); }
674
+ }
675
+
676
+ const float blk_max = block_reduce_max(sc, s_red);
677
+ const float m_new = m > blk_max ? m : blk_max;
678
+ // Rescale factor for everything accumulated so far. On the first
679
+ // chunk m is -FLT_MAX, so corr underflows to 0 as intended.
680
+ const float corr = expf(m - m_new);
681
+
682
+ float p = 0.f;
683
+ float w = 0.f;
684
+ if (t < T) {
685
+ p = expf(sc - m_new);
686
+ w = p;
687
+ if (p_drop > 0.f) {
688
+ const unsigned long long z =
689
+ attention_rand(seed, (bh * S + s) * T + t);
690
+ const float u =
691
+ (float)((z >> 40) & 0xFFFFFFULL) * (1.0f / 16777216.0f);
692
+ w = (u >= p_drop) ? p * drop_scale : 0.f;
693
+ }
694
+ }
695
+ s_w[threadIdx.x] = w;
696
+
697
+ const float blk_sum = block_reduce_sum(p, s_red);
698
+ l = l * corr + blk_sum;
699
+
700
+ // Threads switch roles here: each one owns a slice of the output
701
+ // channels and walks the whole chunk. Consecutive threads read
702
+ // consecutive v elements, so the loads stay coalesced.
703
+ for (long long e = threadIdx.x; e < E; e += blockDim.x) {
704
+ float acc = s_acc[e] * corr;
705
+ for (long long j = 0; j < blockDim.x && t0 + j < T; ++j) {
706
+ acc += s_w[j] * %LD%(vbase[(t0 + j) * E + e]);
707
+ }
708
+ s_acc[e] = acc;
709
+ }
710
+ // s_w is rewritten by the next chunk: everyone must be done reading.
711
+ __syncthreads();
712
+ m = m_new;
713
+ }
714
+
715
+ const float inv = l > 0.f ? 1.f / l : 0.f;
716
+ %T%* orow = out + (bh * S + s) * E;
717
+ for (long long e = threadIdx.x; e < E; e += blockDim.x) {
718
+ orow[e] = %ST%(s_acc[e] * inv);
719
+ }
720
+ }
721
+ """
722
+ )
723
+
724
+ LAYERNORM_SRC = (
725
+ PRELUDE
726
+ + r"""
727
+ extern "C" __global__ void layernorm_last(const %T%* __restrict__ x,
728
+ const %T%* __restrict__ gamma,
729
+ const %T%* __restrict__ beta,
730
+ %T%* __restrict__ out,
731
+ long long rows, long long cols, float eps) {
732
+ long long row = blockIdx.x;
733
+ if (row >= rows) { return; }
734
+ const %T%* xr = x + row * cols;
735
+ %T%* orow = out + row * cols;
736
+ __shared__ float smem[1024];
737
+
738
+ float s = 0.f;
739
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += %LD%(xr[i]); }
740
+ s = block_reduce_sum(s, smem);
741
+ float mean = s / (float)cols;
742
+
743
+ float v = 0.f;
744
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
745
+ float d = %LD%(xr[i]) - mean;
746
+ v += d * d;
747
+ }
748
+ v = block_reduce_sum(v, smem);
749
+ float inv = rsqrtf(v / (float)cols + eps);
750
+
751
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
752
+ orow[i] = %ST%((%LD%(xr[i]) - mean) * inv * %LD%(gamma[i]) + %LD%(beta[i]));
753
+ }
754
+ }
755
+ """
756
+ )
757
+
758
+ # LayerNorm with a fused residual: the add is never materialized.
759
+ # The sum is rounded back to the storage type first, so f16 matches the
760
+ # reference semantics (numpy also adds two f16 arrays in f16).
761
+ LAYERNORM_RESIDUAL_SRC = (
762
+ PRELUDE
763
+ + r"""
764
+ extern "C" __global__ void layernorm_residual(const %T%* __restrict__ x,
765
+ const %T%* __restrict__ res,
766
+ const %T%* __restrict__ gamma,
767
+ const %T%* __restrict__ beta,
768
+ %T%* __restrict__ out,
769
+ long long rows, long long cols, float eps) {
770
+ long long row = blockIdx.x;
771
+ if (row >= rows) { return; }
772
+ const %T%* xr = x + row * cols;
773
+ const %T%* rr = res + row * cols;
774
+ %T%* orow = out + row * cols;
775
+ __shared__ float smem[1024];
776
+
777
+ float s = 0.f;
778
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
779
+ %T% xv = %ST%(%LD%(xr[i]) + %LD%(rr[i]));
780
+ s += %LD%(xv);
781
+ }
782
+ s = block_reduce_sum(s, smem);
783
+ float mean = s / (float)cols;
784
+
785
+ float v = 0.f;
786
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
787
+ %T% xv = %ST%(%LD%(xr[i]) + %LD%(rr[i]));
788
+ float d = %LD%(xv) - mean;
789
+ v += d * d;
790
+ }
791
+ v = block_reduce_sum(v, smem);
792
+ float inv = rsqrtf(v / (float)cols + eps);
793
+
794
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
795
+ %T% xv = %ST%(%LD%(xr[i]) + %LD%(rr[i]));
796
+ orow[i] = %ST%((%LD%(xv) - mean) * inv * %LD%(gamma[i]) + %LD%(beta[i]));
797
+ }
798
+ }
799
+ """
800
+ )
801
+
802
+ # Gated SiLU (SwiGLU): silu(x) * gate in one pass, no intermediate tensor.
803
+ SILU_GATE_SRC = (
804
+ PRELUDE
805
+ + r"""
806
+ extern "C" __global__ void silu_gate(const %T%* __restrict__ x,
807
+ const %T%* __restrict__ gate,
808
+ %T%* __restrict__ out,
809
+ long long n) {
810
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
811
+ long long stride = (long long)gridDim.x * blockDim.x;
812
+ for (; i < n; i += stride) {
813
+ float xv = %LD%(x[i]);
814
+ out[i] = %ST%(xv / (1.f + expf(-xv)) * %LD%(gate[i]));
815
+ }
816
+ }
817
+ """
818
+ )
819
+
820
+ # RoPE:x*cos + rotate_half(x)*sin。cos/sin 是每层共用的 (T, D) 位置表,
821
+ # x 视为 (..., T, D) 的连续缓冲;配对元素在同一 (b, h, t) 行内,前一半
822
+ # 看后一半取负、后一半看前一半,所以只需要 d 与 t 两个下标。
823
+ ROPE_SRC = (
824
+ PRELUDE
825
+ + r"""
826
+ extern "C" __global__ void rope(const %T%* __restrict__ x,
827
+ const %T%* __restrict__ cos,
828
+ const %T%* __restrict__ sin,
829
+ %T%* __restrict__ out,
830
+ long long n, int T, int D) {
831
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
832
+ long long stride = (long long)gridDim.x * blockDim.x;
833
+ for (; i < n; i += stride) {
834
+ int d = i % D;
835
+ long long rest = i / D;
836
+ int t = rest % T;
837
+ int half = D / 2;
838
+ long long row = i - d;
839
+ int pos = t * D + d;
840
+ long long src = d < half ? row + (d + half) : row + (d - half);
841
+ float sign = d < half ? -1.f : 1.f;
842
+ out[i] = %ST%(%LD%(x[i]) * %LD%(cos[pos]) + (sign * %LD%(x[src])) * %LD%(sin[pos]));
843
+ }
844
+ }
845
+ """
846
+ )
847
+
848
+ # batch_norm / batch_norm_stats:一个 block 处理一个通道。
849
+ # x 在这里被看成 (outer, channels, inner),所以同一个内核既能覆盖 NCHW,
850
+ # 也能覆盖任意"某一维是通道"的秩;outer/inner 由调用方按 axis 折算。
851
+ BATCH_NORM_SRC = (
852
+ PRELUDE
853
+ + r"""
854
+ extern "C" __global__ void batch_norm(const %T%* __restrict__ x,
855
+ const %T%* __restrict__ gamma,
856
+ const %T%* __restrict__ beta,
857
+ %T%* __restrict__ out,
858
+ long long outer, long long channels,
859
+ long long inner, float eps) {
860
+ const long long c = blockIdx.x;
861
+ if (c >= channels) { return; }
862
+ __shared__ float smem[1024];
863
+ const long long stride = channels * inner;
864
+ const float m = (float)(outer * inner);
865
+
866
+ // Two passes rather than sumsq - mean^2: the reference implementation
867
+ // (numpy.var) is two-pass, and matching it keeps the comparison tight.
868
+ float s = 0.f;
869
+ for (long long o = 0; o < outer; ++o) {
870
+ const %T%* base = x + o * stride + c * inner;
871
+ for (long long i = threadIdx.x; i < inner; i += blockDim.x) { s += %LD%(base[i]); }
872
+ }
873
+ s = block_reduce_sum(s, smem);
874
+ const float mean = s / m;
875
+
876
+ float v = 0.f;
877
+ for (long long o = 0; o < outer; ++o) {
878
+ const %T%* base = x + o * stride + c * inner;
879
+ for (long long i = threadIdx.x; i < inner; i += blockDim.x) {
880
+ const float d = %LD%(base[i]) - mean;
881
+ v += d * d;
882
+ }
883
+ }
884
+ v = block_reduce_sum(v, smem);
885
+ const float inv = rsqrtf(v / m + eps);
886
+ const float g = %LD%(gamma[c]);
887
+ const float b = %LD%(beta[c]);
888
+
889
+ for (long long o = 0; o < outer; ++o) {
890
+ const %T%* src = x + o * stride + c * inner;
891
+ %T%* dst = out + o * stride + c * inner;
892
+ for (long long i = threadIdx.x; i < inner; i += blockDim.x) {
893
+ dst[i] = %ST%((%LD%(src[i]) - mean) * inv * g + b);
894
+ }
895
+ }
896
+ }
897
+
898
+ // Same reduction as above, but writes mean/var out (flat layout (2, channels)).
899
+ extern "C" __global__ void batch_norm_stats(const %T%* __restrict__ x,
900
+ %T%* __restrict__ out,
901
+ long long outer, long long channels,
902
+ long long inner) {
903
+ const long long c = blockIdx.x;
904
+ if (c >= channels) { return; }
905
+ __shared__ float smem[1024];
906
+ const long long stride = channels * inner;
907
+ const float m = (float)(outer * inner);
908
+
909
+ float s = 0.f;
910
+ for (long long o = 0; o < outer; ++o) {
911
+ const %T%* base = x + o * stride + c * inner;
912
+ for (long long i = threadIdx.x; i < inner; i += blockDim.x) { s += %LD%(base[i]); }
913
+ }
914
+ s = block_reduce_sum(s, smem);
915
+ const float mean = s / m;
916
+
917
+ float v = 0.f;
918
+ for (long long o = 0; o < outer; ++o) {
919
+ const %T%* base = x + o * stride + c * inner;
920
+ for (long long i = threadIdx.x; i < inner; i += blockDim.x) {
921
+ const float d = %LD%(base[i]) - mean;
922
+ v += d * d;
923
+ }
924
+ }
925
+ v = block_reduce_sum(v, smem);
926
+
927
+ if (threadIdx.x == 0) {
928
+ out[c] = %ST%(mean);
929
+ out[channels + c] = %ST%(v / m);
930
+ }
931
+ }
932
+ """
933
+ )
934
+
935
+ REDUCE_SUM_SRC = (
936
+ PRELUDE
937
+ + r"""
938
+ extern "C" __global__ void reduce_sum_last(const %T%* __restrict__ x,
939
+ %T%* __restrict__ out,
940
+ long long rows, long long cols) {
941
+ long long row = blockIdx.x;
942
+ if (row >= rows) { return; }
943
+ const %T%* xr = x + row * cols;
944
+ __shared__ float smem[1024];
945
+ float s = 0.f;
946
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += %LD%(xr[i]); }
947
+ s = block_reduce_sum(s, smem);
948
+ if (threadIdx.x == 0) { out[row] = %ST%(s); }
949
+ }
950
+ """
951
+ )
952
+
953
+
954
+ REDUCE_MAX_SRC = (
955
+ PRELUDE
956
+ + r"""
957
+ extern "C" __global__ void reduce_max_last(const %T%* __restrict__ x,
958
+ %T%* __restrict__ out,
959
+ long long rows, long long cols) {
960
+ long long row = blockIdx.x;
961
+ if (row >= rows) { return; }
962
+ const %T%* xr = x + row * cols;
963
+ __shared__ float smem[1024];
964
+ float s = -3.4e38f;
965
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
966
+ float v = %LD%(xr[i]);
967
+ if (v > s) { s = v; }
968
+ }
969
+ s = block_reduce_max(s, smem);
970
+ if (threadIdx.x == 0) { out[row] = %ST%(s); }
971
+ }
972
+ """
973
+ )
974
+
975
+
976
+ REDUCE_MEAN_SRC = (
977
+ PRELUDE
978
+ + r"""
979
+ extern "C" __global__ void reduce_mean_last(const %T%* __restrict__ x,
980
+ %T%* __restrict__ out,
981
+ long long rows, long long cols) {
982
+ long long row = blockIdx.x;
983
+ if (row >= rows) { return; }
984
+ const %T%* xr = x + row * cols;
985
+ __shared__ float smem[1024];
986
+ float s = 0.f;
987
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += %LD%(xr[i]); }
988
+ s = block_reduce_sum(s, smem) / (float)cols;
989
+ if (threadIdx.x == 0) { out[row] = %ST%(s); }
990
+ }
991
+ """
992
+ )
993
+
994
+
995
+ # bool 归约(5.341):存储是 0/1 的 1 字节,求和等价于"数真值个数"。
996
+ # ``any`` 看和是否非零,``all`` 看和是否等于列数;判定放在块内归约之后。
997
+ REDUCE_ANY_SRC = (
998
+ PRELUDE
999
+ + r"""
1000
+ extern "C" __global__ void reduce_any_last(const %T%* __restrict__ x,
1001
+ %T%* __restrict__ out,
1002
+ long long rows, long long cols) {
1003
+ long long row = blockIdx.x;
1004
+ if (row >= rows) { return; }
1005
+ const %T%* xr = x + row * cols;
1006
+ __shared__ float smem[1024];
1007
+ float s = 0.f;
1008
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += %LD%(xr[i]); }
1009
+ s = block_reduce_sum(s, smem) != 0.f ? 1.f : 0.f;
1010
+ if (threadIdx.x == 0) { out[row] = %ST%(s); }
1011
+ }
1012
+ """
1013
+ )
1014
+
1015
+
1016
+ REDUCE_ALL_SRC = (
1017
+ PRELUDE
1018
+ + r"""
1019
+ extern "C" __global__ void reduce_all_last(const %T%* __restrict__ x,
1020
+ %T%* __restrict__ out,
1021
+ long long rows, long long cols) {
1022
+ long long row = blockIdx.x;
1023
+ if (row >= rows) { return; }
1024
+ const %T%* xr = x + row * cols;
1025
+ __shared__ float smem[1024];
1026
+ float s = 0.f;
1027
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) { s += %LD%(xr[i]); }
1028
+ s = block_reduce_sum(s, smem) == (float)cols ? 1.f : 0.f;
1029
+ if (threadIdx.x == 0) { out[row] = %ST%(s); }
1030
+ }
1031
+ """
1032
+ )
1033
+
1034
+
1035
+ ARGMAX_SRC = (
1036
+ PRELUDE
1037
+ + r"""
1038
+ // argmax over the last dim: block-wide max, then smallest matching index via
1039
+ // atomicMin so ties resolve to the first occurrence (numpy/PyTorch convention).
1040
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1041
+ extern "C" __global__ void argmax_last(const %T%* __restrict__ x,
1042
+ int* __restrict__ out,
1043
+ long long rows, long long cols) {
1044
+ long long row = blockIdx.x;
1045
+ if (row >= rows) { return; }
1046
+ const %T%* xr = x + row * cols;
1047
+ __shared__ float smem[1024];
1048
+ __shared__ int ibuf[1];
1049
+ float best = -3.4e38f;
1050
+ int best_i = -1;
1051
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
1052
+ float v = %LD%(xr[i]);
1053
+ if (v > best) { best = v; best_i = (int)i; }
1054
+ }
1055
+ float m = block_reduce_max(best, smem);
1056
+ if (threadIdx.x == 0) { ibuf[0] = (int)cols; }
1057
+ __syncthreads();
1058
+ if (best == m) { atomicMin(&ibuf[0], best_i); }
1059
+ __syncthreads();
1060
+ if (threadIdx.x == 0) { out[row] = ibuf[0]; }
1061
+ }
1062
+ """
1063
+ )
1064
+
1065
+
1066
+ TOPK_SRC = (
1067
+ PRELUDE
1068
+ + r"""
1069
+ // topk over the last dim: k rounds of (block-wide max, then smallest index via
1070
+ // atomicMin). Ties resolve to the smaller index and NaN ranks as +inf, matching
1071
+ // the IR reference (torch.topk convention). `sel` is dynamic shared memory with
1072
+ // room for k ints; it doubles as the buffer for the chosen index and as the
1073
+ // already-taken list, so the kernel never allocates per-row scratch.
1074
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1075
+ __device__ __forceinline__ void topk_select_row(const %T%* __restrict__ xr,
1076
+ long long cols, int k, int mode,
1077
+ %T%* __restrict__ vals,
1078
+ int* __restrict__ ids,
1079
+ float* smem, int* sel) {
1080
+ for (int rank = 0; rank < k; ++rank) {
1081
+ float best = __int_as_float(0xff800000); // -inf
1082
+ int best_i = 0x7fffffff;
1083
+ for (long long j = threadIdx.x; j < cols; j += blockDim.x) {
1084
+ int taken = 0;
1085
+ for (int t = 0; t < rank; ++t) {
1086
+ if (sel[t] == (int)j) { taken = 1; break; }
1087
+ }
1088
+ if (taken) { continue; }
1089
+ float v = %LD%(xr[j]);
1090
+ if (v != v) { v = __int_as_float(0x7f800000); } // +inf
1091
+ if (v > best || (v == best && (int)j < best_i)) {
1092
+ best = v;
1093
+ best_i = (int)j;
1094
+ }
1095
+ }
1096
+ float m = block_reduce_max(best, smem);
1097
+ if (threadIdx.x == 0) { sel[rank] = (int)cols; }
1098
+ __syncthreads();
1099
+ if (best == m) { atomicMin(&sel[rank], best_i); }
1100
+ __syncthreads();
1101
+ if (threadIdx.x == 0) {
1102
+ int at = sel[rank];
1103
+ if (mode == 0) { vals[(long long)rank] = xr[at]; }
1104
+ else if (mode == 1) { ids[(long long)rank] = at; }
1105
+ else { vals[at] = %ST%(1.f); }
1106
+ }
1107
+ __syncthreads();
1108
+ }
1109
+ }
1110
+
1111
+ extern "C" __global__ void topk_values(const %T%* __restrict__ x,
1112
+ void* __restrict__ outp,
1113
+ long long rows, long long cols, int k) {
1114
+ long long row = blockIdx.x;
1115
+ if (row >= rows) { return; }
1116
+ extern __shared__ int sel_dyn[];
1117
+ __shared__ float smem[1024];
1118
+ topk_select_row(x + row * cols, cols, k, 0,
1119
+ (%T%*)outp + row * (long long)k, 0, smem, sel_dyn);
1120
+ }
1121
+
1122
+ extern "C" __global__ void topk_indices(const %T%* __restrict__ x,
1123
+ void* __restrict__ outp,
1124
+ long long rows, long long cols, int k) {
1125
+ long long row = blockIdx.x;
1126
+ if (row >= rows) { return; }
1127
+ extern __shared__ int sel_dyn[];
1128
+ __shared__ float smem[1024];
1129
+ topk_select_row(x + row * cols, cols, k, 1,
1130
+ 0, (int*)outp + row * (long long)k, smem, sel_dyn);
1131
+ }
1132
+
1133
+ extern "C" __global__ void topk_mask_select(const %T%* __restrict__ x,
1134
+ void* __restrict__ outp,
1135
+ long long rows, long long cols, int k) {
1136
+ long long row = blockIdx.x;
1137
+ if (row >= rows) { return; }
1138
+ extern __shared__ int sel_dyn[];
1139
+ __shared__ float smem[1024];
1140
+ topk_select_row(x + row * cols, cols, k, 2,
1141
+ (%T%*)outp + row * cols, 0, smem, sel_dyn);
1142
+ }
1143
+ """
1144
+ )
1145
+
1146
+
1147
+ IM2COL_SRC = (
1148
+ PRELUDE
1149
+ + r"""
1150
+ // im2col: NCHW -> (N, C*KH*KW, HO*WO) column matrix for batched GEMM.
1151
+ // Segments are kept per batch (not merged into one big matrix) so the GEMM
1152
+ // output is already (N, O, HO*WO) and no transpose/col2im is needed.
1153
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1154
+ extern "C" __global__ void im2col(const %T%* __restrict__ x,
1155
+ %T%* __restrict__ cols,
1156
+ int C, int H, int W,
1157
+ int KH, int KW, int HO, int WO,
1158
+ int SH, int SW, int PH, int PW,
1159
+ int DH, int DW,
1160
+ long long total) {
1161
+ const long long step = (long long)gridDim.x * blockDim.x;
1162
+ const int plane = KH * KW;
1163
+ const int per_n = C * plane;
1164
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1165
+ idx < total; idx += step) {
1166
+ int wo = (int)(idx % WO);
1167
+ long long t = idx / WO;
1168
+ int ho = (int)(t % HO);
1169
+ t /= HO;
1170
+ int k = (int)(t % per_n);
1171
+ long long n = t / per_n;
1172
+ int kj = k % KW;
1173
+ int ki = (k / KW) % KH;
1174
+ int c = k / plane;
1175
+ int ih = ho * SH - PH + ki * DH;
1176
+ int iw = wo * SW - PW + kj * DW;
1177
+ float v = 0.f;
1178
+ if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
1179
+ v = %LD%(x[((long long)n * C + c) * H * W + (long long)ih * W + iw]);
1180
+ }
1181
+ cols[idx] = %ST%(v);
1182
+ }
1183
+ }
1184
+ """
1185
+ )
1186
+
1187
+
1188
+ MAXPOOL2D_SRC = (
1189
+ PRELUDE
1190
+ + r"""
1191
+ // maxpool2d: one thread per output element, grid-stride loop.
1192
+ // Cells that fall into the padded border are skipped, so they never compete
1193
+ // with real values in the max (matches the IR reference, which pads with -inf).
1194
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1195
+ extern "C" __global__ void maxpool2d(const %T%* __restrict__ x,
1196
+ %T%* __restrict__ out,
1197
+ int C, int H, int W,
1198
+ int KH, int KW, int HO, int WO,
1199
+ int SH, int SW, int PH, int PW,
1200
+ long long total) {
1201
+ const long long step = (long long)gridDim.x * blockDim.x;
1202
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1203
+ idx < total; idx += step) {
1204
+ int wo = (int)(idx % WO);
1205
+ long long t = idx / WO;
1206
+ int ho = (int)(t % HO);
1207
+ t /= HO;
1208
+ int c = (int)(t % C);
1209
+ long long n = t / C;
1210
+ const %T%* base = x + ((long long)n * C + c) * (long long)H * W;
1211
+ float m = __int_as_float(0xff800000); // -inf; NVRTC has no <math.h> macros
1212
+ for (int ki = 0; ki < KH; ++ki) {
1213
+ int ih = ho * SH - PH + ki;
1214
+ if (ih < 0 || ih >= H) { continue; }
1215
+ for (int kj = 0; kj < KW; ++kj) {
1216
+ int iw = wo * SW - PW + kj;
1217
+ if (iw < 0 || iw >= W) { continue; }
1218
+ float v = %LD%(base[(long long)ih * W + iw]);
1219
+ m = v > m ? v : m;
1220
+ }
1221
+ }
1222
+ out[idx] = %ST%(m);
1223
+ }
1224
+ }
1225
+ """
1226
+ )
1227
+
1228
+
1229
+ CONV2D_TILED_SRC = (
1230
+ PRELUDE
1231
+ + r"""
1232
+ // Direct tiled conv2d (NCHW, cross-correlation, no kernel flip).
1233
+ // One thread computes ROC output channels at one spatial position. Two kinds of
1234
+ // reuse make this competitive with im2col + GEMM without materializing the
1235
+ // (N, K, HO*WO) column buffer:
1236
+ // 1. weights for the block's TOC channels are staged in shared memory CB
1237
+ // input channels at a time (TOC*CB*KH*KW floats), so shared memory stays
1238
+ // small enough to keep occupancy high while the barrier cost is amortized
1239
+ // over CB channels of work;
1240
+ // 2. each input value fetched from global memory feeds ROC accumulators,
1241
+ // cutting global input reads by a factor of ROC.
1242
+ // Threads that fall outside the output stay in the loop so every
1243
+ // __syncthreads() is reached by the whole block.
1244
+ // The bias is folded into the store: acc + (has_bias ? b[oc] : 0). Callers
1245
+ // without a bias pass any valid pointer and has_bias = 0; it is never read.
1246
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1247
+ extern "C" __global__ void conv2d_tiled(const float* __restrict__ x,
1248
+ const float* __restrict__ w,
1249
+ float* __restrict__ out,
1250
+ const float* __restrict__ b,
1251
+ int C, int H, int W,
1252
+ int O, int KH, int KW,
1253
+ int HO, int WO,
1254
+ int SH, int SW, int PH, int PW,
1255
+ int DH, int DW,
1256
+ int TOC, int ROC, int CB, int oc_tiles,
1257
+ int has_bias) {
1258
+ extern __shared__ float sw[];
1259
+ const int nx = blockDim.x;
1260
+ const int nt = nx * blockDim.y;
1261
+ const int tid = threadIdx.y * nx + threadIdx.x;
1262
+ const int khkw = KH * KW;
1263
+ const int K = C * khkw;
1264
+
1265
+ const int tile = blockIdx.z;
1266
+ const int oc0 = (tile % oc_tiles) * TOC;
1267
+ const int n = tile / oc_tiles;
1268
+ const int ho = blockIdx.y;
1269
+ const int wo = blockIdx.x * nx + threadIdx.x;
1270
+ const int oc = oc0 + threadIdx.y * ROC;
1271
+
1272
+ const bool active = (wo < WO) && (oc < O);
1273
+ // Fast path: the whole KH*KW window lies inside the image, so the inner
1274
+ // loops need no bounds checks. Only border threads take the slow path.
1275
+ const int ih0 = ho * SH - PH;
1276
+ const int iw0 = wo * SW - PW;
1277
+ const bool inside = active && ih0 >= 0 && ih0 + (KH - 1) * DH < H &&
1278
+ iw0 >= 0 && iw0 + (KW - 1) * DW < W;
1279
+ const float* xn = x + (long long)n * C * H * W;
1280
+ float acc[8];
1281
+ for (int j = 0; j < ROC; ++j) { acc[j] = 0.f; }
1282
+
1283
+ for (int c0 = 0; c0 < C; c0 += CB) {
1284
+ __syncthreads();
1285
+ const int cb = (C - c0 < CB) ? (C - c0) : CB;
1286
+ for (int i = tid; i < TOC * cb * khkw; i += nt) {
1287
+ const int t = i % khkw;
1288
+ const int rest = i / khkw;
1289
+ const int cc = rest % cb;
1290
+ const int ocg = oc0 + rest / cb;
1291
+ sw[i] = ocg < O ? w[(long long)ocg * K + (long long)(c0 + cc) * khkw + t]
1292
+ : 0.f;
1293
+ }
1294
+ __syncthreads();
1295
+ if (!active) { continue; }
1296
+
1297
+ if (inside) {
1298
+ // Fast path: the whole KH*KW window is inside the image, so the
1299
+ // inner loops carry no bounds checks at all.
1300
+ for (int cc = 0; cc < cb; ++cc) {
1301
+ const float* xc = xn + (long long)(c0 + cc) * H * W;
1302
+ const float* wb = sw + cc * khkw;
1303
+ for (int ki = 0; ki < KH; ++ki) {
1304
+ const float* xr = xc + (long long)(ih0 + ki * DH) * W;
1305
+ const int off = threadIdx.y * ROC * cb * khkw + ki * KW;
1306
+ for (int kj = 0; kj < KW; ++kj) {
1307
+ const float v = xr[iw0 + kj * DW];
1308
+ for (int j = 0; j < ROC; ++j) {
1309
+ acc[j] += v * wb[off + j * cb * khkw + kj];
1310
+ }
1311
+ }
1312
+ }
1313
+ }
1314
+ } else {
1315
+ for (int cc = 0; cc < cb; ++cc) {
1316
+ const float* xc = xn + (long long)(c0 + cc) * H * W;
1317
+ const float* wb = sw + cc * khkw;
1318
+ for (int ki = 0; ki < KH; ++ki) {
1319
+ const int ih = ih0 + ki * DH;
1320
+ if (ih < 0 || ih >= H) { continue; }
1321
+ const float* xr = xc + (long long)ih * W;
1322
+ const int off = threadIdx.y * ROC * cb * khkw + ki * KW;
1323
+ for (int kj = 0; kj < KW; ++kj) {
1324
+ const int iw = iw0 + kj * DW;
1325
+ if (iw < 0 || iw >= W) { continue; }
1326
+ const float v = xr[iw];
1327
+ for (int j = 0; j < ROC; ++j) {
1328
+ acc[j] += v * wb[off + j * cb * khkw + kj];
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ if (!active) { return; }
1337
+ float* dst = out + ((long long)n * O + oc) * HO * WO + (long long)ho * WO + wo;
1338
+ for (int j = 0; j < ROC; ++j) {
1339
+ if (oc + j < O) {
1340
+ dst[(long long)j * HO * WO] = acc[j] + (has_bias ? b[oc + j] : 0.f);
1341
+ }
1342
+ }
1343
+ }
1344
+ """
1345
+ )
1346
+
1347
+
1348
+ RMSNORM_SRC = (
1349
+ PRELUDE
1350
+ + r"""
1351
+ // rmsnorm: one block per row, reduce mean(x^2) over the last dim.
1352
+ // No mean-centering and no beta -- that is what separates RMSNorm from
1353
+ // LayerNorm, and it is why the reference only needs one reduction.
1354
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1355
+ extern "C" __global__ void rmsnorm_last(const %T%* __restrict__ x,
1356
+ const %T%* __restrict__ gamma,
1357
+ %T%* __restrict__ out,
1358
+ long long rows, long long cols, float eps) {
1359
+ long long row = blockIdx.x;
1360
+ if (row >= rows) { return; }
1361
+ const %T%* xr = x + row * cols;
1362
+ %T%* orow = out + row * cols;
1363
+ __shared__ float smem[1024];
1364
+
1365
+ float s = 0.f;
1366
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
1367
+ float v = %LD%(xr[i]);
1368
+ s += v * v;
1369
+ }
1370
+ s = block_reduce_sum(s, smem);
1371
+ float inv = rsqrtf(s / (float)cols + eps);
1372
+
1373
+ for (long long i = threadIdx.x; i < cols; i += blockDim.x) {
1374
+ orow[i] = %ST%(%LD%(xr[i]) * inv * %LD%(gamma[i]));
1375
+ }
1376
+ }
1377
+ """
1378
+ )
1379
+
1380
+ AVGPOOL2D_SRC = (
1381
+ PRELUDE
1382
+ + r"""
1383
+ // avgpool2d: one thread per output element, grid-stride loop.
1384
+ // The divisor is the number of taps that landed inside the *padded* input:
1385
+ // with count_include_pad the padding zeros count towards it (bounds
1386
+ // [-P, size + P)), otherwise only real samples do (bounds [0, size)).
1387
+ // ceil_mode lets the last window start inside the image but run past the
1388
+ // padded input; those overhanging taps count for neither the sum nor the
1389
+ // divisor, which is why the divisor cannot be a fixed KH*KW.
1390
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1391
+ extern "C" __global__ void avgpool2d(const %T%* __restrict__ x,
1392
+ %T%* __restrict__ out,
1393
+ int C, int H, int W,
1394
+ int KH, int KW, int HO, int WO,
1395
+ int SH, int SW, int PH, int PW,
1396
+ long long total,
1397
+ int count_include_pad) {
1398
+ const long long step = (long long)gridDim.x * blockDim.x;
1399
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1400
+ idx < total; idx += step) {
1401
+ int wo = (int)(idx % WO);
1402
+ long long t = idx / WO;
1403
+ int ho = (int)(t % HO);
1404
+ t /= HO;
1405
+ int c = (int)(t % C);
1406
+ long long n = t / C;
1407
+ int lo_h = count_include_pad != 0 ? -1 * PH : 0;
1408
+ int hi_h = count_include_pad != 0 ? H + PH : H;
1409
+ int lo_w = count_include_pad != 0 ? -1 * PW : 0;
1410
+ int hi_w = count_include_pad != 0 ? W + PW : W;
1411
+ const %T%* base = x + ((long long)n * C + c) * (long long)H * W;
1412
+ float acc = 0.f;
1413
+ int cnt = 0;
1414
+ for (int ki = 0; ki < KH; ++ki) {
1415
+ int ih = ho * SH - PH + ki;
1416
+ if (ih < lo_h || ih >= hi_h) { continue; }
1417
+ for (int kj = 0; kj < KW; ++kj) {
1418
+ int iw = wo * SW - PW + kj;
1419
+ if (iw < lo_w || iw >= hi_w) { continue; }
1420
+ cnt += 1;
1421
+ acc += ih >= 0 && ih < H && iw >= 0 && iw < W ? %LD%(base[(long long)ih * W + iw]) : 0.f;
1422
+ }
1423
+ }
1424
+ float den = cnt > 0 ? 1.f / (float)cnt : 1.f;
1425
+ out[idx] = %ST%(acc * den);
1426
+ }
1427
+ }
1428
+ """
1429
+ )
1430
+
1431
+ AVGPOOL2D_BACKWARD_SRC = (
1432
+ PRELUDE
1433
+ + r"""
1434
+ // avgpool2d backward: scatter dy/divisor back to every real input position.
1435
+ // The divisor matches the forward pass tap for tap: count_include_pad widens
1436
+ // the counting bounds to [-P, size + P), otherwise they stay [0, size).
1437
+ // Overlapping windows touch the same input cell, so the accumulation must be
1438
+ // atomic -- a plain store would keep only the last window's contribution.
1439
+ // Padding only contributes to the divisor; it never receives a gradient.
1440
+ // dx is zero-initialised by the caller.
1441
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1442
+ extern "C" __global__ void avgpool2d_backward(const %T%* __restrict__ dy,
1443
+ %T%* __restrict__ dx,
1444
+ int C, int H, int W,
1445
+ int KH, int KW, int HO, int WO,
1446
+ int SH, int SW, int PH, int PW,
1447
+ long long total,
1448
+ int count_include_pad) {
1449
+ const long long step = (long long)gridDim.x * blockDim.x;
1450
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1451
+ idx < total; idx += step) {
1452
+ int wo = (int)(idx % WO);
1453
+ long long t = idx / WO;
1454
+ int ho = (int)(t % HO);
1455
+ t /= HO;
1456
+ int c = (int)(t % C);
1457
+ long long n = t / C;
1458
+ int lo_h = count_include_pad != 0 ? -1 * PH : 0;
1459
+ int hi_h = count_include_pad != 0 ? H + PH : H;
1460
+ int lo_w = count_include_pad != 0 ? -1 * PW : 0;
1461
+ int hi_w = count_include_pad != 0 ? W + PW : W;
1462
+ int cnt = 0;
1463
+ for (int ki = 0; ki < KH; ++ki) {
1464
+ int ih = ho * SH - PH + ki;
1465
+ if (ih < lo_h || ih >= hi_h) { continue; }
1466
+ for (int kj = 0; kj < KW; ++kj) {
1467
+ int iw = wo * SW - PW + kj;
1468
+ if (iw < lo_w || iw >= hi_w) { continue; }
1469
+ cnt += 1;
1470
+ }
1471
+ }
1472
+ float den = cnt > 0 ? 1.f / (float)cnt : 1.f;
1473
+ float g = %LD%(dy[idx]) * den;
1474
+ %T%* base = dx + ((long long)n * C + c) * (long long)H * W;
1475
+ for (int ki = 0; ki < KH; ++ki) {
1476
+ int ih = ho * SH - PH + ki;
1477
+ if (ih < lo_h || ih >= hi_h) { continue; }
1478
+ for (int kj = 0; kj < KW; ++kj) {
1479
+ int iw = wo * SW - PW + kj;
1480
+ if (iw < lo_w || iw >= hi_w) { continue; }
1481
+ if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
1482
+ %ATOMIC%(&base[(long long)ih * W + iw], g);
1483
+ }
1484
+ }
1485
+ }
1486
+ }
1487
+ }
1488
+ """
1489
+ )
1490
+
1491
+ ADAPTIVE_AVGPOOL2D_SRC = (
1492
+ PRELUDE
1493
+ + r"""
1494
+ // adaptive_avg_pool2d: one thread per output element.
1495
+ // The window of output cell (oh, ow) is [floor(oh*H/OH), ceil((oh+1)*H/OH))
1496
+ // by [floor(ow*W/OW), ceil((ow+1)*W/OW)); for H not divisible by OH adjacent
1497
+ // windows overlap, and the divisor is this window's own area, not a constant.
1498
+ // The integer form of floor/ceil is used so the window edges match the IR
1499
+ // reference exactly (no float rounding on the boundary).
1500
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1501
+ extern "C" __global__ void adaptive_avg_pool2d(const %T%* __restrict__ x,
1502
+ %T%* __restrict__ out,
1503
+ int C, int H, int W,
1504
+ int OH, int OW,
1505
+ long long total) {
1506
+ const long long step = (long long)gridDim.x * blockDim.x;
1507
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1508
+ idx < total; idx += step) {
1509
+ int ow = (int)(idx % OW);
1510
+ long long t = idx / OW;
1511
+ int oh = (int)(t % OH);
1512
+ t /= OH;
1513
+ int c = (int)(t % C);
1514
+ long long n = t / C;
1515
+ const %T%* base = x + ((long long)n * C + c) * (long long)H * W;
1516
+ int hs = (int)(((long long)oh * H) / OH);
1517
+ int he = (int)((((long long)(oh + 1) * H) + OH - 1) / OH);
1518
+ int ws = (int)(((long long)ow * W) / OW);
1519
+ int we = (int)((((long long)(ow + 1) * W) + OW - 1) / OW);
1520
+ float acc = 0.f;
1521
+ for (int ih = hs; ih < he; ++ih) {
1522
+ for (int iw = ws; iw < we; ++iw) {
1523
+ acc += %LD%(base[(long long)ih * W + iw]);
1524
+ }
1525
+ }
1526
+ out[idx] = %ST%(acc / (float)((he - hs) * (we - ws)));
1527
+ }
1528
+ }
1529
+ """
1530
+ )
1531
+
1532
+ ADAPTIVE_AVGPOOL2D_BACKWARD_SRC = (
1533
+ PRELUDE
1534
+ + r"""
1535
+ // adaptive_avg_pool2d backward: scatter dy/window_area to the window's cells.
1536
+ // Windows may overlap when the input size is not divisible by the output size,
1537
+ // so the same input cell can receive several contributions -- atomic add is
1538
+ // required (dx is zero-initialised by the caller), exactly like avgpool2d.
1539
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1540
+ extern "C" __global__ void adaptive_avg_pool2d_backward(const %T%* __restrict__ dy,
1541
+ %T%* __restrict__ dx,
1542
+ int C, int H, int W,
1543
+ int OH, int OW,
1544
+ long long total) {
1545
+ const long long step = (long long)gridDim.x * blockDim.x;
1546
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1547
+ idx < total; idx += step) {
1548
+ int ow = (int)(idx % OW);
1549
+ long long t = idx / OW;
1550
+ int oh = (int)(t % OH);
1551
+ t /= OH;
1552
+ int c = (int)(t % C);
1553
+ long long n = t / C;
1554
+ int hs = (int)(((long long)oh * H) / OH);
1555
+ int he = (int)((((long long)(oh + 1) * H) + OH - 1) / OH);
1556
+ int ws = (int)(((long long)ow * W) / OW);
1557
+ int we = (int)((((long long)(ow + 1) * W) + OW - 1) / OW);
1558
+ float share = %LD%(dy[idx]) / (float)((he - hs) * (we - ws));
1559
+ %T%* base = dx + ((long long)n * C + c) * (long long)H * W;
1560
+ for (int ih = hs; ih < he; ++ih) {
1561
+ for (int iw = ws; iw < we; ++iw) {
1562
+ %ATOMIC%(&base[(long long)ih * W + iw], share);
1563
+ }
1564
+ }
1565
+ }
1566
+ }
1567
+ """
1568
+ )
1569
+
1570
+ CONCAT_COPY_SRC = (
1571
+ PRELUDE
1572
+ + r"""
1573
+ // concat: one strided copy per input segment, launched once per input.
1574
+ // Viewing the tensor as (outer, axis, inner) turns concat into "copy this
1575
+ // segment to a shifted axis offset"; no index table over the input list is
1576
+ // needed, and every copy stays coalesced along the inner dimension.
1577
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1578
+ extern "C" __global__ void concat_copy(const %T%* __restrict__ x,
1579
+ %T%* __restrict__ out,
1580
+ long long len, long long inner,
1581
+ long long out_axis, long long offset,
1582
+ long long total) {
1583
+ const long long step = (long long)gridDim.x * blockDim.x;
1584
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1585
+ idx < total; idx += step) {
1586
+ long long j = idx % inner;
1587
+ long long t = idx / inner;
1588
+ long long s = t % len;
1589
+ long long o = t / len;
1590
+ out[((o * out_axis) + offset + s) * inner + j] = x[idx];
1591
+ }
1592
+ }
1593
+ """
1594
+ )
1595
+
1596
+ MAXPOOL2D_BACKWARD_SRC = (
1597
+ PRELUDE
1598
+ + r"""
1599
+ // maxpool2d backward: route dy to the argmax cell of each window.
1600
+ // Ties pick the FIRST maximum in row-major scan order, which is exactly what
1601
+ // the IR reference does -- flipping the comparison to >= would silently change
1602
+ // the semantics on plateaus. Overlapping windows can land on the same input
1603
+ // cell, so the scatter must be atomic.
1604
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1605
+ extern "C" __global__ void maxpool2d_backward(const %T%* __restrict__ x,
1606
+ const %T%* __restrict__ dy,
1607
+ %T%* __restrict__ dx,
1608
+ int C, int H, int W,
1609
+ int KH, int KW, int HO, int WO,
1610
+ int SH, int SW, int PH, int PW,
1611
+ long long total) {
1612
+ const long long step = (long long)gridDim.x * blockDim.x;
1613
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1614
+ idx < total; idx += step) {
1615
+ int wo = (int)(idx % WO);
1616
+ long long t = idx / WO;
1617
+ int ho = (int)(t % HO);
1618
+ t /= HO;
1619
+ int c = (int)(t % C);
1620
+ long long n = t / C;
1621
+ const %T%* base = x + ((long long)n * C + c) * (long long)H * W;
1622
+ float best = -3.4e38f;
1623
+ int best_ih = -1, best_iw = -1;
1624
+ for (int ki = 0; ki < KH; ++ki) {
1625
+ int ih = ho * SH - PH + ki;
1626
+ if (ih < 0 || ih >= H) { continue; }
1627
+ for (int kj = 0; kj < KW; ++kj) {
1628
+ int iw = wo * SW - PW + kj;
1629
+ if (iw < 0 || iw >= W) { continue; }
1630
+ float v = %LD%(base[(long long)ih * W + iw]);
1631
+ if (best_ih < 0 || v > best) {
1632
+ best = v;
1633
+ best_ih = ih;
1634
+ best_iw = iw;
1635
+ }
1636
+ }
1637
+ }
1638
+ if (best_ih >= 0) {
1639
+ %T%* dst = dx + ((long long)n * C + c) * (long long)H * W;
1640
+ %ATOMIC%(&dst[(long long)best_ih * W + best_iw], %LD%(dy[idx]));
1641
+ }
1642
+ }
1643
+ }
1644
+ """
1645
+ )
1646
+
1647
+ MAXPOOL2D_INDICES_SRC = (
1648
+ PRELUDE
1649
+ + r"""
1650
+ // maxpool2d indices: one thread per output element.
1651
+ // Writes ih*W + iw of the window maximum (i32), matching PyTorch's
1652
+ // max_pool2d(return_indices=True). Ties pick the FIRST maximum in row-major
1653
+ // scan order, exactly like maxpool2d_backward, so the three pooling ops agree
1654
+ // on which element they mean. A window entirely inside padding would leave
1655
+ // nothing to report; -1 is written first so the output is never undefined.
1656
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1657
+ extern "C" __global__ void maxpool2d_indices(const %T%* __restrict__ x,
1658
+ int* __restrict__ out,
1659
+ int C, int H, int W,
1660
+ int KH, int KW, int HO, int WO,
1661
+ int SH, int SW, int PH, int PW,
1662
+ long long total) {
1663
+ const long long step = (long long)gridDim.x * blockDim.x;
1664
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1665
+ idx < total; idx += step) {
1666
+ int wo = (int)(idx % WO);
1667
+ long long t = idx / WO;
1668
+ int ho = (int)(t % HO);
1669
+ t /= HO;
1670
+ int c = (int)(t % C);
1671
+ long long n = t / C;
1672
+ const %T%* base = x + ((long long)n * C + c) * (long long)H * W;
1673
+ float best = -3.4e38f;
1674
+ int best_ih = -1, best_iw = -1;
1675
+ for (int ki = 0; ki < KH; ++ki) {
1676
+ int ih = ho * SH - PH + ki;
1677
+ if (ih < 0 || ih >= H) { continue; }
1678
+ for (int kj = 0; kj < KW; ++kj) {
1679
+ int iw = wo * SW - PW + kj;
1680
+ if (iw < 0 || iw >= W) { continue; }
1681
+ float v = %LD%(base[(long long)ih * W + iw]);
1682
+ if (best_ih < 0 || v > best) {
1683
+ best = v;
1684
+ best_ih = ih;
1685
+ best_iw = iw;
1686
+ }
1687
+ }
1688
+ }
1689
+ out[idx] = -1;
1690
+ if (best_ih >= 0) {
1691
+ out[idx] = best_ih * W + best_iw;
1692
+ }
1693
+ }
1694
+ }
1695
+ """
1696
+ )
1697
+
1698
+ CONV2D_INPUT_GRAD_SRC = (
1699
+ PRELUDE
1700
+ + r"""
1701
+ // conv2d input gradient (gather form): one thread per dx element.
1702
+ // For a fixed input cell (ih, iw) the contributing output cells are those with
1703
+ // ho*SH - PH + ki*DH == ih, so ho = (ih + PH - ki*DH)/SH and must be an exact
1704
+ // non-negative division. Gathering avoids atomics entirely: every dx element
1705
+ // is written by exactly one thread, and each thread sums over (o, ki, kj).
1706
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1707
+ extern "C" __global__ void conv2d_input_grad(const %T%* __restrict__ dy,
1708
+ const %T%* __restrict__ weight,
1709
+ %T%* __restrict__ dx,
1710
+ int C, int H, int W,
1711
+ int O, int KH, int KW, int HO, int WO,
1712
+ int SH, int SW, int PH, int PW,
1713
+ int DH, int DW,
1714
+ long long total) {
1715
+ const long long step = (long long)gridDim.x * blockDim.x;
1716
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1717
+ idx < total; idx += step) {
1718
+ int iw = (int)(idx % W);
1719
+ long long t = idx / W;
1720
+ int ih = (int)(t % H);
1721
+ t /= H;
1722
+ int c = (int)(t % C);
1723
+ long long n = t / C;
1724
+
1725
+ float acc = 0.f;
1726
+ for (int oi = 0; oi < O; ++oi) {
1727
+ for (int ki = 0; ki < KH; ++ki) {
1728
+ int num = ih + PH - ki * DH;
1729
+ if (num < 0 || num % SH != 0) { continue; }
1730
+ int ho = num / SH;
1731
+ if (ho >= HO) { continue; }
1732
+ for (int kj = 0; kj < KW; ++kj) {
1733
+ int numw = iw + PW - kj * DW;
1734
+ if (numw < 0 || numw % SW != 0) { continue; }
1735
+ int wo = numw / SW;
1736
+ if (wo >= WO) { continue; }
1737
+ acc += %LD%(dy[((long long)(n * O + oi) * HO + ho) * WO + wo])
1738
+ * %LD%(weight[((long long)(oi * C + c) * KH + ki) * KW + kj]);
1739
+ }
1740
+ }
1741
+ }
1742
+ dx[idx] = %ST%(acc);
1743
+ }
1744
+ }
1745
+ """
1746
+ )
1747
+
1748
+ CONV2D_WEIGHT_GRAD_SRC = (
1749
+ PRELUDE
1750
+ + r"""
1751
+ // conv2d weight gradient (gather form): one thread per dw element.
1752
+ // Accumulates over the whole batch and every output cell, so small batch
1753
+ // training is compute-bound here -- same order as the forward convolution.
1754
+ // Gathering again keeps the result deterministic (no float atomics).
1755
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1756
+ extern "C" __global__ void conv2d_weight_grad(const %T%* __restrict__ x,
1757
+ const %T%* __restrict__ dy,
1758
+ %T%* __restrict__ dw,
1759
+ int N, int C, int H, int W,
1760
+ int O, int KH, int KW, int HO, int WO,
1761
+ int SH, int SW, int PH, int PW,
1762
+ int DH, int DW,
1763
+ long long total) {
1764
+ const long long step = (long long)gridDim.x * blockDim.x;
1765
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1766
+ idx < total; idx += step) {
1767
+ int kj = (int)(idx % KW);
1768
+ long long t = idx / KW;
1769
+ int ki = (int)(t % KH);
1770
+ t /= KH;
1771
+ int ci = (int)(t % C);
1772
+ int oi = (int)(t / C);
1773
+
1774
+ float acc = 0.f;
1775
+ for (long long ni = 0; ni < N; ++ni) {
1776
+ for (int ho = 0; ho < HO; ++ho) {
1777
+ int ih = ho * SH - PH + ki * DH;
1778
+ if (ih < 0 || ih >= H) { continue; }
1779
+ for (int wo = 0; wo < WO; ++wo) {
1780
+ int iw = wo * SW - PW + kj * DW;
1781
+ if (iw < 0 || iw >= W) { continue; }
1782
+ acc += %LD%(dy[((long long)(ni * O + oi) * HO + ho) * WO + wo])
1783
+ * %LD%(x[((long long)(ni * C + ci) * H + ih) * W + iw]);
1784
+ }
1785
+ }
1786
+ }
1787
+ dw[idx] = %ST%(acc);
1788
+ }
1789
+ }
1790
+ """
1791
+ )
1792
+
1793
+ # dropout 的掩码生成。随机源刻意不用 cuRAND:参考实现(numpy)与内核必须
1794
+ # 生成**逐位相同**的掩码,否则这个算子无法做跨后端对拍,只剩"统计上近似"
1795
+ # 这一种弱验证。SplitMix64 只用整数乘法与异或,两边用同一套位运算即可。
1796
+ DROPOUT_MASK_SRC = (
1797
+ PRELUDE
1798
+ + r"""
1799
+ __device__ __forceinline__ unsigned long long splitmix64(unsigned long long z) {
1800
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
1801
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
1802
+ return z ^ (z >> 31);
1803
+ }
1804
+
1805
+ // One thread per element. The flat index doubles as the counter, so the mask
1806
+ // depends only on (seed, index) and never on the launch geometry: the same
1807
+ // seed yields the same mask on any device and with any block size.
1808
+ extern "C" __global__ void dropout_mask(%T%* __restrict__ out,
1809
+ long long n,
1810
+ float p,
1811
+ float scale,
1812
+ unsigned long long seed) {
1813
+ const long long step = (long long)gridDim.x * blockDim.x;
1814
+ for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1815
+ i < n; i += step) {
1816
+ unsigned long long z =
1817
+ splitmix64(seed + (unsigned long long)i * 0x9E3779B97F4A7C15ULL);
1818
+ // Top 24 bits map to [0, 1); that is exactly the float32 mantissa width,
1819
+ // so numpy and CUDA land on the same float without extra rounding.
1820
+ float u = (float)((z >> 40) & 0xFFFFFFULL) * (1.0f / 16777216.0f);
1821
+ out[i] = %ST%((u >= p) ? scale : 0.0f);
1822
+ }
1823
+ }
1824
+ """
1825
+ )
1826
+
1827
+ # 运行期 key 版:seed 从设备内存读,捕获成 CUDA Graph 之后仍能换掩码。
1828
+ # L2 描述的参数类型只有浮点张量与标量,表达不了"整数指针"参数,所以这一版
1829
+ # 是手写模板;常量 seed 版继续走 L2(流水线没有分叉,只是这一个变体多一条路)。
1830
+ DROPOUT_MASK_KEYED_SRC = (
1831
+ PRELUDE
1832
+ + r"""
1833
+ __device__ __forceinline__ unsigned long long splitmix64(unsigned long long z) {
1834
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
1835
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
1836
+ return z ^ (z >> 31);
1837
+ }
1838
+
1839
+ // Same bit-exact mapping as the constant-seed kernel, but the seed is read
1840
+ // from device memory: a captured CUDA Graph replays the same launch, so a
1841
+ // scalar kernel argument would freeze the mask forever. `offset` separates
1842
+ // dropout sites that share one key input.
1843
+ extern "C" __global__ void dropout_mask_keyed(%T%* __restrict__ out,
1844
+ long long n,
1845
+ float p,
1846
+ float scale,
1847
+ const int* __restrict__ key,
1848
+ unsigned long long offset) {
1849
+ const unsigned long long seed =
1850
+ (unsigned long long)(long long)(*key) + offset;
1851
+ const long long step = (long long)gridDim.x * blockDim.x;
1852
+ for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1853
+ i < n; i += step) {
1854
+ unsigned long long z =
1855
+ splitmix64(seed + (unsigned long long)i * 0x9E3779B97F4A7C15ULL);
1856
+ float u = (float)((z >> 40) & 0xFFFFFFULL) * (1.0f / 16777216.0f);
1857
+ out[i] = %ST%((u >= p) ? scale : 0.0f);
1858
+ }
1859
+ }
1860
+ """
1861
+ )
1862
+
1863
+ _EMBEDDING_TMPL = (
1864
+ PRELUDE
1865
+ + r"""
1866
+ // embedding: gather row ids[i] from the table. The table is viewed as
1867
+ // (vocab, row) so any trailing shape works without extra arithmetic.
1868
+ // An out-of-range id cannot be raised from inside a kernel: instead of a
1869
+ // silent clamp we flag it in *err, and the host turns that into a
1870
+ // BackendCapabilityError. The clamp only prevents an illegal memory access
1871
+ // on the way to that error.
1872
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1873
+ extern "C" __global__ void embedding(const %T%* __restrict__ table,
1874
+ const %IDS_T%* __restrict__ ids,
1875
+ %T%* __restrict__ out,
1876
+ long long n, long long row, long long vocab,
1877
+ int* __restrict__ err, long long total) {
1878
+ const long long step = (long long)gridDim.x * blockDim.x;
1879
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1880
+ idx < total; idx += step) {
1881
+ long long j = idx % row;
1882
+ long long i = idx / row;
1883
+ long long v = (long long)ids[i];
1884
+ if (v < 0 || v >= vocab) { *err = 1; v = 0; }
1885
+ out[idx] = table[v * row + j];
1886
+ }
1887
+ }
1888
+ """
1889
+ )
1890
+
1891
+ _EMBEDDING_BACKWARD_TMPL = (
1892
+ PRELUDE
1893
+ + r"""
1894
+ // embedding backward: scatter-add each dy row back to its table row.
1895
+ // Repeated ids are the normal case (the same token appears many times in a
1896
+ // batch), so the accumulation must be atomic; assignment would lose all but
1897
+ // the last occurrence.
1898
+ // NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1899
+ extern "C" __global__ void embedding_backward(const %T%* __restrict__ dy,
1900
+ const %IDS_T%* __restrict__ ids,
1901
+ %T%* __restrict__ dtable,
1902
+ long long n, long long row, long long vocab,
1903
+ int* __restrict__ err, long long total) {
1904
+ const long long step = (long long)gridDim.x * blockDim.x;
1905
+ for (long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1906
+ idx < total; idx += step) {
1907
+ long long j = idx % row;
1908
+ long long i = idx / row;
1909
+ long long v = (long long)ids[i];
1910
+ if (v < 0 || v >= vocab) { *err = 1; continue; }
1911
+ %ATOMIC%(&dtable[v * row + j], %LD%(dy[idx]));
1912
+ }
1913
+ }
1914
+ """
1915
+ )
1916
+
1917
+
1918
+ # gather: out[p] = x[(o * x_dim + v) * inner + i]. idx / out are viewed as
1919
+ # (outer, idx_dim, inner) and x as (outer, x_dim, inner) -- the IR requires
1920
+ # the same rank and equal non-dim extents, so this three-axis form is exact.
1921
+ # Out-of-range ids are flagged in *err instead of being wrapped; the clamp to
1922
+ # 0 only prevents an illegal access on the way to the host-side error.
1923
+ # NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
1924
+ _GATHER_TMPL = (
1925
+ PRELUDE
1926
+ + r"""
1927
+ extern "C" __global__ void gather(const %T%* __restrict__ x,
1928
+ const %IDS_T%* __restrict__ idx,
1929
+ %T%* __restrict__ out,
1930
+ long long total, long long inner,
1931
+ long long idx_dim, long long x_dim,
1932
+ int* __restrict__ err) {
1933
+ const long long step = (long long)gridDim.x * blockDim.x;
1934
+ for (long long p = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1935
+ p < total; p += step) {
1936
+ const long long i = p % inner;
1937
+ const long long t = p / inner;
1938
+ const long long o = t / idx_dim;
1939
+ long long v = (long long)idx[p];
1940
+ if (v < 0 || v >= x_dim) { *err = 1; v = 0; }
1941
+ out[p] = x[(o * x_dim + v) * inner + i];
1942
+ }
1943
+ }
1944
+ """
1945
+ )
1946
+
1947
+ # gather backward: scatter-add dy[p] to the selected slot of x. Repeated ids
1948
+ # are expected (the same row can be selected many times), so the add is
1949
+ # atomic; a plain store would keep only the last contribution.
1950
+ _GATHER_BACKWARD_TMPL = (
1951
+ PRELUDE
1952
+ + r"""
1953
+ extern "C" __global__ void gather_backward(const %T%* __restrict__ dy,
1954
+ const %IDS_T%* __restrict__ idx,
1955
+ %T%* __restrict__ dx,
1956
+ long long total, long long inner,
1957
+ long long idx_dim, long long x_dim,
1958
+ int* __restrict__ err) {
1959
+ const long long step = (long long)gridDim.x * blockDim.x;
1960
+ for (long long p = (long long)blockIdx.x * blockDim.x + threadIdx.x;
1961
+ p < total; p += step) {
1962
+ const long long i = p % inner;
1963
+ const long long t = p / inner;
1964
+ const long long o = t / idx_dim;
1965
+ long long v = (long long)idx[p];
1966
+ if (v < 0 || v >= x_dim) { *err = 1; continue; }
1967
+ %ATOMIC%(&dx[(o * x_dim + v) * inner + i], %LD%(dy[p]));
1968
+ }
1969
+ }
1970
+ """
1971
+ )
1972
+
1973
+ # cross_entropy: one block per row, two block-wide reductions (max, then
1974
+ # exp-sum). The softmax probabilities are never materialised: only the row
1975
+ # statistics and the single target logit are touched, which is the whole
1976
+ # point of fusing when V is 32k and there are B*T rows.
1977
+ # Shared scratch is REDUCE_SCRATCH (1024 floats), matching the block cap.
1978
+ _CROSS_ENTROPY_TMPL = (
1979
+ PRELUDE
1980
+ + r"""
1981
+ extern "C" __global__ void cross_entropy(const %T%* __restrict__ logits,
1982
+ const %IDS_T%* __restrict__ target,
1983
+ %T%* __restrict__ out,
1984
+ long long rows, long long vocab,
1985
+ int* __restrict__ err) {
1986
+ __shared__ float smem[1024];
1987
+ const long long row = (long long)blockIdx.x;
1988
+ if (row >= rows) { return; }
1989
+ const %T%* xr = logits + row * vocab;
1990
+ float m = -3.4e38f;
1991
+ for (long long j = threadIdx.x; j < vocab; j += blockDim.x) {
1992
+ const float v = %LD%(xr[j]);
1993
+ m = v > m ? v : m;
1994
+ }
1995
+ m = block_reduce_max(m, smem);
1996
+ float s = 0.f;
1997
+ for (long long j = threadIdx.x; j < vocab; j += blockDim.x) {
1998
+ s += expf(%LD%(xr[j]) - m);
1999
+ }
2000
+ s = block_reduce_sum(s, smem);
2001
+ if (threadIdx.x == 0) {
2002
+ long long t = (long long)target[row];
2003
+ if (t < 0 || t >= vocab) { *err = 1; t = 0; }
2004
+ out[row] = %ST%(m + logf(s) - %LD%(xr[t]));
2005
+ }
2006
+ }
2007
+ """
2008
+ )
2009
+
2010
+ # cross_entropy backward: (softmax - onehot) * dloss, computed row by row.
2011
+ # It re-derives the row statistics instead of caching probabilities from the
2012
+ # forward pass: caching would need a [rows, vocab] buffer, exactly the
2013
+ # materialisation the fused forward avoids.
2014
+ _CROSS_ENTROPY_BACKWARD_TMPL = (
2015
+ PRELUDE
2016
+ + r"""
2017
+ extern "C" __global__ void cross_entropy_backward(
2018
+ const %T%* __restrict__ logits,
2019
+ const %IDS_T%* __restrict__ target,
2020
+ const %T%* __restrict__ dloss,
2021
+ %T%* __restrict__ dlogits,
2022
+ long long rows, long long vocab,
2023
+ int* __restrict__ err) {
2024
+ __shared__ float smem[1024];
2025
+ const long long row = (long long)blockIdx.x;
2026
+ if (row >= rows) { return; }
2027
+ const %T%* xr = logits + row * vocab;
2028
+ %T%* dr = dlogits + row * vocab;
2029
+ float m = -3.4e38f;
2030
+ for (long long j = threadIdx.x; j < vocab; j += blockDim.x) {
2031
+ const float v = %LD%(xr[j]);
2032
+ m = v > m ? v : m;
2033
+ }
2034
+ m = block_reduce_max(m, smem);
2035
+ float s = 0.f;
2036
+ for (long long j = threadIdx.x; j < vocab; j += blockDim.x) {
2037
+ s += expf(%LD%(xr[j]) - m);
2038
+ }
2039
+ s = block_reduce_sum(s, smem);
2040
+ const float inv = 1.f / s;
2041
+ const float g = %LD%(dloss[row]);
2042
+ long long t = (long long)target[row];
2043
+ if (t < 0 || t >= vocab) { *err = 1; t = 0; }
2044
+ for (long long j = threadIdx.x; j < vocab; j += blockDim.x) {
2045
+ float p = expf(%LD%(xr[j]) - m) * inv;
2046
+ if (j == t) { p -= 1.f; }
2047
+ dr[j] = %ST%(p * g);
2048
+ }
2049
+ }
2050
+ """
2051
+ )
2052
+
2053
+
2054
+ # scan_linear: h_t = a_t * h_{t-1} + b_t, h_{-1} = h0.
2055
+ # One thread owns one tail element and walks the time axis in order. The
2056
+ # recurrence is inherently sequential, so the parallelism comes from the tail
2057
+ # (batch / channel / state), not from T; the tail is flattened, so any rank
2058
+ # >= 2 works without extra index math. A chunked (Blelloch) scan would need a
2059
+ # second pass and is left for a later round -- this kernel is the semantics,
2060
+ # not a bandwidth-optimal implementation.
2061
+ # NOTE: NVRTC requires ASCII source -- keep every comment in this file ASCII.
2062
+ SCAN_LINEAR_SRC = (
2063
+ PRELUDE
2064
+ + r"""
2065
+ extern "C" __global__ void scan_linear(const %T%* __restrict__ a,
2066
+ const %T%* __restrict__ b,
2067
+ const %T%* __restrict__ h0,
2068
+ %T%* __restrict__ out,
2069
+ long long steps, long long elems) {
2070
+ const long long stride = (long long)gridDim.x * blockDim.x;
2071
+ for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
2072
+ i < elems; i += stride) {
2073
+ float h = %LD%(h0[i]);
2074
+ for (long long t = 0; t < steps; ++t) {
2075
+ const long long idx = t * elems + i;
2076
+ h = %LD%(a[idx]) * h + %LD%(b[idx]);
2077
+ out[idx] = %ST%(h);
2078
+ }
2079
+ }
2080
+ }
2081
+ """
2082
+ )
2083
+
2084
+ # scan_linear_backward: dh_t = dy_t + a_{t+1} * dh_{t+1}, dh_T = 0.
2085
+ # Same owner-per-tail-element layout, walked backwards. a[idx + elems] is
2086
+ # a_{t+1}; the last step has no successor, so its carry is dropped.
2087
+ SCAN_LINEAR_BACKWARD_SRC = (
2088
+ PRELUDE
2089
+ + r"""
2090
+ extern "C" __global__ void scan_linear_backward(const %T%* __restrict__ a,
2091
+ const %T%* __restrict__ dy,
2092
+ %T%* __restrict__ out,
2093
+ long long steps, long long elems) {
2094
+ const long long stride = (long long)gridDim.x * blockDim.x;
2095
+ for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
2096
+ i < elems; i += stride) {
2097
+ float dh = 0.f;
2098
+ for (long long t = steps - 1; t >= 0; --t) {
2099
+ const long long idx = t * elems + i;
2100
+ const float carry = (t + 1 < steps) ? %LD%(a[idx + elems]) * dh : 0.f;
2101
+ dh = %LD%(dy[idx]) + carry;
2102
+ out[idx] = %ST%(dh);
2103
+ }
2104
+ }
2105
+ }
2106
+ """
2107
+ )
2108
+
2109
+
2110
+ # ids 的 numpy dtype -> CUDA C 类型。不能直接把 "int32" 填进源码:
2111
+ # CUDA C 没有这个类型名,NVRTC 会在编译期报 "identifier int32 is undefined"。
2112
+ _IDS_C_TYPE = {"int32": "int", "int8": "signed char"}
2113
+
2114
+
2115
+ def embedding_source(ids_dtype) -> str:
2116
+ """按 ids 的实际类型生成查表 kernel。
2117
+
2118
+ i32 与 i8 是两个真实的来源(前端导入的 token 既可能是 int32 索引,
2119
+ 也可能是 int8 压缩过的标签),所以按类型生成而不是在 kernel 里做
2120
+ 有符号扩展——后者在 NVRTC 下会把类型问题推迟成运行期的静默错值。
2121
+ """
2122
+ name = str(ids_dtype)
2123
+ if name not in _IDS_C_TYPE:
2124
+ raise ValueError(f"embedding 的 ids 只支持 int32/int8,收到 {ids_dtype}")
2125
+ return _EMBEDDING_TMPL.replace("%IDS_T%", _IDS_C_TYPE[name])
2126
+
2127
+
2128
+ def embedding_backward_source(ids_dtype) -> str:
2129
+ name = str(ids_dtype)
2130
+ if name not in _IDS_C_TYPE:
2131
+ raise ValueError(f"embedding_backward 的 ids 只支持 int32/int8,收到 {ids_dtype}")
2132
+ return _EMBEDDING_BACKWARD_TMPL.replace("%IDS_T%", _IDS_C_TYPE[name])
2133
+
2134
+
2135
+ def _ids_template(template: str, ids_dtype, op: str) -> str:
2136
+ """把 ``%IDS_T%`` 换成真实的 C 类型;只接受 IR 允许的两种下标类型。"""
2137
+ name = str(ids_dtype)
2138
+ if name not in _IDS_C_TYPE:
2139
+ raise ValueError(f"{op} 的 idx 只支持 int32/int8,收到 {ids_dtype}")
2140
+ return template.replace("%IDS_T%", _IDS_C_TYPE[name])
2141
+
2142
+
2143
+ def gather_source(ids_dtype) -> str:
2144
+ return _ids_template(_GATHER_TMPL, ids_dtype, "gather")
2145
+
2146
+
2147
+ def gather_backward_source(ids_dtype) -> str:
2148
+ return _ids_template(_GATHER_BACKWARD_TMPL, ids_dtype, "gather_backward")
2149
+
2150
+
2151
+ def cross_entropy_source(ids_dtype) -> str:
2152
+ return _ids_template(_CROSS_ENTROPY_TMPL, ids_dtype, "cross_entropy")
2153
+
2154
+
2155
+ def cross_entropy_backward_source(ids_dtype) -> str:
2156
+ return _ids_template(
2157
+ _CROSS_ENTROPY_BACKWARD_TMPL, ids_dtype, "cross_entropy_backward"
2158
+ )
2159
+
2160
+
2161
+ def binary_template(kind: str, scalar_a: bool = False, scalar_b: bool = False) -> str:
2162
+ """手写模板——**对照物**,不参与生产。
2163
+
2164
+ 5.42 之后生产路径走 ``binary_source`` 的 L2 描述;这里保留一份逐字等价的
2165
+ 手写版本,测试拿它当基准:L2 打印器一旦漂移,去空白后的 diff 就会失败。
2166
+ 等 L2 覆盖全部算子并稳定一轮,这份对照物可以删。
2167
+ """
2168
+ a_ref = "%LD%(a[0])" if scalar_a else "%LD%(a[i])"
2169
+ b_ref = "%LD%(b[0])" if scalar_b else "%LD%(b[i])"
2170
+ src = _BINARY_TMPL
2171
+ src = src.replace("%A_DECL%", "const %T%* __restrict__ a")
2172
+ src = src.replace("%B_DECL%", "const %T%* __restrict__ b")
2173
+ src = src.replace("%EXPR%", BINARY_FN[kind].format(a_ref, b_ref))
2174
+ return src
2175
+
2176
+
2177
+ def binary_source(kind: str, scalar_a: bool = False, scalar_b: bool = False) -> Kernel:
2178
+ """逐元素二元内核的 L2 描述(生产路径,5.42)。
2179
+
2180
+ ``scalar_a`` / ``scalar_b`` 表示对应侧按标量处理(用于 (1,) 广播)。
2181
+ 这不是"优化",是语义需要:Transformer 里的 ``x * scale`` 就是标量广播。
2182
+
2183
+ 标量一侧仍然收**设备指针**(kernel 内取 ``a[0]``),而不是主机 float:
2184
+ 传主机 float 需要先 ``float(array)`` 把值拷回 CPU,那是一次强制同步,
2185
+ 既拖慢每次 execute,也让整张图无法被 CUDA Graph 捕获。
2186
+ """
2187
+ return ew_binary(kind, scalar_a=scalar_a, scalar_b=scalar_b)
2188
+
2189
+
2190
+ def reduce_sum_source() -> Kernel:
2191
+ """末维求和的 L2 描述(生产路径,5.42)。"""
2192
+ return reduce_sum_last()
2193
+
2194
+
2195
+ def reduce_sum_rows_source() -> Kernel:
2196
+ """窄末维求和的 L2 描述:一个 block 打包多行(每行一个 warp 宽)。
2197
+
2198
+ 只在 ``cols <= 32`` 时启用(见 ``device_reduce._reduce_last_dim``):
2199
+ 这种形状下行数往往上百万,"一 block 一行"的调度开销远大于算术。
2200
+ """
2201
+ return reduce_sum_rows()
2202
+
2203
+
2204
+ def reduce_max_source() -> Kernel:
2205
+ """末维最大值的 L2 描述(生产路径)。"""
2206
+ return reduce_max_last()
2207
+
2208
+
2209
+ def reduce_mean_source() -> Kernel:
2210
+ """末维均值的 L2 描述(生产路径)。"""
2211
+ return reduce_mean_last()
2212
+
2213
+
2214
+ def reduce_any_source() -> Kernel:
2215
+ """末维逻辑或的 L2 描述:bool 输入,求和后判非零(5.341)。
2216
+
2217
+ 输出也是 bool,写回由 ``af_st_q`` 归一成 0/1——``render`` 按 dtype 自动
2218
+ 选 1 字节容器的方言,调用点只需要把 bool 张量传进来。
2219
+ """
2220
+ return reduce_any_last()
2221
+
2222
+
2223
+ def reduce_all_source() -> Kernel:
2224
+ """末维逻辑与的 L2 描述:bool 输入,和等于列数才算全真(5.341)。"""
2225
+ return reduce_all_last()
2226
+
2227
+
2228
+ def reduce_axis_source(kind: str, pred: str | None = None) -> Kernel:
2229
+ """非末维单轴归约的 L2 描述:一个线程一个输出元素(5.153)。
2230
+
2231
+ ``kind`` 取 ``sum`` / ``max`` / ``min`` / ``mean``,四者的内核骨架相同,
2232
+ 只有初值、合并方式与是否除以长度不同。``pred`` 是 bool 归约的判定方式
2233
+ (``any`` / ``all``,见 5.341),与 ``reduce_any_source`` 同一口径。
2234
+ """
2235
+ return reduce_axis(kind, pred)
2236
+
2237
+
2238
+ def reduce_axis_tiled_source(kind: str, pred: str | None = None) -> Kernel:
2239
+ """非末维归约的两维铺法:x 沿 inner、y 切 reduce 轴(5.174)。"""
2240
+ return reduce_axis_tiled(kind, pred)
2241
+
2242
+
2243
+ def softmax_axis_source() -> Kernel:
2244
+ """非末维 softmax 的 L2 描述:一个线程一行,三遍扫描(5.153)。"""
2245
+ return softmax_axis()
2246
+
2247
+
2248
+ def argmax_source() -> Kernel:
2249
+ """末维 argmax 的 L2 描述(生产路径)。
2250
+
2251
+ 输出参数是 ``int*``(i32),不随输入 dtype 变化——下标不是浮点激活值。
2252
+ """
2253
+ return argmax_last()
2254
+
2255
+
2256
+ def argmin_source() -> Kernel:
2257
+ """末维 argmin 的 L2 描述(生产路径,5.349)。
2258
+
2259
+ 与 ``argmax_source`` 同构,只换比较方向;并列同样取第一次出现。
2260
+ """
2261
+ return argmin_last()
2262
+
2263
+
2264
+ def logsumexp_source() -> Kernel:
2265
+ """任意单轴 logsumexp 的 L2 描述(5.349)。
2266
+
2267
+ 铺法与 ``softmax_axis`` 相同(一个线程扫完一行),输出比输入少一维,
2268
+ 每行一个标量。
2269
+ """
2270
+ return logsumexp_axis()
2271
+
2272
+
2273
+ def topk_source() -> str:
2274
+ """末维 topk 的手写内核源码(values / indices / mask 三个入口共用)。
2275
+
2276
+ 没有做成 L2 描述:每轮需要一段运行期长度(``k``)的动态共享内存,
2277
+ 而 L2 的 ``Shared`` 只能声明静态大小。选择规则与 ``argmax_last`` 一致
2278
+ (最大值、并列取小下标),NaN 按 +inf 参与比较。
2279
+ """
2280
+ return TOPK_SRC
2281
+
2282
+
2283
+ def broadcast_binary_source(kind: str) -> Kernel:
2284
+ """支持 numpy 多维广播的逐元素二元内核的 L2 描述(生产路径)。
2285
+
2286
+ 广播通过"对齐后的 stride"实现:被广播的维度 stride 置 0,
2287
+ 于是同一份输入元素会被多个输出位置复用。维度上限 4,
2288
+ 超过时由后端拒绝(而不是悄悄换实现)。
2289
+
2290
+ ``pow2`` 的掩码/右移变体已删除:V100 上实测反而更慢,理由见
2291
+ ``ew_broadcast`` 与 DESIGN 5.300。
2292
+ """
2293
+ return ew_broadcast(kind)
2294
+
2295
+
2296
+ def compare_source(
2297
+ kind: str,
2298
+ *,
2299
+ scalar_a: bool = False,
2300
+ scalar_b: bool = False,
2301
+ broadcast: bool = False,
2302
+ dtype=None,
2303
+ dialect=None,
2304
+ ) -> str:
2305
+ """比较内核源码:输出容器固定是 1 字节 bool。
2306
+
2307
+ ``broadcast`` 为假表示两侧同形(扁平网格),为真表示走多维广播版。
2308
+ ``dtype`` 是**输入**的存储类型:参数声明、读取 helper
2309
+ 与 prelude 都由它决定,输出则钉死成 bool 并裸写(比较结果本身就是 0/1)。
2310
+ bool 输入(``ne(mask, 0)``)需要 1 字节容器的方言,因此单独走
2311
+ ``BOOL_DIALECT``。
2312
+ """
2313
+ if not broadcast:
2314
+ template = ew_binary(kind, scalar_a=scalar_a, scalar_b=scalar_b, compare=True)
2315
+ else:
2316
+ template = ew_broadcast(kind, compare=True)
2317
+ ir_dtype = _ir_dtype(np.dtype("float32") if dtype is None else dtype)
2318
+ if dialect is None:
2319
+ if ir_dtype is DType.BOOL:
2320
+ from .dialect import BOOL_DIALECT
2321
+
2322
+ dialect = BOOL_DIALECT
2323
+ else:
2324
+ from .dialect import CUDA_DIALECT
2325
+
2326
+ dialect = CUDA_DIALECT
2327
+ return emit(template, dialect, ir_dtype)
2328
+
2329
+
2330
+ def where_source(*, broadcast: bool = False, dtype=None, dialect=None) -> str:
2331
+ """``where(cond, a, b)`` 源码。
2332
+
2333
+ ``broadcast`` 为假表示三者同形(扁平网格),为真表示三输入广播版。``dtype``
2334
+ 是 a / b 的存储类型,**输出跟随它**:浮点时正常走 ``af_st_*``;两侧本身
2335
+ 就是 bool(掩码之间选择)时输出也是 1 字节,此时裸写并换用
2336
+ ``BOOL_DIALECT``。``cond`` 无论如何都是 1 字节 bool,裸索引读取。
2337
+ """
2338
+ ir_dtype = _ir_dtype(np.dtype("float32") if dtype is None else dtype)
2339
+ is_bool = ir_dtype is DType.BOOL
2340
+ if not broadcast:
2341
+ template = ew_where_same(raw_store=is_bool)
2342
+ else:
2343
+ template = ew_where_bcast(raw_store=is_bool)
2344
+ if dialect is None:
2345
+ if is_bool:
2346
+ from .dialect import BOOL_DIALECT
2347
+
2348
+ dialect = BOOL_DIALECT
2349
+ else:
2350
+ from .dialect import CUDA_DIALECT
2351
+
2352
+ dialect = CUDA_DIALECT
2353
+ return emit(template, dialect, ir_dtype)
2354
+
2355
+
2356
+ def broadcast_template(kind: str) -> str:
2357
+ """手写模板——对照物,不参与生产(同 ``binary_template``)。"""
2358
+ return _BCAST_TMPL.replace(
2359
+ "%EXPR%", BINARY_FN[kind].format("%LD%(a[oa])", "%LD%(b[ob])")
2360
+ )
2361
+
2362
+
2363
+ def unary_source(kind: str) -> Kernel:
2364
+ """逐元素一元内核的 L2 描述(生产路径)。"""
2365
+ return ew_unary(kind)
2366
+
2367
+
2368
+ def cast_fn(src, dst, dialect=None) -> str:
2369
+ """跨存储宽度的转换源码(f32 / f16 / bf16 三者任意方向)。
2370
+
2371
+ 这是唯一一个"两侧类型不一致"的内核:读取按**源** dtype 渲染(决定用
2372
+ ``af_ld_f`` / ``af_ld_h`` / ``af_ld_b``),写回的目标类型由张量参数自己
2373
+ 声明。方言换成 ``CAST_DIALECT``,让它同时带上三套存取 helper。HIP 侧传入
2374
+ 自己的一份(f16 的 helper 换成 clang 版),L2 描述与其余逻辑逐字共用。
2375
+ """
2376
+ if dialect is None:
2377
+ from .dialect import CAST_DIALECT as dialect
2378
+
2379
+ src_key, dst_key = _dtype_key(src), _dtype_key(dst)
2380
+ if src_key == dst_key:
2381
+ raise ValueError(f"cast_fn 只处理跨宽度转换,收到 {src_key} -> {dst_key}")
2382
+ out_type = _STORAGE[dst_key][0]
2383
+ # f32 是恒等 store,裸赋值即可;窄类型必须走各自的 RNE store helper。
2384
+ out_store = None if dst_key == "f32" else _STORAGE[dst_key][2]
2385
+ return emit(ew_cast(out_type, out_store), dialect, _ir_dtype(src))
2386
+
2387
+
2388
+ def unary_template(kind: str) -> str:
2389
+ """手写模板——对照物,不参与生产。"""
2390
+ return _UNARY_TMPL.replace("%EXPR%", UNARY_EXPR[kind])
2391
+
2392
+
2393
+ def step_source() -> Kernel:
2394
+ """阶跃内核的 L2 描述(生产路径)。"""
2395
+ return ew_step()
2396
+
2397
+
2398
+ def step_template() -> str:
2399
+ """手写模板——对照物,不参与生产。"""
2400
+ return STEP_SRC
2401
+
2402
+
2403
+ def clamp_source() -> Kernel:
2404
+ """按标量上下界截断的 L2 描述(生产路径)。"""
2405
+ return ew_clamp()
2406
+
2407
+
2408
+ def mod_source(*, scalar_a: bool = False, scalar_b: bool = False) -> Kernel:
2409
+ """i32 floor 取模的 L2 描述(生产路径)。
2410
+
2411
+ 整数参数在 L2 里用 ``type_name="int"`` 钉死,不跟随渲染 dtype;调用方
2412
+ 传 f32 只是为了拿到方言 prelude(见 ``ew_mod_int`` 的说明)。
2413
+ """
2414
+ return ew_mod_int(scalar_a=scalar_a, scalar_b=scalar_b)
2415
+
2416
+
2417
+ def softmax_source(cache: int = 0) -> Kernel:
2418
+ """末维 softmax 的 L2 描述(生产路径)。
2419
+
2420
+ ``cache`` 非 0 时整行只读一遍显存(见 ``reduce.softmax_last``)。
2421
+ """
2422
+ return softmax_last(cache)
2423
+
2424
+
2425
+ def softmax_template() -> str:
2426
+ """手写模板——对照物,不参与生产。"""
2427
+ return SOFTMAX_SRC
2428
+
2429
+
2430
+ def layernorm_source(cache: int = 0) -> Kernel:
2431
+ """末维 LayerNorm 的 L2 描述(生产路径)。
2432
+
2433
+ ``cache`` 是每线程缓存的元素数,非 0 时整行只读一遍显存(见
2434
+ ``norm.layernorm_last``)。
2435
+ """
2436
+ return layernorm_last(cache)
2437
+
2438
+
2439
+ def layernorm_template() -> str:
2440
+ """手写模板——对照物,不参与生产。"""
2441
+ return LAYERNORM_SRC
2442
+
2443
+
2444
+ def layernorm_residual_source(cache: int = 0) -> Kernel:
2445
+ """融合残差的末维 LayerNorm 的 L2 描述(生产路径)。
2446
+
2447
+ ``cache`` 非 0 时整行只读一遍显存(见 ``norm.layernorm_residual_last``)。
2448
+ """
2449
+ return layernorm_residual_last(cache)
2450
+
2451
+
2452
+ def layernorm_residual_template() -> str:
2453
+ """手写模板——对照物,不参与生产。"""
2454
+ return LAYERNORM_RESIDUAL_SRC
2455
+
2456
+
2457
+ def rmsnorm_source(cache: int = 0) -> Kernel:
2458
+ """末维 RMSNorm 的 L2 描述(生产路径)。
2459
+
2460
+ ``cache`` 非 0 时整行只读一遍显存(见 ``norm.rmsnorm_last``)。
2461
+ """
2462
+ return rmsnorm_last(cache)
2463
+
2464
+
2465
+ def rmsnorm_template() -> str:
2466
+ """手写模板——对照物,不参与生产。"""
2467
+ return RMSNORM_SRC
2468
+
2469
+
2470
+ def silu_gate_source() -> Kernel:
2471
+ """门控 SiLU 的 L2 描述(生产路径)。"""
2472
+ return silu_gate()
2473
+
2474
+
2475
+ def silu_gate_template() -> str:
2476
+ """手写模板——对照物,不参与生产。"""
2477
+ return SILU_GATE_SRC
2478
+
2479
+
2480
+ def rope_source() -> Kernel:
2481
+ """旋转位置编码的 L2 描述(生产路径)。"""
2482
+ return rope_apply()
2483
+
2484
+
2485
+ def rope_template() -> str:
2486
+ """手写模板——对照物,不参与生产。"""
2487
+ return ROPE_SRC
2488
+
2489
+
2490
+ def batch_norm_source() -> Kernel:
2491
+ """训练态批归一化的 L2 描述(生产路径)。"""
2492
+ return batch_norm()
2493
+
2494
+
2495
+ def batch_norm_stats_source() -> Kernel:
2496
+ """批归一化统计量的 L2 描述(生产路径)。"""
2497
+ return batch_norm_stats()
2498
+
2499
+
2500
+ def batch_norm_template() -> str:
2501
+ """手写模板——对照物,不参与生产。
2502
+
2503
+ 这一份字符串里有 ``batch_norm`` 与 ``batch_norm_stats`` 两个内核(原先
2504
+ 一起交给 NVRTC 编译),拆成两个 ``Kernel`` 后对照时按名字截取。
2505
+ """
2506
+ return BATCH_NORM_SRC
2507
+
2508
+
2509
+ def concat_copy_source() -> Kernel:
2510
+ """拼接 / 补零的分段拷贝的 L2 描述(生产路径)。"""
2511
+ return concat_copy()
2512
+
2513
+
2514
+ def concat_copy_template() -> str:
2515
+ """手写模板——对照物,不参与生产。"""
2516
+ return CONCAT_COPY_SRC
2517
+
2518
+
2519
+ def dropout_mask_source() -> Kernel:
2520
+ """缩放 dropout 掩码的 L2 描述(生产路径)。"""
2521
+ return dropout_mask()
2522
+
2523
+
2524
+ def sparse_linear_source() -> Kernel:
2525
+ """事件驱动稀疏线性的 L2 描述(生产路径)。
2526
+
2527
+ 没有手写模板对照物:内核只做一次 CSR 段内的加权求和,形状与语义都
2528
+ 足够简单,再抄一份 C 只会多一处会漂移的事实。
2529
+ """
2530
+ return sparse_linear()
2531
+
2532
+
2533
+ def spike_offsets_source() -> Kernel:
2534
+ """脉冲压缩第一趟(统计每行非零数并写起点表)的 L2 描述。"""
2535
+ return spike_offsets()
2536
+
2537
+
2538
+ def spike_csr_source() -> Kernel:
2539
+ """脉冲压缩第二趟(按起点表写列号)的 L2 描述。"""
2540
+ return spike_csr()
2541
+
2542
+
2543
+ def spike_csr_serial_source() -> Kernel:
2544
+ """同一趟的旧铺法:一个线程一行、沿列号串行(仅 5.176 的基准对照)。"""
2545
+ return spike_csr_serial()
2546
+
2547
+
2548
+ def sparse_linear_weight_grad_source() -> Kernel:
2549
+ """事件驱动稀疏线性对权重梯度的 L2 描述(生产路径)。"""
2550
+ return sparse_linear_weight_grad()
2551
+
2552
+
2553
+ def sparse_linear_values_grad_source() -> Kernel:
2554
+ """事件驱动稀疏线性对事件幅度梯度的 L2 描述(生产路径)。
2555
+
2556
+ 与权重梯度相反,这里按步并行、逐事件算点积,不需要原子加——事件之间
2557
+ 不存在重复下标。没有手写模板对照物:骨架就是"一段事件 + 一段列号",
2558
+ 与 ``sparse_linear`` 的前向同形。
2559
+ """
2560
+ return sparse_linear_values_grad()
2561
+
2562
+
2563
+ def spike_linear_source() -> Kernel:
2564
+ """融合事件线性(脉冲值直接从 CSR 结构读)的 L2 描述(生产路径)。
2565
+
2566
+ 没有手写模板对照物:它与 ``sparse_linear`` 共用同一套逐事件累加骨架,
2567
+ 差别只在事件幅度取自脉冲矩阵本身。
2568
+ """
2569
+ return spike_linear()
2570
+
2571
+
2572
+ def spike_linear_weight_grad_source() -> Kernel:
2573
+ """融合事件线性对权重梯度的 L2 描述(生产路径)。"""
2574
+ return spike_linear_weight_grad()
2575
+
2576
+
2577
+ def dropout_mask_template() -> str:
2578
+ """手写模板——对照物,不参与生产。"""
2579
+ return DROPOUT_MASK_SRC
2580
+
2581
+
2582
+ def dropout_mask_keyed_template() -> str:
2583
+ """运行期 key 版的手写模板(捕获后仍能推进掩码)。"""
2584
+ return DROPOUT_MASK_KEYED_SRC
2585
+
2586
+
2587
+ def scan_linear_source() -> Kernel:
2588
+ """线性递推的 L2 描述(生产路径)。"""
2589
+ return scan_linear()
2590
+
2591
+
2592
+ def scan_linear_template() -> str:
2593
+ """手写模板——对照物,不参与生产。"""
2594
+ return SCAN_LINEAR_SRC
2595
+
2596
+
2597
+ def scan_linear_backward_source() -> Kernel:
2598
+ """线性递推反向的 L2 描述(生产路径)。"""
2599
+ return scan_linear_backward()
2600
+
2601
+
2602
+ def scan_linear_backward_template() -> str:
2603
+ """手写模板——对照物,不参与生产。"""
2604
+ return SCAN_LINEAR_BACKWARD_SRC
2605
+
2606
+
2607
+ def scan_linear_chunk_sum_source() -> Kernel:
2608
+ """分块扫描第一趟(块内复合)的 L2 描述。
2609
+
2610
+ 这些内核没有手写对照模板:它们不是 ``scan_linear`` 的逐字等价物
2611
+ (块间前缀的舍入路径不同),"逐 token 相等"的判据在这里不成立。
2612
+ 验收方式是数值对拍与开关默认关闭时逐位不变。
2613
+ """
2614
+ return scan_linear_chunk_sum()
2615
+
2616
+
2617
+ def scan_linear_chunk_source() -> Kernel:
2618
+ """分块扫描第二趟(块前缀 + 块内读出)的 L2 描述。"""
2619
+ return scan_linear_chunk()
2620
+
2621
+
2622
+ def scan_linear_chunk_sum_backward_source() -> Kernel:
2623
+ """分块反向第一趟的 L2 描述。"""
2624
+ return scan_linear_chunk_sum_backward()
2625
+
2626
+
2627
+ def scan_linear_chunk_backward_source() -> Kernel:
2628
+ """分块反向第二趟的 L2 描述。"""
2629
+ return scan_linear_chunk_backward()
2630
+
2631
+
2632
+ def scan_linear_last_source() -> Kernel:
2633
+ """只写末状态的 L2 描述。"""
2634
+ return scan_linear_last()
2635
+
2636
+
2637
+ def scan_linear_chunk_last_source() -> Kernel:
2638
+ """分块末状态的 L2 描述。"""
2639
+ return scan_linear_chunk_last()
2640
+
2641
+
2642
+ def cumsum_source() -> Kernel:
2643
+ """前缀和的 L2 描述(生产路径)。
2644
+
2645
+ 没有手写模板对照物:它与 ``scan_linear`` 的铺法同构(一个线程一个尾元素
2646
+ 沿时间轴走),差别只在没有 ``a_t`` 乘法,抄一份模板只会多一处漂移点。
2647
+ """
2648
+ return cumsum()
2649
+
2650
+
2651
+ def cumprod_source() -> Kernel:
2652
+ """前缀积的 L2 描述(5.349)。
2653
+
2654
+ 与 ``cumsum_source`` 同一份铺法,只有累加器换成累乘、初值换成 1。
2655
+ """
2656
+ return cumprod()
2657
+
2658
+
2659
+ def flip_source() -> Kernel:
2660
+ """单轴反转的 L2 描述(5.349):一个线程搬一个元素。"""
2661
+ return flip()
2662
+
2663
+
2664
+ def roll_source() -> Kernel:
2665
+ """单轴循环移位的 L2 描述(5.349):一个线程搬一个元素,``shift`` 由 host 归一化。"""
2666
+ return roll()
2667
+
2668
+
2669
+ def repeat_interleave_source() -> Kernel:
2670
+ """单轴逐元素重复的 L2 描述(5.350):输出轴长是输入的 ``repeats`` 倍。"""
2671
+ return repeat_interleave()
2672
+
2673
+
2674
+ def tril_source() -> Kernel:
2675
+ """下三角掩码的 L2 描述(生产路径)。
2676
+
2677
+ 没有手写模板对照物:单趟逐元素写回,结构由 ``grid_stride`` 定死。
2678
+ """
2679
+ return tril()
2680
+
2681
+
2682
+ def conv2d_input_grad_source() -> Kernel:
2683
+ """卷积输入梯度的 L2 描述(生产路径)。"""
2684
+ return conv2d_input_grad()
2685
+
2686
+
2687
+ def conv2d_input_grad_template() -> str:
2688
+ """手写模板——对照物,不参与生产。"""
2689
+ return CONV2D_INPUT_GRAD_SRC
2690
+
2691
+
2692
+ def conv2d_weight_grad_source() -> Kernel:
2693
+ """卷积权重梯度的 L2 描述(生产路径)。"""
2694
+ return conv2d_weight_grad()
2695
+
2696
+
2697
+ def conv2d_weight_grad_template() -> str:
2698
+ """手写模板——对照物,不参与生产。"""
2699
+ return CONV2D_WEIGHT_GRAD_SRC
2700
+
2701
+
2702
+ def maxpool2d_source(layout: str = "nchw") -> Kernel:
2703
+ """2D 最大池化的 L2 描述(生产路径)。"""
2704
+ return maxpool2d(layout=layout)
2705
+
2706
+
2707
+ def maxpool2d_template() -> str:
2708
+ """手写模板——对照物,不参与生产。"""
2709
+ return MAXPOOL2D_SRC
2710
+
2711
+
2712
+ def maxpool2d_backward_source() -> Kernel:
2713
+ """2D 最大池化反向的 L2 描述(生产路径)。"""
2714
+ return maxpool2d_backward()
2715
+
2716
+
2717
+ def maxpool2d_indices_source() -> Kernel:
2718
+ """2D 最大池化取值位置的 L2 描述(i32 平面内下标,生产路径)。"""
2719
+ return maxpool2d_indices()
2720
+
2721
+
2722
+ def maxpool2d_backward_template() -> str:
2723
+ """手写模板——对照物,不参与生产。"""
2724
+ return MAXPOOL2D_BACKWARD_SRC
2725
+
2726
+
2727
+ def maxpool2d_indices_template() -> str:
2728
+ """手写模板——对照物,不参与生产。"""
2729
+ return MAXPOOL2D_INDICES_SRC
2730
+
2731
+
2732
+ def avgpool2d_source(layout: str = "nchw") -> Kernel:
2733
+ """2D 平均池化的 L2 描述(生产路径)。"""
2734
+ return avgpool2d(layout=layout)
2735
+
2736
+
2737
+ def avgpool2d_template() -> str:
2738
+ """手写模板——对照物,不参与生产。"""
2739
+ return AVGPOOL2D_SRC
2740
+
2741
+
2742
+ def avgpool2d_backward_source() -> Kernel:
2743
+ """2D 平均池化反向的 L2 描述(生产路径)。"""
2744
+ return avgpool2d_backward()
2745
+
2746
+
2747
+ def avgpool2d_backward_template() -> str:
2748
+ """手写模板——对照物,不参与生产。"""
2749
+ return AVGPOOL2D_BACKWARD_SRC
2750
+
2751
+
2752
+ def adaptive_avg_pool2d_source() -> Kernel:
2753
+ """自适应平均池化的 L2 描述(生产路径)。"""
2754
+ return adaptive_avg_pool2d()
2755
+
2756
+
2757
+ def adaptive_avg_pool2d_template() -> str:
2758
+ """手写模板——对照物,不参与生产。"""
2759
+ return ADAPTIVE_AVGPOOL2D_SRC
2760
+
2761
+
2762
+ def adaptive_avg_pool2d_backward_source() -> Kernel:
2763
+ """自适应平均池化反向的 L2 描述(生产路径)。"""
2764
+ return adaptive_avg_pool2d_backward()
2765
+
2766
+
2767
+ def adaptive_avg_pool2d_backward_template() -> str:
2768
+ """手写模板——对照物,不参与生产。"""
2769
+ return ADAPTIVE_AVGPOOL2D_BACKWARD_SRC
2770
+
2771
+
2772
+ def interpolate_nearest_source() -> Kernel:
2773
+ """最近邻插值的 L2 描述(生产路径)。"""
2774
+ return interpolate_nearest()
2775
+
2776
+
2777
+ def interpolate_bilinear_source(align_corners: bool = False) -> Kernel:
2778
+ """双线性插值的 L2 描述(生产路径);``align_corners`` 决定坐标公式。"""
2779
+ return interpolate_bilinear(align_corners=align_corners)
2780
+
2781
+
2782
+ def interpolate_nearest_backward_source() -> Kernel:
2783
+ """最近邻插值反向的 L2 描述(生产路径)。"""
2784
+ return interpolate_nearest_backward()
2785
+
2786
+
2787
+ def interpolate_bilinear_backward_source(align_corners: bool = False) -> Kernel:
2788
+ """双线性插值反向的 L2 描述(生产路径)。"""
2789
+ return interpolate_bilinear_backward(align_corners=align_corners)
2790
+
2791
+
2792
+ def im2col_source() -> Kernel:
2793
+ """卷积展开的 L2 描述(生产路径)。"""
2794
+ return im2col()
2795
+
2796
+
2797
+ def im2col_template() -> str:
2798
+ """手写模板——对照物,不参与生产。"""
2799
+ return IM2COL_SRC
2800
+
2801
+
2802
+ def conv2d_tiled_source(layout: str = "nchw") -> Kernel:
2803
+ """直接分块卷积的 L2 描述(生产路径)。
2804
+
2805
+ 这个内核不做 dtype 参数化(全程 ``float``),模板里的 ``%T%`` 从未出现,
2806
+ 因此两种 dtype 打印出的源码相同。``layout="nhwc"`` 只改寻址公式
2807
+ (通道在末维,见 5.334),分块几何与累加顺序不变。
2808
+ """
2809
+ return conv2d_tiled(layout=layout)
2810
+
2811
+
2812
+ def conv2d_tiled_template() -> str:
2813
+ """手写模板——对照物,不参与生产。"""
2814
+ return CONV2D_TILED_SRC
2815
+
2816
+
2817
+ def conv2d_grouped_source() -> Kernel:
2818
+ """分组 / depthwise 卷积的 L2 描述(生产路径,5.165)。
2819
+
2820
+ 与分块核、隐式核一样不做 dtype 参数化:全程 ``float``,f16 走 im2col。
2821
+ """
2822
+ return conv2d_grouped()
2823
+
2824
+
2825
+ def conv2d_implicit_source() -> Kernel:
2826
+ """隐式 GEMM 卷积的 L2 描述:输入窗口也进 shared。
2827
+
2828
+ 与 :func:`conv2d_tiled_source` 一样不做 dtype 参数化,模板里的 ``%T%``
2829
+ 不出现,两种 dtype 打印出的源码相同。
2830
+ """
2831
+ return conv2d_implicit()
2832
+
2833
+
2834
+ def winograd_weight_source() -> Kernel:
2835
+ """Winograd F(2x2,3x3) 的权重变换 ``U = G g G^T``(生产路径)。
2836
+
2837
+ 三个 Winograd 内核都只做 f32:变换的中间量(``1/2`` 缩放后的和)没有
2838
+ 对应的 f16 写法,且 f16 卷积已经走 im2col + hgemm。
2839
+ """
2840
+ return winograd_weight_transform()
2841
+
2842
+
2843
+ def winograd_input_source() -> Kernel:
2844
+ """Winograd F(2x2,3x3) 的输入变换 ``V = B^T d B``(生产路径)。"""
2845
+ return winograd_input_transform()
2846
+
2847
+
2848
+ def winograd_output_source(epilogue=None, extra=()) -> Kernel:
2849
+ """Winograd F(2x2,3x3) 的输出变换 ``Y = A^T M A`` + bias(生产路径)。
2850
+
2851
+ ``epilogue`` 非空时把后继逐元素链(BN / 激活)内联进写回点:``Y`` 不再
2852
+ 落一次全局内存再被链读回来。默认 ``None`` 生成的源码逐字不变。
2853
+ """
2854
+ return winograd_output_transform(epilogue=epilogue, extra=extra)
2855
+
2856
+
2857
+ def winograd_fused_source(epilogue=None, extra=()) -> Kernel:
2858
+ """融合版 Winograd:输入变换 + 乘加 + 输出变换,一次 launch。
2859
+
2860
+ 与上面三个内核只差"在哪算":``V`` 不进全局缓冲而是留在共享内存,
2861
+ ``M`` 不进全局缓冲而是留在寄存器。数值与四段版逐位一致(同一组
2862
+ ``B`` / ``A`` / ``G`` 系数、同样的求和顺序)。
2863
+ """
2864
+ return winograd_fused(epilogue=epilogue, extra=extra)
2865
+
2866
+
2867
+ def attention_source() -> Kernel:
2868
+ """融合注意力前向的 L2 描述(生产路径)。"""
2869
+ return attention_fwd()
2870
+
2871
+
2872
+ def attention_template() -> str:
2873
+ """手写模板——对照物,不参与生产。"""
2874
+ return ATTENTION_SRC