flashdiffusion 0.1.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.
- flashdiffusion/ROPE.py +597 -0
- flashdiffusion/__init__.py +25 -0
- flashdiffusion/cdc.py +168 -0
- flashdiffusion/dmap.py +321 -0
- flashdiffusion/eigensolver.py +131 -0
- flashdiffusion/eigensolver_gpu.py +217 -0
- flashdiffusion/kernel.py +256 -0
- flashdiffusion/kernel_cuda.py +152 -0
- flashdiffusion/kernel_cuda_sm120.py +92 -0
- flashdiffusion/kernel_jit.py +125 -0
- flashdiffusion/utils.py +134 -0
- flashdiffusion-0.1.0.dist-info/METADATA +169 -0
- flashdiffusion-0.1.0.dist-info/RECORD +16 -0
- flashdiffusion-0.1.0.dist-info/WHEEL +5 -0
- flashdiffusion-0.1.0.dist-info/licenses/LICENSE +21 -0
- flashdiffusion-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
flashdiffusion/kernel_cuda_sm120.py
|
|
3
|
+
=====================================
|
|
4
|
+
Python wrapper for the SM120 (RTX 5090 / consumer Blackwell) kernel.
|
|
5
|
+
|
|
6
|
+
Differences from SM80 wrapper:
|
|
7
|
+
- module name: flash_diffusion_sm120
|
|
8
|
+
- larger tiles (128×128 vs 64×64) — same interface
|
|
9
|
+
- cp.async pipeline baked into kernel — no API change needed
|
|
10
|
+
- compile with -arch=sm_120
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
import numpy as np
|
|
15
|
+
import torch
|
|
16
|
+
from typing import Optional
|
|
17
|
+
|
|
18
|
+
_ext = None # injected by notebook or loaded via _load_ext()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _load_ext():
|
|
22
|
+
global _ext
|
|
23
|
+
if _ext is None:
|
|
24
|
+
try:
|
|
25
|
+
import flash_diffusion_sm120 as ext
|
|
26
|
+
_ext = ext
|
|
27
|
+
except ImportError as e:
|
|
28
|
+
raise ImportError(
|
|
29
|
+
"flash_diffusion_sm120 not compiled. Build with:\n"
|
|
30
|
+
" FLASHDIFFUSION_BUILD_CUDA=1 "
|
|
31
|
+
" TORCH_CUDA_ARCH_LIST='12.0' "
|
|
32
|
+
" pip install -e '.[cuda]'"
|
|
33
|
+
) from e
|
|
34
|
+
return _ext
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _to_gpu_fp16(X: np.ndarray) -> torch.Tensor:
|
|
38
|
+
return torch.from_numpy(np.asarray(X, dtype=np.float16)).cuda()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _to_gpu_fp32(x: np.ndarray) -> torch.Tensor:
|
|
42
|
+
return torch.from_numpy(np.asarray(x, dtype=np.float32)).cuda()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CUDAStateSM120:
|
|
46
|
+
"""Cached GPU tensors for SM120. Same interface as CUDAState (SM80)."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, X_fp16, sq_X, rscale, D, D_alpha, beta, alpha):
|
|
49
|
+
self.X_fp16 = X_fp16
|
|
50
|
+
self.sq_X = sq_X
|
|
51
|
+
self.rscale = rscale
|
|
52
|
+
self.D = D
|
|
53
|
+
self.D_alpha = D_alpha
|
|
54
|
+
self.beta = beta
|
|
55
|
+
self.alpha = alpha
|
|
56
|
+
self.N = X_fp16.shape[0]
|
|
57
|
+
self.d = X_fp16.shape[1]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def precompute_sm120(
|
|
61
|
+
X: np.ndarray,
|
|
62
|
+
beta: float,
|
|
63
|
+
alpha: float = 0.5,
|
|
64
|
+
) -> CUDAStateSM120:
|
|
65
|
+
"""Two-pass precomputation on SM120 GPU."""
|
|
66
|
+
import time
|
|
67
|
+
ext = _load_ext()
|
|
68
|
+
N, d = X.shape
|
|
69
|
+
print(f"[precompute_sm120] N={N} d={d} beta={beta} alpha={alpha}")
|
|
70
|
+
|
|
71
|
+
X_fp16 = _to_gpu_fp16(X)
|
|
72
|
+
sq_X = ext.compute_sq_norms(X_fp16)
|
|
73
|
+
|
|
74
|
+
t0 = time.perf_counter()
|
|
75
|
+
w1 = torch.ones(N, dtype=torch.float32, device='cuda')
|
|
76
|
+
D = ext.prepass(X_fp16, w1, sq_X, beta)
|
|
77
|
+
w = D.pow(-alpha)
|
|
78
|
+
D_alpha = ext.prepass(X_fp16, w, sq_X, beta) * w
|
|
79
|
+
rscale = D_alpha.pow(-0.5) * w
|
|
80
|
+
print(f" precompute done (SM120) in {time.perf_counter()-t0:.3f}s")
|
|
81
|
+
|
|
82
|
+
return CUDAStateSM120(X_fp16, sq_X, rscale, D, D_alpha, beta, alpha)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def matvec_sm120(state: CUDAStateSM120, v: np.ndarray) -> np.ndarray:
|
|
86
|
+
"""Apply M to Lanczos vector v. GPU→GPU, pull back to CPU for ARPACK."""
|
|
87
|
+
ext = _load_ext()
|
|
88
|
+
v_gpu = torch.from_numpy(v.astype(np.float32)).cuda()
|
|
89
|
+
with torch.no_grad():
|
|
90
|
+
out = ext.matvec(
|
|
91
|
+
state.X_fp16, v_gpu, state.rscale, state.sq_X, state.beta)
|
|
92
|
+
return out.cpu().numpy().astype(np.float64)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# src/flashdiffusion/kernel_jit.py
|
|
2
|
+
# Called on first import if no compiled .so found.
|
|
3
|
+
# Clones CUTLASS if needed, builds the right kernel for the current GPU.
|
|
4
|
+
|
|
5
|
+
import os, sys, glob, subprocess, sysconfig, time
|
|
6
|
+
import torch
|
|
7
|
+
from torch.utils.cpp_extension import load
|
|
8
|
+
|
|
9
|
+
_CACHE_DIR = os.path.expanduser('~/.cache/flashdiffusion')
|
|
10
|
+
|
|
11
|
+
def _build_kernel(sm, repo_root, verbose=False):
|
|
12
|
+
"""JIT-build the right kernel for this GPU. Returns loaded module."""
|
|
13
|
+
|
|
14
|
+
# fix 1: no local import of sys — use module-level sys
|
|
15
|
+
import importlib
|
|
16
|
+
if importlib.util.find_spec('ninja') is None:
|
|
17
|
+
subprocess.check_call(
|
|
18
|
+
[sys.executable, '-m', 'pip', 'install', '-q', 'ninja'])
|
|
19
|
+
|
|
20
|
+
_SOURCES = {
|
|
21
|
+
80: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
22
|
+
86: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
23
|
+
89: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
24
|
+
90: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
25
|
+
100: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
26
|
+
103: ('flash_diffusion_sm80.cu', 'sm_80', False, 'flash_diffusion_cuda'),
|
|
27
|
+
120: ('flash_diffusion_sm120.cu', 'sm_120', False, 'flash_diffusion_sm120'),
|
|
28
|
+
121: ('flash_diffusion_sm120.cu', 'sm_120', False, 'flash_diffusion_sm120'),
|
|
29
|
+
}
|
|
30
|
+
cu_file, arch, needs_cutlass, mod_name = _SOURCES.get(sm, _SOURCES[80]) # fix 2: keep mod_name from tuple
|
|
31
|
+
|
|
32
|
+
cu_path = os.path.join(repo_root, 'src', 'flashdiffusion', 'csrc', cu_file)
|
|
33
|
+
# removed: mod_name = os.path.splitext(cu_file)[0] ← this was overwriting the correct name
|
|
34
|
+
|
|
35
|
+
build_dir = os.path.join(_CACHE_DIR, f'sm{sm}')
|
|
36
|
+
os.makedirs(build_dir, exist_ok=True)
|
|
37
|
+
|
|
38
|
+
# check if already built
|
|
39
|
+
existing = glob.glob(f'{build_dir}/{mod_name}*.so')
|
|
40
|
+
if existing:
|
|
41
|
+
return _load_so(existing[0], mod_name)
|
|
42
|
+
|
|
43
|
+
# CUTLASS clone if needed
|
|
44
|
+
cutlass_inc = None
|
|
45
|
+
if needs_cutlass:
|
|
46
|
+
cutlass_inc = _ensure_cutlass(repo_root)
|
|
47
|
+
|
|
48
|
+
# gather nvidia includes
|
|
49
|
+
py = f'python{sys.version_info.major}.{sys.version_info.minor}'
|
|
50
|
+
nvidia_incs = glob.glob(
|
|
51
|
+
f'/usr/local/lib/{py}/site-packages/nvidia/*/include')
|
|
52
|
+
includes = ([cutlass_inc] if cutlass_inc else []) + \
|
|
53
|
+
[sysconfig.get_path('include')] + nvidia_incs
|
|
54
|
+
|
|
55
|
+
extra_defines = []
|
|
56
|
+
if sm in (90,):
|
|
57
|
+
extra_defines = ['-DCUTLASS_ARCH_MMA_SM90_SUPPORTED=1',
|
|
58
|
+
'-DCUTE_ARCH_MMA_SM90A_ENABLED=1']
|
|
59
|
+
if sm in (100, 103):
|
|
60
|
+
extra_defines = ['-DCUTLASS_ARCH_MMA_SM100_SUPPORTED=1',
|
|
61
|
+
'-DCUTE_ARCH_MMA_SM100A_ENABLED=1']
|
|
62
|
+
|
|
63
|
+
compute = arch.replace('sm_', 'compute_').rstrip('a')
|
|
64
|
+
|
|
65
|
+
print(f'[FlashDiffusion] Building SM{sm} kernel ({arch})...')
|
|
66
|
+
t0 = time.perf_counter()
|
|
67
|
+
load(
|
|
68
|
+
name = mod_name,
|
|
69
|
+
sources = [cu_path],
|
|
70
|
+
extra_include_paths = includes,
|
|
71
|
+
extra_cuda_cflags = [
|
|
72
|
+
f'-arch={arch}', '-std=c++17', '-O3', '--use_fast_math',
|
|
73
|
+
f'-gencode=arch={compute},code={arch}',
|
|
74
|
+
'-U__CUDA_NO_HALF_OPERATORS__',
|
|
75
|
+
'-U__CUDA_NO_HALF_CONVERSIONS__',
|
|
76
|
+
'-U__CUDA_NO_HALF2_OPERATORS__',
|
|
77
|
+
'--expt-relaxed-constexpr',
|
|
78
|
+
'--expt-extended-lambda',
|
|
79
|
+
] + extra_defines,
|
|
80
|
+
extra_cflags = ['-O3'],
|
|
81
|
+
build_directory = build_dir,
|
|
82
|
+
verbose = verbose,
|
|
83
|
+
)
|
|
84
|
+
print(f'[FlashDiffusion] Built in {time.perf_counter()-t0:.0f}s')
|
|
85
|
+
|
|
86
|
+
so = glob.glob(f'{build_dir}/*.so')[0]
|
|
87
|
+
return _load_so(so, mod_name)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _load_so(so_path, mod_name):
|
|
91
|
+
import importlib.util
|
|
92
|
+
spec = importlib.util.spec_from_file_location(mod_name, so_path)
|
|
93
|
+
mod = importlib.util.module_from_spec(spec)
|
|
94
|
+
spec.loader.exec_module(mod)
|
|
95
|
+
sys.modules[mod_name] = mod
|
|
96
|
+
|
|
97
|
+
# legacy names that kernel_cuda_*.py files expect to import
|
|
98
|
+
_LEGACY = {
|
|
99
|
+
'flash_diffusion_sm80': 'flash_diffusion_cuda', # kernel_cuda.py
|
|
100
|
+
'flash_diffusion_sm90': 'flash_diffusion_sm90', # kernel_cuda_sm90.py
|
|
101
|
+
'flash_diffusion_sm100': 'flash_diffusion_sm100', # kernel_cuda_sm100.py
|
|
102
|
+
'flash_diffusion_sm120': 'flash_diffusion_sm120', # kernel_cuda_sm120.py
|
|
103
|
+
}
|
|
104
|
+
for name in set([mod_name, _LEGACY.get(mod_name, mod_name)]):
|
|
105
|
+
sys.modules[name] = mod
|
|
106
|
+
|
|
107
|
+
return mod
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _ensure_cutlass(repo_root):
|
|
111
|
+
# prefer submodule → /tmp/cutlass_main → auto-clone
|
|
112
|
+
sub = os.path.join(repo_root, 'third_party', 'cutlass', 'include')
|
|
113
|
+
if os.path.exists(os.path.join(sub, 'cute', 'tensor.hpp')):
|
|
114
|
+
return sub
|
|
115
|
+
tmp = '/tmp/cutlass_main/include'
|
|
116
|
+
if os.path.exists(os.path.join(tmp, 'cute', 'tensor.hpp')):
|
|
117
|
+
return tmp
|
|
118
|
+
# auto-clone
|
|
119
|
+
target = '/tmp/cutlass_main'
|
|
120
|
+
print('[FlashDiffusion] Cloning CUTLASS (one-time, ~2min)...')
|
|
121
|
+
subprocess.check_call(
|
|
122
|
+
['git', 'clone', '--depth=1',
|
|
123
|
+
'https://github.com/NVIDIA/cutlass', target],
|
|
124
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
125
|
+
return tmp
|
flashdiffusion/utils.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
flashdiffusion/utils.py
|
|
3
|
+
=======================
|
|
4
|
+
Bandwidth selection, Nyström out-of-sample extension, dtype helpers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
import numpy as np
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# ---------------------------------------------------------------------------
|
|
13
|
+
# Bandwidth selection
|
|
14
|
+
# ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
def median_bandwidth(X: np.ndarray, subsample: int = 2000) -> float:
|
|
17
|
+
"""
|
|
18
|
+
Median heuristic for beta: beta = 1 / (2 * median(||xi-xj||²)).
|
|
19
|
+
|
|
20
|
+
Subsamples if N > subsample to keep cost O(subsample²).
|
|
21
|
+
"""
|
|
22
|
+
N = X.shape[0]
|
|
23
|
+
if N > subsample:
|
|
24
|
+
idx = np.random.default_rng(0).choice(N, subsample, replace=False)
|
|
25
|
+
X = X[idx]
|
|
26
|
+
sq = (X * X).sum(axis=1)
|
|
27
|
+
dist2 = np.maximum(sq[:, None] + sq[None, :] - 2 * X @ X.T, 0)
|
|
28
|
+
med = np.median(dist2[dist2 > 0])
|
|
29
|
+
return 1.0 / (2.0 * med) if med > 0 else 1.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def knn_bandwidth(X: np.ndarray, k: int = 7) -> np.ndarray:
|
|
33
|
+
"""
|
|
34
|
+
Self-tuning (Zelnik-Manor & Perona) per-point bandwidth.
|
|
35
|
+
|
|
36
|
+
sigma_i = ||xi - x_{i,k}|| (distance to k-th nearest neighbour)
|
|
37
|
+
|
|
38
|
+
For use with the anisotropic kernel:
|
|
39
|
+
K(i,j) = exp(-||xi-xj||² / (sigma_i * sigma_j))
|
|
40
|
+
|
|
41
|
+
Returns sigma (N,) — to use, replace beta * dist2 with dist2 / outer(sigma, sigma).
|
|
42
|
+
Note: this changes the kernel primitive; requires a modified prepass.
|
|
43
|
+
Currently returned as metadata for the caller to handle.
|
|
44
|
+
"""
|
|
45
|
+
N = X.shape[0]
|
|
46
|
+
sq = (X * X).sum(1)
|
|
47
|
+
dist2 = np.maximum(sq[:, None] + sq[None, :] - 2 * X @ X.T, 0)
|
|
48
|
+
# k-th nearest neighbour distance (excluding self at dist=0)
|
|
49
|
+
sorted_d = np.sort(dist2, axis=1)
|
|
50
|
+
sigma = np.sqrt(sorted_d[:, k]) # (N,)
|
|
51
|
+
sigma = np.maximum(sigma, 1e-10)
|
|
52
|
+
return sigma
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
# Nyström out-of-sample extension
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
def nystrom_extend(
|
|
60
|
+
dm, # fitted DiffusionMap
|
|
61
|
+
X_new: np.ndarray, # (M, d) new points
|
|
62
|
+
t: int = 1,
|
|
63
|
+
) -> np.ndarray:
|
|
64
|
+
"""
|
|
65
|
+
Nyström extension: embed new points using the training eigenvectors.
|
|
66
|
+
|
|
67
|
+
For a new point x*, the diffusion map coordinate is:
|
|
68
|
+
ψₖ(x*) = (1/λₖ) · Σᵢ p(x*, xᵢ) · φₖ(xᵢ)
|
|
69
|
+
|
|
70
|
+
where p(x*, xᵢ) = K_alpha(x*, xᵢ) / D_alpha(x*)
|
|
71
|
+
and φₖ are the (row-normalised) eigenvectors of P⁺.
|
|
72
|
+
|
|
73
|
+
This requires ONE tiled kernel pass for each new point batch,
|
|
74
|
+
reusing the precomputed rscale_ from the training set.
|
|
75
|
+
|
|
76
|
+
Returns
|
|
77
|
+
-------
|
|
78
|
+
coords : (M, n_components-1) diffusion coordinates for X_new
|
|
79
|
+
"""
|
|
80
|
+
from .kernel import FlashDiffusion, prepass_rowsum
|
|
81
|
+
|
|
82
|
+
if dm.eigenvalues_ is None:
|
|
83
|
+
raise RuntimeError("Call transform() on training data first.")
|
|
84
|
+
|
|
85
|
+
beta, alpha, tile = dm.beta, dm.alpha, dm.tile
|
|
86
|
+
X_train = dm.X_
|
|
87
|
+
N_train = X_train.shape[0]
|
|
88
|
+
rscale_k = dm.rscale_
|
|
89
|
+
|
|
90
|
+
# normalise new points against training set
|
|
91
|
+
# D_new_i = Σⱼ K(x*_i, x_j) · w_j (using training w)
|
|
92
|
+
w_train = dm.D_ ** (-alpha)
|
|
93
|
+
D_new = prepass_rowsum(X_new, X_train, beta,
|
|
94
|
+
weights_k=w_train, tile=tile)
|
|
95
|
+
w_new = D_new ** (-alpha)
|
|
96
|
+
|
|
97
|
+
# D_alpha_new_i = (Σⱼ K(x*_i, xⱼ) · w_j) · w_new_i (approx, Nyström)
|
|
98
|
+
D_alpha_new = D_new * w_new # approximate row sum in alpha-kernel
|
|
99
|
+
inv_Dalpha_new = w_new / D_alpha_new # = 1/D_new (since D_alpha_new = D_new*w)
|
|
100
|
+
|
|
101
|
+
# rscale for new query points
|
|
102
|
+
rscale_q_new = D_alpha_new ** (-0.5) * w_new
|
|
103
|
+
|
|
104
|
+
# get training eigenvectors in P⁺ basis
|
|
105
|
+
phi = dm.eigenvectors_ / dm.rscale_[:, None] # (N_train, k)
|
|
106
|
+
phi /= np.linalg.norm(phi, axis=0, keepdims=True)
|
|
107
|
+
|
|
108
|
+
# Nyström: apply K_alpha from new -> training
|
|
109
|
+
# coords_new_k = (1/λₖ) · Σⱼ K_alpha(x*_i, xⱼ) · φₖ(xⱼ)
|
|
110
|
+
coords_new = FlashDiffusion(
|
|
111
|
+
Q = X_new,
|
|
112
|
+
K = X_train,
|
|
113
|
+
V = phi[:, 1:], # drop trivial first eigvec
|
|
114
|
+
beta = beta,
|
|
115
|
+
rscale_q = rscale_q_new,
|
|
116
|
+
rscale_k = rscale_k,
|
|
117
|
+
tile = tile,
|
|
118
|
+
)
|
|
119
|
+
# scale by 1/λₖ and λₖ^t -> net scale λₖ^{t-1}
|
|
120
|
+
lam = dm.eigenvalues_[1:]
|
|
121
|
+
coords_new *= (lam ** (t - 1))[None, :]
|
|
122
|
+
|
|
123
|
+
return coords_new # (M, k-1)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ---------------------------------------------------------------------------
|
|
127
|
+
# dtype helpers
|
|
128
|
+
# ---------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
def to_f32(X: np.ndarray) -> np.ndarray:
|
|
131
|
+
return np.asarray(X, dtype=np.float32)
|
|
132
|
+
|
|
133
|
+
def to_f64(X: np.ndarray) -> np.ndarray:
|
|
134
|
+
return np.asarray(X, dtype=np.float64)
|
|
@@ -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,16 @@
|
|
|
1
|
+
flashdiffusion/ROPE.py,sha256=8rMdBvpAu30Bz1Bx09nNefryqAxACdqFX2clbVpfMF4,18581
|
|
2
|
+
flashdiffusion/__init__.py,sha256=WxtXnl8BkUrdkGoRk6eqUYTJPsGY6ZciXgGINnutr8A,768
|
|
3
|
+
flashdiffusion/cdc.py,sha256=efUwK-BWk5WS2I5uv0GdCXrcw26VxTXgfRr7rKN4LNs,5939
|
|
4
|
+
flashdiffusion/dmap.py,sha256=9Z-nq3Broygis-CJtY9Z_ki4QKdHn32PWuuRaqL01c8,12346
|
|
5
|
+
flashdiffusion/eigensolver.py,sha256=K4SH4WLtJ8kT_05kZOJZQNcPJQZQcuCUGyQNbUYYzXM,3986
|
|
6
|
+
flashdiffusion/eigensolver_gpu.py,sha256=OYYithUoU8vekvxy7hcXT9mnT_NmQQLZa9NLS8U7C_w,7701
|
|
7
|
+
flashdiffusion/kernel.py,sha256=bxKrxcEg-4VTdke9QPuF0SthE2Z3ppdhvpr56ARmIZI,8971
|
|
8
|
+
flashdiffusion/kernel_cuda.py,sha256=KHZukaIf_9YKVGv97q5fC0DQEIebFxt0L-UVfb0MNBM,4861
|
|
9
|
+
flashdiffusion/kernel_cuda_sm120.py,sha256=NNWfqdPhbgGRYIX0dh5VVE5lTUYVjJVIUJgMziorXTQ,2831
|
|
10
|
+
flashdiffusion/kernel_jit.py,sha256=DMQz_UkRNzTGS9X0usFTWGmHddMHQU1q0Wvywg8dUzU,5052
|
|
11
|
+
flashdiffusion/utils.py,sha256=2yyz-5BRuxVDteoD1jAa-_d97xFledF9f1FIokGMayo,4712
|
|
12
|
+
flashdiffusion-0.1.0.dist-info/licenses/LICENSE,sha256=YbHWZNWPD1wrm59kbXmefsOQJNxcbEsUrEfD0_6qyzw,1072
|
|
13
|
+
flashdiffusion-0.1.0.dist-info/METADATA,sha256=X0tKfLCwtDEOaK3z00Uajr5PdCS3RluFdfwz1F41zTM,6055
|
|
14
|
+
flashdiffusion-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
15
|
+
flashdiffusion-0.1.0.dist-info/top_level.txt,sha256=gqLX_QKzwtUq4XCFoC8CSUBQUZcaX60YOAl95Ug7iNw,15
|
|
16
|
+
flashdiffusion-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
flashdiffusion
|