flashdiffusion 0.1.0__tar.gz → 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/PKG-INFO +1 -1
  2. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/pyproject.toml +4 -1
  3. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/__init__.py +7 -4
  4. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm120.cu +328 -0
  5. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm120X.cu +312 -0
  6. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm120_.cu +204 -0
  7. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm80.cu +324 -0
  8. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm80X.cu +293 -0
  9. flashdiffusion-0.1.2/src/flashdiffusion/csrc/flash_diffusion_sm80_.cu +238 -0
  10. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/kernel_cuda.py +11 -9
  11. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/kernel_cuda_sm120.py +12 -10
  12. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/kernel_jit.py +58 -23
  13. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion.egg-info/PKG-INFO +1 -1
  14. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion.egg-info/SOURCES.txt +6 -0
  15. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/LICENSE +0 -0
  16. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/README.md +0 -0
  17. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/setup.cfg +0 -0
  18. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/setup.py +0 -0
  19. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/ROPE.py +0 -0
  20. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/cdc.py +0 -0
  21. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/dmap.py +0 -0
  22. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/eigensolver.py +0 -0
  23. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/eigensolver_gpu.py +0 -0
  24. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/kernel.py +0 -0
  25. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion/utils.py +0 -0
  26. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion.egg-info/dependency_links.txt +0 -0
  27. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion.egg-info/requires.txt +0 -0
  28. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/src/flashdiffusion.egg-info/top_level.txt +0 -0
  29. {flashdiffusion-0.1.0 → flashdiffusion-0.1.2}/tests/test_kernel.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flashdiffusion
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: GPU-accelerated diffusion maps with tensor core kernels
5
5
  Author: Julio Candanedo
6
6
  Author-email: Julio Candanedo <julio@sparsetrace.ai>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "flashdiffusion"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "GPU-accelerated diffusion maps with tensor core kernels"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -28,3 +28,6 @@ Homepage = "https://github.com/sparsetrace/FlashDiffusion"
28
28
 
29
29
  [tool.setuptools.packages.find]
30
30
  where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ flashdiffusion = ["csrc/*.cu", "csrc/*.cuh"]
@@ -1,11 +1,14 @@
1
1
  # src/flashdiffusion/__init__.py
2
2
 
3
3
  import sys, os
4
+
5
+ # ensure src/ is on path for editable installs
4
6
  _src = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5
7
  if _src not in sys.path:
6
8
  sys.path.insert(0, _src)
7
9
 
8
- import os, torch
10
+ import torch
11
+
9
12
  def _jit_init():
10
13
  """On first import: detect GPU, JIT-build kernel, inject into sys.modules."""
11
14
  if not torch.cuda.is_available():
@@ -13,12 +16,12 @@ def _jit_init():
13
16
  major, minor = torch.cuda.get_device_capability()
14
17
  sm = major * 10 + minor
15
18
 
16
- repo_root = os.path.dirname(os.path.dirname(os.path.dirname(
17
- os.path.abspath(__file__)))) # src/flashdiffusion → repo root
19
+ # package_dir = .../flashdiffusion/ (works for both pip and editable)
20
+ package_dir = os.path.dirname(os.path.abspath(__file__))
18
21
 
19
22
  from .kernel_jit import _build_kernel
20
23
  try:
21
- _build_kernel(sm, repo_root)
24
+ _build_kernel(sm, package_dir)
22
25
  except Exception as e:
23
26
  print(f'[FlashDiffusion] JIT build failed ({e}), CPU fallback only')
24
27
 
