flashdiffusion 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Julio Candanedo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: flashdiffusion
3
+ Version: 0.1.0
4
+ Summary: GPU-accelerated diffusion maps with tensor core kernels
5
+ Author: Julio Candanedo
6
+ Author-email: Julio Candanedo <julio@sparsetrace.ai>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/sparsetrace/FlashDiffusion
9
+ Keywords: diffusion maps,manifold learning,CUDA,tensor cores,GPU
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: scipy>=1.10
23
+ Requires-Dist: ninja
24
+ Dynamic: author
25
+ Dynamic: license-file
26
+ Dynamic: requires-python
27
+
28
+ # FlashDiffusion
29
+
30
+ Tiled, memory-efficient diffusion maps eigensolver — never materialises the O(N²) kernel matrix.
31
+
32
+ ## What this enables
33
+
34
+ | Task | N limit (dense) | N limit (FlashDiffusion) |
35
+ |---|---|---|
36
+ | Diffusion map eigenvectors | ~20k (8 GB) | ~10M (memory: O(N·tile)) |
37
+ | Carré du Champ metric tensor | ~10k | ~1M |
38
+ | Schrödinger bridge / Doob h-transform | ~10k | ~1M |
39
+ | MD trajectory slow manifold | ~5k frames | ~500k frames |
40
+
41
+ ## The primitive
42
+
43
+ ```python
44
+ from flashdiffusion import FlashDiffusion
45
+
46
+ # K(i,j) = exp(-beta * score_mod(xi, xj))
47
+ # with Coifman-Lafon alpha-normalisation and optional Doob h-transform
48
+ out = FlashDiffusion(X, X, V, beta=1.0, alpha=0.5, h=None)
49
+ ```
50
+
51
+ `FlashDiffusion(Q, K, V, beta, alpha, h)` is the single kernel underlying everything:
52
+ - **DMAP mode** (Q=K=X, V=eigvec guess): symmetric diffusion matvec for Lanczos
53
+ - **AMAP mode** (Q≠K, asymmetric W): directed/NESS Markov operator (DAC §3)
54
+ - **Doob mode** (h≠None): h-transform of any of the above (DAC §4)
55
+
56
+ ## Design
57
+
58
+ ```
59
+ kernel.py FlashDiffusion primitive — tiled O(N·tile) memory matvec
60
+ dmap.py DiffusionMap class: fit() precomputes rscale; transform() calls kernel
61
+ eigensolver.py Lanczos/LOBPCG with bf16→fp32→fp64 precision ramp; orthog in fp64
62
+ cdc.py Carré du Champ operator Γ(f,g) and metric tensor M = ΣᵢGᵢGᵢᵀ
63
+ utils.py Bandwidth selection (self-tuning, median), Nyström extension
64
+ ```
65
+
66
+ ## Physics background
67
+
68
+ Transformer attention, diffusion maps, and magnetic Laplacians are three regimes
69
+ of a single Markov geometry (Candanedo 2025). The EQ/NESS classification:
70
+
71
+ - **EQ** (symmetric W): DMAP — reversible diffusion, detailed balance
72
+ - **NESS** (asymmetric W): self-attention — directed, probability current ≠ 0
73
+ - **Doob deformation**: h-transform preserves EQ class (Theorem 5.1, DAC)
74
+
75
+ The Coifman-Lafon α-normalisation is an exact Doob transform (Corollary 4.2, DAC).
76
+
77
+ # FlashDiffusion SM120 — RTX 6000 / Consumer Blackwell
78
+
79
+ ## What's in this package
80
+
81
+ ```
82
+ flashdiffusion/csrc/flash_diffusion_sm120.cu ← kernel
83
+ flashdiffusion/kernel_cuda_sm120.py ← Python wrapper
84
+ setup_sm120.py ← build script
85
+ sm120_notebook.py ← notebook cells
86
+ ```
87
+
88
+ ## SM120 vs SM80 kernel differences
89
+
90
+ | Feature | SM80 (A100) | SM120 (RTX 5090) |
91
+ |-----------------|--------------------|-------------------------|
92
+ | MMA instruction | mma.sync f16→f32 | mma.sync f16→f32 (same) |
93
+ | Tile size | 64×64 | 128×128 |
94
+ | SMEM async | __syncthreads | cp.async pipeline |
95
+ | TMA | no | yes (not used yet) |
96
+ | TMEM | no | no (SM100 only) |
97
+ | Cluster shape | 1×1×1 | 1×1×1 (no multicast) |
98
+ | WGMMA/UMMA | no | no (SM100 only) |
99
+
100
+ The inner GEMM instruction is **identical** to SM80. The speedup comes from:
101
+ 1. Larger 128×128 tiles → better arithmetic intensity
102
+ 2. cp.async pipeline → hides GMEM→SMEM load latency
103
+ 3. Higher RTX 5090 clock speed
104
+
105
+ ## Build
106
+
107
+ ```bash
108
+ # on a machine with RTX 5090
109
+ FLASHDIFFUSION_BUILD_CUDA=1 \
110
+ TORCH_CUDA_ARCH_LIST="12.0" \
111
+ python setup_sm120.py build_ext --inplace
112
+ ```
113
+
114
+ Or in notebook (see sm120_notebook.py Cell 2).
115
+
116
+ ## Expected performance vs SM80
117
+
118
+ ```
119
+ N=200k SM80 A100 precompute: 0.4s Lanczos: ~100s
120
+ N=200k SM120 5090 precompute: ~0.3s Lanczos: ~60s (estimate)
121
+ ```
122
+
123
+ RTX 5090 has higher memory bandwidth than A100 (1.8 TB/s vs 2.0 TB/s)
124
+ but our scalar kernel is compute-bound not memory-bound.
125
+ The cp.async pipeline and larger tiles are the main wins.
126
+
127
+ ## Next step: TiledMMA on SM120
128
+
129
+ The `mma.sync.aligned.m16n8k16` instruction on SM120 uses the same
130
+ CuTe atom as SM80: `SM80_16x8x16_F32F16F16F32`.
131
+ Wiring TiledMMA replaces the scalar inner loop, giving ~10× speedup.
132
+ This is `flash_diffusion_sm120_v2.cu` — to be added next.
133
+
134
+
135
+ ## CUDA roadmap
136
+
137
+ Current: NumPy reference (validates correctness, runs on CPU).
138
+ Next: CuTe kernel — SM90 tensor cores, fused prepass+matvec, no online softmax needed
139
+ (precomputed rscale eliminates the log-sum-exp recurrence that drives FA4 complexity).
140
+
141
+ ```
142
+ prepass: out_i = Σⱼ K(i,j) · wⱼ # scalar reduction per row, one kernel
143
+ matvec: out_i = rscaleᵢ · Σⱼ K(i,j) · rscaleⱼ · vⱼ # vector, same tiling
144
+ ```
145
+
146
+ Both kernels share the same tile loop; only the epilogue differs.
147
+
148
+ ## Installation
149
+
150
+ ```bash
151
+ pip install -e ".[dev]"
152
+ ```
153
+
154
+ ## Quick start
155
+
156
+ ```python
157
+ from flashdiffusion import DiffusionMap
158
+
159
+ dm = DiffusionMap(beta=1.0, alpha=0.5, n_components=8)
160
+ dm.fit(X) # two prepass tiled reductions, O(N·tile) memory
161
+ coords = dm.transform() # Lanczos eigensolver, mixed precision
162
+ ```
163
+
164
+ ## References
165
+
166
+ - Coifman & Lafon (2006) — diffusion maps
167
+ - Candanedo (2025) — diffusion-attention connection, bidivergence, Doob classification
168
+ - Dao et al. (2024) — FlashAttention-4
169
+ - Rohrdanz, Zheng, Clementi (2011) — diffusion maps for MD
@@ -0,0 +1,142 @@
1
+ # FlashDiffusion
2
+
3
+ Tiled, memory-efficient diffusion maps eigensolver — never materialises the O(N²) kernel matrix.
4
+
5
+ ## What this enables
6
+
7
+ | Task | N limit (dense) | N limit (FlashDiffusion) |
8
+ |---|---|---|
9
+ | Diffusion map eigenvectors | ~20k (8 GB) | ~10M (memory: O(N·tile)) |
10
+ | Carré du Champ metric tensor | ~10k | ~1M |
11
+ | Schrödinger bridge / Doob h-transform | ~10k | ~1M |
12
+ | MD trajectory slow manifold | ~5k frames | ~500k frames |
13
+
14
+ ## The primitive
15
+
16
+ ```python
17
+ from flashdiffusion import FlashDiffusion
18
+
19
+ # K(i,j) = exp(-beta * score_mod(xi, xj))
20
+ # with Coifman-Lafon alpha-normalisation and optional Doob h-transform
21
+ out = FlashDiffusion(X, X, V, beta=1.0, alpha=0.5, h=None)
22
+ ```
23
+
24
+ `FlashDiffusion(Q, K, V, beta, alpha, h)` is the single kernel underlying everything:
25
+ - **DMAP mode** (Q=K=X, V=eigvec guess): symmetric diffusion matvec for Lanczos
26
+ - **AMAP mode** (Q≠K, asymmetric W): directed/NESS Markov operator (DAC §3)
27
+ - **Doob mode** (h≠None): h-transform of any of the above (DAC §4)
28
+
29
+ ## Design
30
+
31
+ ```
32
+ kernel.py FlashDiffusion primitive — tiled O(N·tile) memory matvec
33
+ dmap.py DiffusionMap class: fit() precomputes rscale; transform() calls kernel
34
+ eigensolver.py Lanczos/LOBPCG with bf16→fp32→fp64 precision ramp; orthog in fp64
35
+ cdc.py Carré du Champ operator Γ(f,g) and metric tensor M = ΣᵢGᵢGᵢᵀ
36
+ utils.py Bandwidth selection (self-tuning, median), Nyström extension
37
+ ```
38
+
39
+ ## Physics background
40
+
41
+ Transformer attention, diffusion maps, and magnetic Laplacians are three regimes
42
+ of a single Markov geometry (Candanedo 2025). The EQ/NESS classification:
43
+
44
+ - **EQ** (symmetric W): DMAP — reversible diffusion, detailed balance
45
+ - **NESS** (asymmetric W): self-attention — directed, probability current ≠ 0
46
+ - **Doob deformation**: h-transform preserves EQ class (Theorem 5.1, DAC)
47
+
48
+ The Coifman-Lafon α-normalisation is an exact Doob transform (Corollary 4.2, DAC).
49
+
50
+ # FlashDiffusion SM120 — RTX 6000 / Consumer Blackwell
51
+
52
+ ## What's in this package
53
+
54
+ ```
55
+ flashdiffusion/csrc/flash_diffusion_sm120.cu ← kernel
56
+ flashdiffusion/kernel_cuda_sm120.py ← Python wrapper
57
+ setup_sm120.py ← build script
58
+ sm120_notebook.py ← notebook cells
59
+ ```
60
+
61
+ ## SM120 vs SM80 kernel differences
62
+
63
+ | Feature | SM80 (A100) | SM120 (RTX 5090) |
64
+ |-----------------|--------------------|-------------------------|
65
+ | MMA instruction | mma.sync f16→f32 | mma.sync f16→f32 (same) |
66
+ | Tile size | 64×64 | 128×128 |
67
+ | SMEM async | __syncthreads | cp.async pipeline |
68
+ | TMA | no | yes (not used yet) |
69
+ | TMEM | no | no (SM100 only) |
70
+ | Cluster shape | 1×1×1 | 1×1×1 (no multicast) |
71
+ | WGMMA/UMMA | no | no (SM100 only) |
72
+
73
+ The inner GEMM instruction is **identical** to SM80. The speedup comes from:
74
+ 1. Larger 128×128 tiles → better arithmetic intensity
75
+ 2. cp.async pipeline → hides GMEM→SMEM load latency
76
+ 3. Higher RTX 5090 clock speed
77
+
78
+ ## Build
79
+
80
+ ```bash
81
+ # on a machine with RTX 5090
82
+ FLASHDIFFUSION_BUILD_CUDA=1 \
83
+ TORCH_CUDA_ARCH_LIST="12.0" \
84
+ python setup_sm120.py build_ext --inplace
85
+ ```
86
+
87
+ Or in notebook (see sm120_notebook.py Cell 2).
88
+
89
+ ## Expected performance vs SM80
90
+
91
+ ```
92
+ N=200k SM80 A100 precompute: 0.4s Lanczos: ~100s
93
+ N=200k SM120 5090 precompute: ~0.3s Lanczos: ~60s (estimate)
94
+ ```
95
+
96
+ RTX 5090 has higher memory bandwidth than A100 (1.8 TB/s vs 2.0 TB/s)
97
+ but our scalar kernel is compute-bound not memory-bound.
98
+ The cp.async pipeline and larger tiles are the main wins.
99
+
100
+ ## Next step: TiledMMA on SM120
101
+
102
+ The `mma.sync.aligned.m16n8k16` instruction on SM120 uses the same
103
+ CuTe atom as SM80: `SM80_16x8x16_F32F16F16F32`.
104
+ Wiring TiledMMA replaces the scalar inner loop, giving ~10× speedup.
105
+ This is `flash_diffusion_sm120_v2.cu` — to be added next.
106
+
107
+
108
+ ## CUDA roadmap
109
+
110
+ Current: NumPy reference (validates correctness, runs on CPU).
111
+ Next: CuTe kernel — SM90 tensor cores, fused prepass+matvec, no online softmax needed
112
+ (precomputed rscale eliminates the log-sum-exp recurrence that drives FA4 complexity).
113
+
114
+ ```
115
+ prepass: out_i = Σⱼ K(i,j) · wⱼ # scalar reduction per row, one kernel
116
+ matvec: out_i = rscaleᵢ · Σⱼ K(i,j) · rscaleⱼ · vⱼ # vector, same tiling
117
+ ```
118
+
119
+ Both kernels share the same tile loop; only the epilogue differs.
120
+
121
+ ## Installation
122
+
123
+ ```bash
124
+ pip install -e ".[dev]"
125
+ ```
126
+
127
+ ## Quick start
128
+
129
+ ```python
130
+ from flashdiffusion import DiffusionMap
131
+
132
+ dm = DiffusionMap(beta=1.0, alpha=0.5, n_components=8)
133
+ dm.fit(X) # two prepass tiled reductions, O(N·tile) memory
134
+ coords = dm.transform() # Lanczos eigensolver, mixed precision
135
+ ```
136
+
137
+ ## References
138
+
139
+ - Coifman & Lafon (2006) — diffusion maps
140
+ - Candanedo (2025) — diffusion-attention connection, bidivergence, Doob classification
141
+ - Dao et al. (2024) — FlashAttention-4
142
+ - Rohrdanz, Zheng, Clementi (2011) — diffusion maps for MD
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flashdiffusion"
7
+ version = "0.1.0"
8
+ description = "GPU-accelerated diffusion maps with tensor core kernels"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "Julio Candanedo", email = "julio@sparsetrace.ai"}]
13
+ keywords = ["diffusion maps", "manifold learning", "CUDA", "tensor cores", "GPU"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ ]
24
+ dependencies = ["numpy>=1.24", "scipy>=1.10", "ninja"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/sparsetrace/FlashDiffusion"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,319 @@
1
+ """
2
+ setup.py
3
+ ========
4
+ Builds FlashDiffusion CUDA extensions.
5
+
6
+ Kernels in csrc/:
7
+ flash_diffusion_sm80.cu — SM80 scalar (A100, fallback)
8
+ flash_diffusion_sm90.cu — SM90 wgmma+TMA (H100, requires CUTLASS >= 3.5)
9
+ flash_diffusion_sm100.cu — SM100 WMMA (B200/B300)
10
+ flash_diffusion_sm120.cu — SM120 128×128 tile (RTX 5090 / RTX PRO 6000)
11
+
12
+ Usage
13
+ -----
14
+ # CPU only:
15
+ pip install -e .
16
+
17
+ # GPU — auto-detects SM, auto-clones CUTLASS if needed:
18
+ FLASHDIFFUSION_BUILD_CUDA=1 pip install -e ".[cuda]"
19
+
20
+ # specific arch:
21
+ FLASHDIFFUSION_BUILD_CUDA=1 TORCH_CUDA_ARCH_LIST="8.0" pip install -e ".[cuda]"
22
+ FLASHDIFFUSION_BUILD_CUDA=1 TORCH_CUDA_ARCH_LIST="10.0" pip install -e ".[cuda]"
23
+ FLASHDIFFUSION_BUILD_CUDA=1 TORCH_CUDA_ARCH_LIST="12.0" pip install -e ".[cuda]"
24
+
25
+ CUTLASS
26
+ -------
27
+ SM90 and SM100 kernels need CUTLASS headers.
28
+ setup.py will auto-clone CUTLASS main into third_party/cutlass if not found.
29
+ To skip auto-clone, set CUTLASS_PATH to an existing CUTLASS include dir.
30
+ To use a git submodule instead:
31
+ git submodule add https://github.com/NVIDIA/cutlass third_party/cutlass
32
+ git submodule update --init --depth=1
33
+ """
34
+
35
+ import os, sys, glob, subprocess
36
+ from setuptools import setup
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Helper: find CUDA headers
40
+ # ---------------------------------------------------------------------------
41
+
42
+ def find_cuda_includes():
43
+ py = f"python{sys.version_info.major}.{sys.version_info.minor}"
44
+ candidates = []
45
+ cuda_home = os.environ.get("CUDA_HOME") or os.environ.get("CUDA_PATH")
46
+ if cuda_home:
47
+ candidates.append(os.path.join(cuda_home, "include"))
48
+ for base in [
49
+ f"/usr/local/lib/{py}/site-packages/nvidia",
50
+ f"/usr/lib/{py}/site-packages/nvidia",
51
+ ]:
52
+ candidates += glob.glob(f"{base}/*/include")
53
+ candidates += ["/usr/local/cuda/include", "/usr/cuda/include"]
54
+ return [p for p in candidates if os.path.isdir(p)]
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Helper: find or auto-clone CUTLASS
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def _has_sm100_headers(inc):
62
+ return os.path.exists(
63
+ os.path.join(inc, "cute", "arch", "mma_sm100_umma.hpp"))
64
+
65
+ def _has_sm90_headers(inc):
66
+ return os.path.exists(
67
+ os.path.join(inc, "cute", "tensor.hpp"))
68
+
69
+ def find_cutlass_include():
70
+ """
71
+ Find CUTLASS headers. Check order:
72
+ 1. CUTLASS_PATH env var
73
+ 2. third_party/cutlass submodule (in this repo)
74
+ 3. /tmp/cutlass* (notebook session clones)
75
+ 4. Auto-clone CUTLASS main into third_party/cutlass
76
+ Returns path to include/ dir, or None if all fail.
77
+ """
78
+ repo_root = os.path.dirname(os.path.abspath(__file__))
79
+ candidates = []
80
+
81
+ # 1. env var
82
+ env = os.environ.get("CUTLASS_PATH", "")
83
+ if env:
84
+ candidates.append(env if env.endswith("include") else
85
+ os.path.join(env, "include"))
86
+
87
+ # 2. git submodule
88
+ sub = os.path.join(repo_root, "third_party", "cutlass", "include")
89
+ candidates.append(sub)
90
+
91
+ # 3. /tmp session clones — prefer cutlass_main (has SM100 headers)
92
+ for p in sorted(glob.glob("/tmp/cutlass*/include"), reverse=True):
93
+ candidates.append(p)
94
+
95
+ for inc in candidates:
96
+ if os.path.isdir(inc) and _has_sm90_headers(inc):
97
+ return inc
98
+
99
+ return None # trigger auto-clone below
100
+
101
+
102
+ def ensure_cutlass():
103
+ """
104
+ Return CUTLASS include path, auto-cloning if necessary.
105
+ Clones into third_party/cutlass (persists across sessions).
106
+ """
107
+ inc = find_cutlass_include()
108
+ if inc:
109
+ return inc
110
+
111
+ # auto-clone CUTLASS main into third_party/cutlass
112
+ repo_root = os.path.dirname(os.path.abspath(__file__))
113
+ target = os.path.join(repo_root, "third_party", "cutlass")
114
+ inc = os.path.join(target, "include")
115
+
116
+ print("[setup.py] CUTLASS not found — cloning main branch into "
117
+ "third_party/cutlass ...")
118
+ print("[setup.py] (This happens once; subsequent installs reuse the clone.)")
119
+
120
+ os.makedirs(os.path.dirname(target), exist_ok=True)
121
+ subprocess.check_call([
122
+ "git", "clone", "--depth=1",
123
+ "https://github.com/NVIDIA/cutlass", target
124
+ ])
125
+ print(f"[setup.py] CUTLASS cloned to {target}")
126
+ return inc
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # SM routing tables
131
+ # ---------------------------------------------------------------------------
132
+
133
+ _SM_SOURCES = {
134
+ "80": "src/flashdiffusion/csrc/flash_diffusion_sm80.cu",
135
+ "86": "src/flashdiffusion/csrc/flash_diffusion_sm80.cu",
136
+ "89": "src/flashdiffusion/csrc/flash_diffusion_sm80.cu",
137
+ "90": "src/flashdiffusion/csrc/flash_diffusion_sm90.cu",
138
+ "100": "src/flashdiffusion/csrc/flash_diffusion_sm100.cu",
139
+ "103": "src/flashdiffusion/csrc/flash_diffusion_sm100.cu",
140
+ "120": "src/flashdiffusion/csrc/flash_diffusion_sm120.cu",
141
+ "121": "src/flashdiffusion/csrc/flash_diffusion_sm120.cu",
142
+ }
143
+
144
+ _SM_MODULE = {
145
+ "80": "flash_diffusion_cuda",
146
+ "86": "flash_diffusion_cuda",
147
+ "89": "flash_diffusion_cuda",
148
+ "90": "flash_diffusion_sm90",
149
+ "100": "flash_diffusion_sm100",
150
+ "103": "flash_diffusion_sm100",
151
+ "120": "flash_diffusion_sm120",
152
+ "121": "flash_diffusion_sm120",
153
+ }
154
+
155
+ _SM_ARCH = {
156
+ "80": "sm_80",
157
+ "86": "sm_86",
158
+ "89": "sm_89",
159
+ "90": "sm_90a", # 'a' required for wgmma
160
+ "100": "sm_100a", # 'a' required for UMMA
161
+ "103": "sm_100a",
162
+ "120": "sm_120",
163
+ "121": "sm_121",
164
+ }
165
+
166
+ # SMs that need CUTLASS headers
167
+ _SM_NEEDS_CUTLASS = {"90", "100", "103"}
168
+
169
+ # Extra nvcc defines per SM
170
+ _SM_NVCC_DEFINES = {
171
+ "90": ["-DCUTLASS_ARCH_MMA_SM90_SUPPORTED=1",
172
+ "-DCUTE_ARCH_MMA_SM90A_ENABLED=1"],
173
+ "100": ["-DCUTLASS_ARCH_MMA_SM100_SUPPORTED=1",
174
+ "-DCUTE_ARCH_MMA_SM100A_ENABLED=1"],
175
+ "103": ["-DCUTLASS_ARCH_MMA_SM100_SUPPORTED=1",
176
+ "-DCUTE_ARCH_MMA_SM100A_ENABLED=1"],
177
+ }
178
+
179
+
180
+ def _gencode(sm):
181
+ arch = _SM_ARCH.get(sm, f"sm_{sm}")
182
+ compute = arch.replace("sm_", "compute_").rstrip("a") # compute_100a → compute_100
183
+ return f"-gencode=arch={compute},code={arch}"
184
+
185
+
186
+ # ---------------------------------------------------------------------------
187
+ # Extension build
188
+ # ---------------------------------------------------------------------------
189
+
190
+ BUILD_CUDA = os.environ.get("FLASHDIFFUSION_BUILD_CUDA", "0") == "1"
191
+ ext_modules = []
192
+ cmdclass = {}
193
+
194
+ if BUILD_CUDA:
195
+ try:
196
+ import torch
197
+ from torch.utils.cpp_extension import CUDAExtension, BuildExtension
198
+
199
+ cuda_includes = find_cuda_includes()
200
+ print(f"[setup.py] CUDA includes: {len(cuda_includes)} paths found")
201
+
202
+ # resolve arch list
203
+ arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", "")
204
+ if not arch_list:
205
+ try:
206
+ major, minor = torch.cuda.get_device_capability()
207
+ arch_list = f"{major}.{minor}"
208
+ print(f"[setup.py] Auto-detected: SM{major*10+minor} "
209
+ f"({torch.cuda.get_device_name(0)})")
210
+ except Exception:
211
+ arch_list = "8.0"
212
+ print("[setup.py] No GPU found, defaulting to SM80")
213
+
214
+ # normalise: "8.0 10.0+PTX" → ["80", "100"]
215
+ sms = [a.strip().replace(".", "").replace("+PTX", "")
216
+ for a in arch_list.split() if a.strip()]
217
+
218
+ # check if any SM needs CUTLASS
219
+ needs_cutlass_globally = any(sm in _SM_NEEDS_CUTLASS for sm in sms)
220
+ cutlass_inc = None
221
+ if needs_cutlass_globally:
222
+ try:
223
+ cutlass_inc = ensure_cutlass()
224
+ print(f"[setup.py] CUTLASS: {cutlass_inc}")
225
+ if _has_sm100_headers(cutlass_inc):
226
+ print("[setup.py] CUTLASS has SM100 UMMA headers ✓")
227
+ else:
228
+ print("[setup.py] CUTLASS missing SM100 headers "
229
+ "(SM90 only, no tcgen05.mma support)")
230
+ except Exception as e:
231
+ print(f"[setup.py] WARNING: CUTLASS unavailable ({e}) — "
232
+ f"SM90/SM100 kernels will be skipped")
233
+
234
+ # group by (module, source)
235
+ groups: dict[tuple[str, str], list[str]] = {}
236
+ for sm in sms:
237
+ mod = _SM_MODULE.get(sm, "flash_diffusion_cuda")
238
+ src = _SM_SOURCES.get(sm, _SM_SOURCES["80"])
239
+ groups.setdefault((mod, src), []).append(sm)
240
+
241
+ for (mod, src), sm_list in groups.items():
242
+ if not os.path.exists(src):
243
+ print(f"[setup.py] SKIP {mod}: {src} not found in repo")
244
+ continue
245
+
246
+ # check CUTLASS requirement
247
+ needs_cutlass = any(sm in _SM_NEEDS_CUTLASS for sm in sm_list)
248
+ if needs_cutlass and cutlass_inc is None:
249
+ print(f"[setup.py] SKIP {mod} (SM{sm_list}): "
250
+ f"CUTLASS unavailable")
251
+ continue
252
+
253
+ # build include list
254
+ includes = cuda_includes[:]
255
+ if needs_cutlass:
256
+ includes = [cutlass_inc] + includes
257
+
258
+ # per-SM nvcc defines (deduplicated)
259
+ nvcc_extra = list({
260
+ d
261
+ for sm in sm_list
262
+ for d in _SM_NVCC_DEFINES.get(sm, [])
263
+ })
264
+
265
+ nvcc_flags = [
266
+ "-std=c++17", "-O3", "--use_fast_math",
267
+ "-U__CUDA_NO_HALF_OPERATORS__",
268
+ "-U__CUDA_NO_HALF_CONVERSIONS__",
269
+ "-U__CUDA_NO_HALF2_OPERATORS__",
270
+ "--expt-relaxed-constexpr",
271
+ "--expt-extended-lambda",
272
+ ] + [_gencode(sm) for sm in sm_list] + nvcc_extra
273
+
274
+ print(f"[setup.py] Building {mod} SM{sm_list} "
275
+ f"arch={[_SM_ARCH.get(s, s) for s in sm_list]}")
276
+
277
+ ext_modules.append(CUDAExtension(
278
+ name = mod,
279
+ sources = [src],
280
+ include_dirs = includes,
281
+ extra_compile_args = {
282
+ "cxx": ["-std=c++17", "-O3"],
283
+ "nvcc": nvcc_flags,
284
+ },
285
+ ))
286
+
287
+ cmdclass = {"build_ext": BuildExtension}
288
+ print(f"[setup.py] {len(ext_modules)} extension(s) configured.")
289
+
290
+ except ImportError as e:
291
+ print(f"[setup.py] torch not available, skipping CUDA: {e}")
292
+ except Exception as e:
293
+ print(f"[setup.py] CUDA setup error: {e}")
294
+ raise
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Package metadata
299
+ # ---------------------------------------------------------------------------
300
+
301
+ setup(
302
+ name = "flashdiffusion",
303
+ version = "0.1.0",
304
+ description = "Tiled memory-efficient diffusion maps eigensolver",
305
+ author = "Julio Candanedo",
306
+ author_email = "julio@sparsetrace.ai",
307
+ license = "MIT",
308
+ package_dir = {"": "src"},
309
+ packages = ["flashdiffusion"],
310
+ python_requires = ">=3.10",
311
+ install_requires = ["numpy>=1.24", "scipy>=1.10", "ninja"],
312
+ extras_require = {
313
+ "cuda": ["torch>=2.1", "ninja"],
314
+ "examples": ["matplotlib>=3.7", "scikit-learn>=1.3", "jupyter>=1.0"],
315
+ "dev": ["pytest>=7.0", "ruff>=0.3.0", "black>=24.0"],
316
+ },
317
+ ext_modules = ext_modules,
318
+ cmdclass = cmdclass,
319
+ )