@@ -0,0 +1,328 @@
1
+ /*
2
+ * flash_diffusion_sm120.cu — SM120 WMMA v2
3
+ * ==========================================
4
+ * SM120 (RTX 5090 / RTX PRO 6000 Blackwell consumer) WMMA kernel.
5
+ *
6
+ * v2 over v1:
7
+ * Fixed SMEM size via k-chunking — supports arbitrary d (including d=784).
8
+ * v1 allocated BM×d SMEM which exceeded 99KB limit for d>~350.
9
+ *
10
+ * SMEM layout (fixed, independent of d):
11
+ * sA = BM × KCHUNK × 2 = 128 × 32 × 2 = 8,192 bytes
12
+ * sB = BN × KCHUNK × 2 = 128 × 32 × 2 = 8,192 bytes
13
+ * sDot = BM × BN × 4 = 128 × 128 × 4 = 65,536 bytes
14
+ * Total = 81,920 bytes = 80KB ✓ (SM120 limit: 99KB)
15
+ *
16
+ * K-chunking: outer loop over d in steps of KCHUNK=32.
17
+ * Each chunk loads sA/sB (BM×32) and (BN×32), runs 2 WMMA calls per warp,
18
+ * accumulates into sDot with fill_fragment(fc, 0) only on first chunk.
19
+ *
20
+ * Build:
21
+ * -arch=sm_120 -std=c++17 -O3 --use_fast_math
22
+ * -U__CUDA_NO_HALF_OPERATORS__ -U__CUDA_NO_HALF_CONVERSIONS__
23
+ * --expt-relaxed-constexpr
24
+ */
25
+
26
+ #include <cuda.h>
27
+ #include <cuda_runtime.h>
28
+ #include <cuda_fp16.h>
29
+ #include <mma.h>
30
+
31
+ #include <torch/extension.h>
32
+ #include <ATen/cuda/CUDAContext.h>
33
+ #include <c10/cuda/CUDAException.h>
34
+
35
+ using namespace nvcuda;
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Constants
39
+ // ---------------------------------------------------------------------------
40
+ static constexpr int WMMA_M = 16;
41
+ static constexpr int WMMA_N = 16;
42
+ static constexpr int WMMA_K = 16;
43
+
44
+ static constexpr int BM = 128;
45
+ static constexpr int BN = 128;
46
+ static constexpr int KCHUNK = 32; // process d in 32-wide chunks (2 WMMA_K)
47
+ // keeps SMEM fixed at 80KB regardless of d
48
+
49
+ // 16 warps: each covers 32×32 sub-tile via 2×2 WMMA calls
50
+ static constexpr int WARPS_M = 4;
51
+ static constexpr int WARPS_N = 4;
52
+ static constexpr int NWARPS = WARPS_M * WARPS_N; // 16
53
+ static constexpr int NTHREADS = NWARPS * 32; // 512
54
+
55
+ // Fixed SMEM: sA + sB + sDot
56
+ static constexpr size_t SMEM_BYTES =
57
+ (size_t)BM * KCHUNK * sizeof(half) // sA
58
+ + (size_t)BN * KCHUNK * sizeof(half) // sB
59
+ + (size_t)BM * BN * sizeof(float); // sDot
60
+
61
+ static inline int ceil_div(int a, int b) { return (a + b - 1) / b; }
62
+ static inline int round_up(int a, int b) { return ceil_div(a, b) * b; }
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // Squared norms
66
+ // ---------------------------------------------------------------------------
67
+ __global__ void sq_norm_kernel_sm120(
68
+ const __half* __restrict__ X, float* __restrict__ sq, int N, int d)
69
+ {
70
+ int i = blockIdx.x * blockDim.x + threadIdx.x;
71
+ if (i >= N) return;
72
+ float s = 0.f;
73
+ for (int k = 0; k < d; ++k) { float v = __half2float(X[i*d+k]); s += v*v; }
74
+ sq[i] = s;
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // SMEM loaders for a k-chunk [k0, k0+klen)
79
+ // sA: [BM, KCHUNK] row-major — zero-pad for klen < KCHUNK
80
+ // sB: [BN, KCHUNK] col-major (stored as [col, k]) — zero-pad similarly
81
+ // ---------------------------------------------------------------------------
82
+ __device__ __forceinline__ void load_sA_chunk(
83
+ half* sA, const half* X, int i0, int bm, int d,
84
+ int k0, int klen, int tid)
85
+ {
86
+ for (int idx = tid; idx < BM * KCHUNK; idx += NTHREADS) {
87
+ int r = idx / KCHUNK, c = idx % KCHUNK;
88
+ sA[idx] = (r < bm && c < klen)
89
+ ? X[(long long)(i0+r)*d + k0+c]
90
+ : __float2half(0.f);
91
+ }
92
+ }
93
+
94
+ __device__ __forceinline__ void load_sB_chunk(
95
+ half* sB, const half* X, int j0, int bn, int d,
96
+ int k0, int klen, int tid)
97
+ {
98
+ for (int idx = tid; idx < BN * KCHUNK; idx += NTHREADS) {
99
+ int col = idx / KCHUNK, c = idx % KCHUNK;
100
+ sB[idx] = (col < bn && c < klen)
101
+ ? X[(long long)(j0+col)*d + k0+c]
102
+ : __float2half(0.f);
103
+ }
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // WMMA dot tile accumulate
108
+ // sA (BM×KCHUNK, row) @ sB^T (KCHUNK×BN, col) → sDot (BM×BN)
109
+ // Each of 16 warps covers 32×32 sub-tile (2×2 WMMA calls).
110
+ // first_chunk=true: fill fc=0 before MMA
111
+ // first_chunk=false: load fc from sDot first (accumulate across k-chunks)
112
+ // ---------------------------------------------------------------------------
113
+ __device__ __forceinline__ void wmma_accumulate(
114
+ const half* sA, const half* sB, float* sDot,
115
+ bool first_chunk, int tid)
116
+ {
117
+ const int warp = tid >> 5;
118
+ const int wm = warp / WARPS_N;
119
+ const int wn = warp % WARPS_N;
120
+
121
+ for (int dm = 0; dm < 2; ++dm) {
122
+ for (int dn = 0; dn < 2; ++dn) {
123
+ const int row16 = wm * 32 + dm * 16;
124
+ const int col16 = wn * 32 + dn * 16;
125
+
126
+ wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K,
127
+ half, wmma::row_major> fa;
128
+ wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K,
129
+ half, wmma::col_major> fb;
130
+ wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> fc;
131
+
132
+ if (first_chunk) {
133
+ wmma::fill_fragment(fc, 0.f);
134
+ } else {
135
+ wmma::load_matrix_sync(fc,
136
+ sDot + row16 * BN + col16, BN, wmma::mem_row_major);
137
+ }
138
+
139
+ for (int kk = 0; kk < KCHUNK; kk += WMMA_K) {
140
+ wmma::load_matrix_sync(fa, sA + row16 * KCHUNK + kk, KCHUNK);
141
+ wmma::load_matrix_sync(fb, sB + col16 * KCHUNK + kk, KCHUNK);
142
+ wmma::mma_sync(fc, fa, fb, fc);
143
+ }
144
+
145
+ wmma::store_matrix_sync(
146
+ sDot + row16 * BN + col16, fc, BN, wmma::mem_row_major);
147
+ }
148
+ }
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Prepass kernel: D_i = Σ_j exp(-β||xi-xj||²) * w_j
153
+ // ---------------------------------------------------------------------------
154
+ __global__ void __launch_bounds__(NTHREADS)
155
+ prepass_kernel_sm120(
156
+ const half* __restrict__ X,
157
+ const float* __restrict__ w,
158
+ float* __restrict__ D,
159
+ const float* __restrict__ sq_X,
160
+ int N, int d, float beta)
161
+ {
162
+ extern __shared__ unsigned char smem[];
163
+ half* sA = reinterpret_cast<half*>(smem);
164
+ half* sB = sA + BM * KCHUNK;
165
+ float* sDot = reinterpret_cast<float*>(sB + BN * KCHUNK);
166
+
167
+ const int tid = threadIdx.x;
168
+ const int i0 = blockIdx.x * BM;
169
+ const int bm = min(BM, N - i0);
170
+ float acc = 0.f;
171
+
172
+ for (int j0 = 0; j0 < N; j0 += BN) {
173
+ const int bn = min(BN, N - j0);
174
+
175
+ // k-chunk loop: accumulate dot products into sDot
176
+ for (int k0 = 0; k0 < d; k0 += KCHUNK) {
177
+ const int klen = min(KCHUNK, d - k0);
178
+ const bool first = (k0 == 0);
179
+
180
+ load_sA_chunk(sA, X, i0, bm, d, k0, klen, tid);
181
+ load_sB_chunk(sB, X, j0, bn, d, k0, klen, tid);
182
+ __syncthreads();
183
+
184
+ wmma_accumulate(sA, sB, sDot, first, tid);
185
+ __syncthreads();
186
+ }
187
+
188
+ // epilogue: dist2 → exp → accumulate
189
+ if (tid < bm) {
190
+ float sqi = sq_X[i0 + tid];
191
+ #pragma unroll 4
192
+ for (int j = 0; j < bn; ++j) {
193
+ float dist2 = fmaxf(sqi + sq_X[j0+j] - 2.f * sDot[tid*BN+j], 0.f);
194
+ acc += __expf(-beta * dist2) * w[j0+j];
195
+ }
196
+ }
197
+ __syncthreads();
198
+ }
199
+
200
+ if (tid < bm) D[i0 + tid] = acc;
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Matvec kernel: out_i = rscale_i * Σ_j exp(-β||xi-xj||²) * u_j
205
+ // ---------------------------------------------------------------------------
206
+ __global__ void __launch_bounds__(NTHREADS)
207
+ matvec_kernel_sm120(
208
+ const half* __restrict__ X,
209
+ const float* __restrict__ u,
210
+ float* __restrict__ out,
211
+ const float* __restrict__ sq_X,
212
+ const float* __restrict__ rscale,
213
+ int N, int d, float beta)
214
+ {
215
+ extern __shared__ unsigned char smem[];
216
+ half* sA = reinterpret_cast<half*>(smem);
217
+ half* sB = sA + BM * KCHUNK;
218
+ float* sDot = reinterpret_cast<float*>(sB + BN * KCHUNK);
219
+
220
+ const int tid = threadIdx.x;
221
+ const int i0 = blockIdx.x * BM;
222
+ const int bm = min(BM, N - i0);
223
+ float acc = 0.f;
224
+
225
+ for (int j0 = 0; j0 < N; j0 += BN) {
226
+ const int bn = min(BN, N - j0);
227
+
228
+ for (int k0 = 0; k0 < d; k0 += KCHUNK) {
229
+ const int klen = min(KCHUNK, d - k0);
230
+ const bool first = (k0 == 0);
231
+
232
+ load_sA_chunk(sA, X, i0, bm, d, k0, klen, tid);
233
+ load_sB_chunk(sB, X, j0, bn, d, k0, klen, tid);
234
+ __syncthreads();
235
+
236
+ wmma_accumulate(sA, sB, sDot, first, tid);
237
+ __syncthreads();
238
+ }
239
+
240
+ if (tid < bm) {
241
+ float sqi = sq_X[i0 + tid];
242
+ #pragma unroll 4
243
+ for (int j = 0; j < bn; ++j) {
244
+ float dist2 = fmaxf(sqi + sq_X[j0+j] - 2.f * sDot[tid*BN+j], 0.f);
245
+ acc += __expf(-beta * dist2) * u[j0+j];
246
+ }
247
+ }
248
+ __syncthreads();
249
+ }
250
+
251
+ if (tid < bm) out[i0 + tid] = rscale[i0 + tid] * acc;
252
+ }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // SMEM opt-in
256
+ // ---------------------------------------------------------------------------
257
+ static void set_smem(const void* fn) {
258
+ int dev; C10_CUDA_CHECK(cudaGetDevice(&dev));
259
+ int maxoptin;
260
+ C10_CUDA_CHECK(cudaDeviceGetAttribute(
261
+ &maxoptin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev));
262
+ TORCH_CHECK((int)SMEM_BYTES <= maxoptin,
263
+ "SMEM ", SMEM_BYTES, " > device max ", maxoptin);
264
+ C10_CUDA_CHECK(cudaFuncSetAttribute(
265
+ fn, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SMEM_BYTES));
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Python entry points
270
+ // ---------------------------------------------------------------------------
271
+
272
+ torch::Tensor compute_sq_norms(torch::Tensor X_fp16) {
273
+ int N = X_fp16.size(0), d = X_fp16.size(1);
274
+ auto sq = torch::empty({N}, X_fp16.options().dtype(torch::kFloat32));
275
+ sq_norm_kernel_sm120<<<ceil_div(N,256), 256, 0,
276
+ at::cuda::getCurrentCUDAStream()>>>(
277
+ reinterpret_cast<const __half*>(X_fp16.data_ptr<at::Half>()),
278
+ sq.data_ptr<float>(), N, d);
279
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
280
+ return sq;
281
+ }
282
+
283
+ torch::Tensor prepass(
284
+ torch::Tensor X_fp16, torch::Tensor w,
285
+ torch::Tensor sq_X, float beta)
286
+ {
287
+ int N = X_fp16.size(0), d = X_fp16.size(1);
288
+ set_smem(reinterpret_cast<const void*>(prepass_kernel_sm120));
289
+
290
+ auto D = torch::zeros({N}, w.options());
291
+ prepass_kernel_sm120<<<ceil_div(N,BM), NTHREADS, SMEM_BYTES,
292
+ at::cuda::getCurrentCUDAStream()>>>(
293
+ reinterpret_cast<const half*>(X_fp16.data_ptr<at::Half>()),
294
+ w.data_ptr<float>(), D.data_ptr<float>(),
295
+ sq_X.data_ptr<float>(), N, d, beta);
296
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
297
+ return D;
298
+ }
299
+
300
+ torch::Tensor matvec(
301
+ torch::Tensor X_fp16, torch::Tensor v,
302
+ torch::Tensor rscale, torch::Tensor sq_X, float beta)
303
+ {
304
+ int N = X_fp16.size(0), d = X_fp16.size(1);
305
+ set_smem(reinterpret_cast<const void*>(matvec_kernel_sm120));
306
+
307
+ auto u = (rscale * v).contiguous();
308
+ auto out = torch::empty({N}, v.options());
309
+ matvec_kernel_sm120<<<ceil_div(N,BM), NTHREADS, SMEM_BYTES,
310
+ at::cuda::getCurrentCUDAStream()>>>(
311
+ reinterpret_cast<const half*>(X_fp16.data_ptr<at::Half>()),
312
+ u.data_ptr<float>(), out.data_ptr<float>(),
313
+ sq_X.data_ptr<float>(), rscale.data_ptr<float>(),
314
+ N, d, beta);
315
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
316
+ return out;
317
+ }
318
+
319
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
320
+ m.doc() = "FlashDiffusion SM120 WMMA v2 — k-chunked, arbitrary d "
321
+ "(RTX 5090 / RTX PRO 6000 Blackwell consumer)";
322
+ m.def("compute_sq_norms", &compute_sq_norms, py::arg("X_fp16"));
323
+ m.def("prepass", &prepass,
324
+ py::arg("X_fp16"), py::arg("w"), py::arg("sq_X"), py::arg("beta"));
325
+ m.def("matvec", &matvec,
326
+ py::arg("X_fp16"), py::arg("v"), py::arg("rscale"),
327
+ py::arg("sq_X"), py::arg("beta"));
328
+ }
@@ -0,0 +1,312 @@
1
+ /*
2
+ * flash_diffusion_sm120.cu
3
+ * ========================
4
+ * SM120 (RTX 5090 / RTX PRO 6000 Blackwell consumer) WMMA kernel.
5
+ *
6
+ * Upgraded from scalar v1 to WMMA tensor cores.
7
+ * SM120 uses nvcuda::wmma (same mma.sync family as SM80/SM86/SM89).
8
+ * No wgmma, no TMEM, no UMMA — those are SM90/SM100 only.
9
+ *
10
+ * Key differences from SM80 WMMA kernel:
11
+ * - BM=128, BN=128 (vs 64×64) — larger tiles exploit SM120's bigger SMEM
12
+ * - 16 warps = 512 threads, each warp covers 32×32 via 2×2 WMMA calls
13
+ * - KPAD = ceil(d/16)*16 as usual
14
+ *
15
+ * SMEM per block (SM120 has 100KB):
16
+ * sA = BM × KPAD × 2 = 128 × KPAD × 2
17
+ * sB = BN × KPAD × 2 = 128 × KPAD × 2
18
+ * sDot = BM × BN × 4 = 128 × 128 × 4 = 64KB
19
+ * For d≤16 (KPAD=16): 64 + 4 + 4 = 72KB ✓
20
+ * For d≤64 (KPAD=64): 64 + 16 + 16 = 96KB ✓
21
+ * For d≤128 (KPAD=128): 64 + 32 + 32 = 128KB — needs opt-in
22
+ *
23
+ * Build:
24
+ * -arch=sm_120 -std=c++17 -O3 --use_fast_math
25
+ * -U__CUDA_NO_HALF_OPERATORS__ -U__CUDA_NO_HALF_CONVERSIONS__
26
+ * --expt-relaxed-constexpr
27
+ */
28
+
29
+ #include <cuda.h>
30
+ #include <cuda_runtime.h>
31
+ #include <cuda_fp16.h>
32
+ #include <mma.h>
33
+
34
+ #include <torch/extension.h>
35
+ #include <ATen/cuda/CUDAContext.h>
36
+ #include <c10/cuda/CUDAException.h>
37
+
38
+ using namespace nvcuda;
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Constants
42
+ // ---------------------------------------------------------------------------
43
+ static constexpr int WMMA_M = 16;
44
+ static constexpr int WMMA_N = 16;
45
+ static constexpr int WMMA_K = 16;
46
+
47
+ static constexpr int BM = 128;
48
+ static constexpr int BN = 128;
49
+
50
+ // 16 warps = 512 threads
51
+ // Each warp covers a 32×32 sub-tile via 2×2 WMMA calls
52
+ static constexpr int WARPS_M = 4; // 4 warps in M → 4×32 = 128 rows ✓
53
+ static constexpr int WARPS_N = 4; // 4 warps in N → 4×32 = 128 cols ✓
54
+ static constexpr int NWARPS = WARPS_M * WARPS_N; // 16
55
+ static constexpr int NTHREADS = NWARPS * 32; // 512
56
+
57
+ static inline int ceil_div(int a, int b) { return (a + b - 1) / b; }
58
+ static inline int round_up(int a, int b) { return ceil_div(a, b) * b; }
59
+
60
+ static size_t smem_size(int d) {
61
+ int KPAD = round_up(d, WMMA_K);
62
+ return (size_t)BM * KPAD * sizeof(half)
63
+ + (size_t)BN * KPAD * sizeof(half)
64
+ + (size_t)BM * BN * sizeof(float);
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Squared norms
69
+ // ---------------------------------------------------------------------------
70
+ __global__ void sq_norm_kernel_sm120(
71
+ const __half* __restrict__ X, float* __restrict__ sq, int N, int d)
72
+ {
73
+ int i = blockIdx.x * blockDim.x + threadIdx.x;
74
+ if (i >= N) return;
75
+ float s = 0.f;
76
+ for (int k = 0; k < d; ++k) { float v = __half2float(X[i*d+k]); s += v*v; }
77
+ sq[i] = s;
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // SMEM loaders
82
+ // sA: [BM, KPAD] row-major → matrix_a row_major
83
+ // sB: [BN, KPAD] stored [col,k] → matrix_b col_major (B^T)
84
+ // ---------------------------------------------------------------------------
85
+ __device__ __forceinline__ void load_sA(
86
+ half* sA, const half* X, int i0, int bm, int d, int KPAD, int tid)
87
+ {
88
+ for (int idx = tid; idx < BM * KPAD; idx += NTHREADS) {
89
+ int r = idx / KPAD, c = idx % KPAD;
90
+ sA[idx] = (r < bm && c < d) ? X[(long long)(i0+r)*d + c] : __float2half(0.f);
91
+ }
92
+ }
93
+
94
+ __device__ __forceinline__ void load_sB(
95
+ half* sB, const half* X, int j0, int bn, int d, int KPAD, int tid)
96
+ {
97
+ for (int idx = tid; idx < BN * KPAD; idx += NTHREADS) {
98
+ int col = idx / KPAD, k = idx % KPAD;
99
+ sB[idx] = (col < bn && k < d) ? X[(long long)(j0+col)*d + k] : __float2half(0.f);
100
+ }
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // WMMA dot tile: sA (BM×KPAD, row) @ sB^T (KPAD×BN, col) → sDot (BM×BN)
105
+ //
106
+ // Each of 16 warps covers a 32×32 sub-tile using 2×2 WMMA fragments.
107
+ // warp (wm, wn): output rows [wm*32, wm*32+32), cols [wn*32, wn*32+32)
108
+ // ---------------------------------------------------------------------------
109
+ __device__ __forceinline__ void wmma_dot_tile(
110
+ const half* sA, const half* sB, float* sDot, int KPAD, int tid)
111
+ {
112
+ const int warp = tid >> 5;
113
+ const int wm = warp / WARPS_N; // 0..3
114
+ const int wn = warp % WARPS_N; // 0..3
115
+
116
+ // 2×2 WMMA tiles per warp → 32×32 sub-tile
117
+ for (int dm = 0; dm < 2; ++dm) {
118
+ for (int dn = 0; dn < 2; ++dn) {
119
+ const int row16 = wm * 32 + dm * 16;
120
+ const int col16 = wn * 32 + dn * 16;
121
+
122
+ wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K,
123
+ half, wmma::row_major> fa;
124
+ wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K,
125
+ half, wmma::col_major> fb;
126
+ wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> fc;
127
+ wmma::fill_fragment(fc, 0.f);
128
+
129
+ for (int kk = 0; kk < KPAD; kk += WMMA_K) {
130
+ wmma::load_matrix_sync(fa, sA + row16 * KPAD + kk, KPAD);
131
+ wmma::load_matrix_sync(fb, sB + col16 * KPAD + kk, KPAD);
132
+ wmma::mma_sync(fc, fa, fb, fc);
133
+ }
134
+
135
+ wmma::store_matrix_sync(
136
+ sDot + row16 * BN + col16, fc, BN, wmma::mem_row_major);
137
+ }
138
+ }
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // Prepass kernel
143
+ // ---------------------------------------------------------------------------
144
+ __global__ void prepass_kernel_sm120(
145
+ const half* __restrict__ X,
146
+ const float* __restrict__ w,
147
+ float* __restrict__ D,
148
+ const float* __restrict__ sq_X,
149
+ int N, int d, int KPAD, float beta)
150
+ {
151
+ extern __shared__ unsigned char smem[];
152
+ half* sA = reinterpret_cast<half*>(smem);
153
+ half* sB = sA + BM * KPAD;
154
+ float* sDot = reinterpret_cast<float*>(sB + BN * KPAD);
155
+
156
+ const int tid = threadIdx.x;
157
+ const int i0 = blockIdx.x * BM;
158
+ const int bm = min(BM, N - i0);
159
+ float acc = 0.f;
160
+
161
+ load_sA(sA, X, i0, bm, d, KPAD, tid);
162
+ __syncthreads();
163
+
164
+ for (int j0 = 0; j0 < N; j0 += BN) {
165
+ const int bn = min(BN, N - j0);
166
+
167
+ load_sB(sB, X, j0, bn, d, KPAD, tid);
168
+ __syncthreads();
169
+
170
+ wmma_dot_tile(sA, sB, sDot, KPAD, tid);
171
+ __syncthreads();
172
+
173
+ if (tid < bm) {
174
+ float sqi = sq_X[i0 + tid];
175
+ #pragma unroll 4
176
+ for (int j = 0; j < bn; ++j) {
177
+ float dist2 = fmaxf(sqi + sq_X[j0+j] - 2.f * sDot[tid*BN+j], 0.f);
178
+ acc += __expf(-beta * dist2) * w[j0+j];
179
+ }
180
+ }
181
+ __syncthreads();
182
+ }
183
+
184
+ if (tid < bm) D[i0 + tid] = acc;
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Matvec kernel
189
+ // ---------------------------------------------------------------------------
190
+ __global__ void matvec_kernel_sm120(
191
+ const half* __restrict__ X,
192
+ const float* __restrict__ u,
193
+ float* __restrict__ out,
194
+ const float* __restrict__ sq_X,
195
+ const float* __restrict__ rscale,
196
+ int N, int d, int KPAD, float beta)
197
+ {
198
+ extern __shared__ unsigned char smem[];
199
+ half* sA = reinterpret_cast<half*>(smem);
200
+ half* sB = sA + BM * KPAD;
201
+ float* sDot = reinterpret_cast<float*>(sB + BN * KPAD);
202
+
203
+ const int tid = threadIdx.x;
204
+ const int i0 = blockIdx.x * BM;
205
+ const int bm = min(BM, N - i0);
206
+ float acc = 0.f;
207
+
208
+ load_sA(sA, X, i0, bm, d, KPAD, tid);
209
+ __syncthreads();
210
+
211
+ for (int j0 = 0; j0 < N; j0 += BN) {
212
+ const int bn = min(BN, N - j0);
213
+
214
+ load_sB(sB, X, j0, bn, d, KPAD, tid);
215
+ __syncthreads();
216
+
217
+ wmma_dot_tile(sA, sB, sDot, KPAD, tid);
218
+ __syncthreads();
219
+
220
+ if (tid < bm) {
221
+ float sqi = sq_X[i0 + tid];
222
+ #pragma unroll 4
223
+ for (int j = 0; j < bn; ++j) {
224
+ float dist2 = fmaxf(sqi + sq_X[j0+j] - 2.f * sDot[tid*BN+j], 0.f);
225
+ acc += __expf(-beta * dist2) * u[j0+j];
226
+ }
227
+ }
228
+ __syncthreads();
229
+ }
230
+
231
+ if (tid < bm) out[i0 + tid] = rscale[i0 + tid] * acc;
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // SMEM opt-in
236
+ // ---------------------------------------------------------------------------
237
+ static void set_smem(const void* fn, size_t bytes) {
238
+ int dev; C10_CUDA_CHECK(cudaGetDevice(&dev));
239
+ int maxoptin;
240
+ C10_CUDA_CHECK(cudaDeviceGetAttribute(
241
+ &maxoptin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev));
242
+ TORCH_CHECK((int)bytes <= maxoptin,
243
+ "SMEM ", bytes, " > device max ", maxoptin);
244
+ C10_CUDA_CHECK(cudaFuncSetAttribute(
245
+ fn, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)bytes));
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Python entry points
250
+ // ---------------------------------------------------------------------------
251
+
252
+ torch::Tensor compute_sq_norms(torch::Tensor X_fp16) {
253
+ int N = X_fp16.size(0), d = X_fp16.size(1);
254
+ auto sq = torch::empty({N}, X_fp16.options().dtype(torch::kFloat32));
255
+ sq_norm_kernel_sm120<<<ceil_div(N,256), 256, 0,
256
+ at::cuda::getCurrentCUDAStream()>>>(
257
+ reinterpret_cast<const __half*>(X_fp16.data_ptr<at::Half>()),
258
+ sq.data_ptr<float>(), N, d);
259
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
260
+ return sq;
261
+ }
262
+
263
+ torch::Tensor prepass(
264
+ torch::Tensor X_fp16, torch::Tensor w,
265
+ torch::Tensor sq_X, float beta)
266
+ {
267
+ int N = X_fp16.size(0), d = X_fp16.size(1);
268
+ int KPAD = round_up(d, WMMA_K);
269
+ size_t sm = smem_size(d);
270
+ set_smem(reinterpret_cast<const void*>(prepass_kernel_sm120), sm);
271
+
272
+ auto D = torch::zeros({N}, w.options());
273
+ prepass_kernel_sm120<<<ceil_div(N,BM), NTHREADS, sm,
274
+ at::cuda::getCurrentCUDAStream()>>>(
275
+ reinterpret_cast<const half*>(X_fp16.data_ptr<at::Half>()),
276
+ w.data_ptr<float>(), D.data_ptr<float>(),
277
+ sq_X.data_ptr<float>(), N, d, KPAD, beta);
278
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
279
+ return D;
280
+ }
281
+
282
+ torch::Tensor matvec(
283
+ torch::Tensor X_fp16, torch::Tensor v,
284
+ torch::Tensor rscale, torch::Tensor sq_X, float beta)
285
+ {
286
+ int N = X_fp16.size(0), d = X_fp16.size(1);
287
+ int KPAD = round_up(d, WMMA_K);
288
+ size_t sm = smem_size(d);
289
+ set_smem(reinterpret_cast<const void*>(matvec_kernel_sm120), sm);
290
+
291
+ auto u = (rscale * v).contiguous();
292
+ auto out = torch::empty({N}, v.options());
293
+ matvec_kernel_sm120<<<ceil_div(N,BM), NTHREADS, sm,
294
+ at::cuda::getCurrentCUDAStream()>>>(
295
+ reinterpret_cast<const half*>(X_fp16.data_ptr<at::Half>()),
296
+ u.data_ptr<float>(), out.data_ptr<float>(),
297
+ sq_X.data_ptr<float>(), rscale.data_ptr<float>(),
298
+ N, d, KPAD, beta);
299
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
300
+ return out;
301
+ }
302
+
303
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
304
+ m.doc() = "FlashDiffusion SM120 WMMA tensor cores "
305
+ "(RTX 5090 / RTX PRO 6000 Blackwell consumer)";
306
+ m.def("compute_sq_norms", &compute_sq_norms, py::arg("X_fp16"));
307
+ m.def("prepass", &prepass,
308
+ py::arg("X_fp16"), py::arg("w"), py::arg("sq_X"), py::arg("beta"));
309
+ m.def("matvec", &matvec,
310
+ py::arg("X_fp16"), py::arg("v"), py::arg("rscale"),
311
+ py::arg("sq_X"), py::arg("beta"));
312
+ }