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,217 @@
|
|
|
1
|
+
"""
|
|
2
|
+
flashdiffusion/eigensolver_gpu.py
|
|
3
|
+
==================================
|
|
4
|
+
GPU-resident Lanczos eigensolver for the diffusion map operator.
|
|
5
|
+
|
|
6
|
+
v1: Plain Lanczos with full re-orthogonalization (double MGS).
|
|
7
|
+
No restart — simpler, proven correct, already 10× faster than ARPACK
|
|
8
|
+
for our case because vectors stay on GPU with zero CPU transfer.
|
|
9
|
+
|
|
10
|
+
v2 (future): Thick-restart Lanczos for even fewer matvecs.
|
|
11
|
+
|
|
12
|
+
Algorithm
|
|
13
|
+
---------
|
|
14
|
+
1. Run n_iter Lanczos steps, all vectors on GPU
|
|
15
|
+
2. Full double-pass MGS re-orthogonalization per step
|
|
16
|
+
3. Solve small (n_iter × n_iter) tridiagonal on GPU via torch.linalg.eigh
|
|
17
|
+
4. Return top-k Ritz pairs
|
|
18
|
+
|
|
19
|
+
Why this beats ARPACK for fast GPU kernels
|
|
20
|
+
------------------------------------------
|
|
21
|
+
ARPACK runs on CPU and transfers v to GPU + back each iteration:
|
|
22
|
+
overhead per iter ≈ 2.35s (B200, N=200k)
|
|
23
|
+
50 iters × 2.35s = 117s overhead
|
|
24
|
+
|
|
25
|
+
GPU Lanczos: zero transfer, all computation on GPU:
|
|
26
|
+
50 iters × 0.0s transfer = 0s overhead
|
|
27
|
+
total ≈ 50 × 0.23s matvec + 50 × O(N×j) ortho ≈ 12s
|
|
28
|
+
|
|
29
|
+
References
|
|
30
|
+
----------
|
|
31
|
+
Golub & Van Loan, "Matrix Computations" 4th ed., Ch. 10
|
|
32
|
+
Parlett, "The Symmetric Eigenvalue Problem", SIAM 1998
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
import time
|
|
37
|
+
import numpy as np
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
import torch
|
|
41
|
+
_TORCH_AVAILABLE = True
|
|
42
|
+
except ImportError:
|
|
43
|
+
_TORCH_AVAILABLE = False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def gpu_lanczos(
|
|
47
|
+
matvec_fn,
|
|
48
|
+
N: int,
|
|
49
|
+
k: int = 8,
|
|
50
|
+
n_iter: int = None,
|
|
51
|
+
tol: float = 1e-6,
|
|
52
|
+
dtype = None,
|
|
53
|
+
device: str = "cuda",
|
|
54
|
+
verbose: bool = True,
|
|
55
|
+
q0=None
|
|
56
|
+
) -> tuple:
|
|
57
|
+
"""
|
|
58
|
+
Plain GPU Lanczos with full re-orthogonalization for top-k eigenvalues.
|
|
59
|
+
|
|
60
|
+
Parameters
|
|
61
|
+
----------
|
|
62
|
+
matvec_fn : callable
|
|
63
|
+
(N,) float32 GPU tensor → (N,) float32 GPU tensor.
|
|
64
|
+
Zero CPU transfer — vectors stay on GPU throughout.
|
|
65
|
+
N : int
|
|
66
|
+
Problem size.
|
|
67
|
+
k : int
|
|
68
|
+
Number of eigenvalues/vectors wanted (default 8).
|
|
69
|
+
n_iter : int
|
|
70
|
+
Number of Lanczos steps. Default: min(3*k + 20, N).
|
|
71
|
+
More iterations → better accuracy for clustered spectra.
|
|
72
|
+
Memory cost: N × n_iter × 4 bytes
|
|
73
|
+
(N=200k, n_iter=60: 200k × 60 × 4 = 48MB — trivial on any GPU)
|
|
74
|
+
tol : float
|
|
75
|
+
Not used in plain Lanczos (kept for API compatibility with ARPACK).
|
|
76
|
+
dtype : torch.dtype
|
|
77
|
+
Default float32. Use float64 for better orthogonality (2× memory).
|
|
78
|
+
device : str
|
|
79
|
+
CUDA device (default 'cuda').
|
|
80
|
+
verbose : bool
|
|
81
|
+
Print iteration info.
|
|
82
|
+
|
|
83
|
+
Returns
|
|
84
|
+
-------
|
|
85
|
+
vals : np.ndarray, shape (k,)
|
|
86
|
+
Top-k eigenvalues, descending order.
|
|
87
|
+
vecs : np.ndarray, shape (N, k)
|
|
88
|
+
Corresponding Ritz vectors (approximate eigenvectors).
|
|
89
|
+
"""
|
|
90
|
+
if not _TORCH_AVAILABLE:
|
|
91
|
+
raise ImportError("torch required for gpu_lanczos")
|
|
92
|
+
|
|
93
|
+
import torch
|
|
94
|
+
|
|
95
|
+
if dtype is None:
|
|
96
|
+
dtype = torch.float32
|
|
97
|
+
|
|
98
|
+
if n_iter is None:
|
|
99
|
+
#n_iter = min(6 * k + 40, N) # 88 for k=8 — converges for typical DMAP spectra
|
|
100
|
+
n_iter = min(6 * k + 20, N) # 68 for k=8 with warm start
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
t_start = time.perf_counter()
|
|
104
|
+
if verbose:
|
|
105
|
+
print(f"[gpu_lanczos] N={N} k={k} n_iter={n_iter} dtype={dtype}")
|
|
106
|
+
|
|
107
|
+
# ── allocate Lanczos basis on GPU ────────────────────────────────────────
|
|
108
|
+
# Q: (N, n_iter) — all basis vectors, needed for re-orthogonalization
|
|
109
|
+
# Memory: N=200k, n_iter=60, fp32 → 200k × 60 × 4 = 48MB
|
|
110
|
+
Q = torch.zeros(N, n_iter, dtype=dtype, device=device)
|
|
111
|
+
alphas = torch.zeros(n_iter, dtype=dtype, device=device)
|
|
112
|
+
betas = torch.zeros(n_iter, dtype=dtype, device=device)
|
|
113
|
+
|
|
114
|
+
# random normalised start vector
|
|
115
|
+
torch.manual_seed(42)
|
|
116
|
+
# correct warm start (exact leading eigenvector of P):
|
|
117
|
+
# pass D_alpha from state as optional q0
|
|
118
|
+
if q0 is not None:
|
|
119
|
+
q = q0.to(dtype=dtype)
|
|
120
|
+
else:
|
|
121
|
+
q = torch.ones(N, dtype=dtype, device=device)
|
|
122
|
+
q /= q.norm()
|
|
123
|
+
|
|
124
|
+
Q[:, 0] = q
|
|
125
|
+
|
|
126
|
+
j_final = n_iter # actual steps taken (may terminate early)
|
|
127
|
+
|
|
128
|
+
for j in range(n_iter):
|
|
129
|
+
# ── matvec — stays on GPU, zero transfer ─────────────────────────
|
|
130
|
+
z = matvec_fn(Q[:, j])
|
|
131
|
+
|
|
132
|
+
# ── three-term recurrence ─────────────────────────────────────────
|
|
133
|
+
alphas[j] = torch.dot(Q[:, j], z)
|
|
134
|
+
z = z - alphas[j] * Q[:, j]
|
|
135
|
+
if j > 0:
|
|
136
|
+
z = z - betas[j - 1] * Q[:, j - 1]
|
|
137
|
+
|
|
138
|
+
# ── full re-orthogonalization (double MGS) ────────────────────────
|
|
139
|
+
# Critical for clustered eigenvalues — single pass loses orthogonality
|
|
140
|
+
# Cost: 2 × j × N flops per step — tiny vs matvec cost O(N²)
|
|
141
|
+
if j > 0:
|
|
142
|
+
for _ in range(2):
|
|
143
|
+
# (j+1, N) × (N,) → (j+1,) coefficients
|
|
144
|
+
coeffs = Q[:, :j + 1].T @ z
|
|
145
|
+
z = z - Q[:, :j + 1] @ coeffs
|
|
146
|
+
|
|
147
|
+
# ── next basis vector ─────────────────────────────────────────────
|
|
148
|
+
beta_j = z.norm().item()
|
|
149
|
+
betas[j] = beta_j
|
|
150
|
+
|
|
151
|
+
if j < n_iter - 1:
|
|
152
|
+
if beta_j < 1e-12:
|
|
153
|
+
# lucky breakdown — Krylov space exhausted
|
|
154
|
+
j_final = j + 1
|
|
155
|
+
if verbose:
|
|
156
|
+
print(f" lucky breakdown at j={j}, β={beta_j:.2e}")
|
|
157
|
+
break
|
|
158
|
+
Q[:, j + 1] = z / beta_j
|
|
159
|
+
|
|
160
|
+
# ── solve tridiagonal eigenvalue problem ──────────────────────────────────
|
|
161
|
+
# T is (j_final × j_final) — tiny, solve on GPU
|
|
162
|
+
m = j_final
|
|
163
|
+
T = torch.diag(alphas[:m])
|
|
164
|
+
if m > 1:
|
|
165
|
+
T += torch.diag(betas[:m - 1], 1)
|
|
166
|
+
T += torch.diag(betas[:m - 1], -1)
|
|
167
|
+
|
|
168
|
+
# use numpy for robustness — T is tiny (60×60), CPU cost negligible
|
|
169
|
+
T_np = T.cpu().numpy().astype(np.float64)
|
|
170
|
+
evals_np, evecs_np = np.linalg.eigh(T_np) # ascending, numpy is robust
|
|
171
|
+
|
|
172
|
+
# sort descending, take top-k
|
|
173
|
+
idx = np.argsort(evals_np)[::-1][:k]
|
|
174
|
+
evals_k = evals_np[idx]
|
|
175
|
+
evecs_k = evecs_np[:, idx] # (m, k)
|
|
176
|
+
|
|
177
|
+
# ── Ritz vectors: Q[:, :m] @ evecs_k — GPU matmul ────────────────────────
|
|
178
|
+
# (N, m) × (m, k) → (N, k)
|
|
179
|
+
evecs_k_gpu = torch.from_numpy(evecs_k.astype(np.float32)).to(device)
|
|
180
|
+
ritz_vecs = Q[:, :m] @ evecs_k_gpu # (N, k)
|
|
181
|
+
|
|
182
|
+
elapsed = time.perf_counter() - t_start
|
|
183
|
+
if verbose:
|
|
184
|
+
print(f"[gpu_lanczos] {m} matvecs time={elapsed:.2f}s")
|
|
185
|
+
print(f" eigenvalues: {evals_k}")
|
|
186
|
+
|
|
187
|
+
return evals_k.astype(np.float64), ritz_vecs.cpu().numpy()
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def make_gpu_matvec(state, ext_module):
|
|
191
|
+
"""
|
|
192
|
+
Wrap a CUDAState + ext module into a pure GPU→GPU matvec callable.
|
|
193
|
+
No numpy, no CPU transfer — v stays on GPU throughout.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
state : CUDAState / CUDAStateSM100 / CUDAStateSM120 / etc.
|
|
198
|
+
Precomputed GPU state with X_fp16, sq_X, rscale, beta.
|
|
199
|
+
ext_module : compiled CUDA extension
|
|
200
|
+
Must expose .matvec(X_fp16, v, rscale, sq_X, beta) → GPU tensor.
|
|
201
|
+
|
|
202
|
+
Returns
|
|
203
|
+
-------
|
|
204
|
+
callable : (N,) float32 GPU tensor → (N,) float32 GPU tensor
|
|
205
|
+
"""
|
|
206
|
+
import torch
|
|
207
|
+
|
|
208
|
+
def matvec_gpu(v: torch.Tensor) -> torch.Tensor:
|
|
209
|
+
with torch.no_grad():
|
|
210
|
+
return ext_module.matvec(
|
|
211
|
+
state.X_fp16,
|
|
212
|
+
v,
|
|
213
|
+
state.rscale,
|
|
214
|
+
state.sq_X,
|
|
215
|
+
state.beta,
|
|
216
|
+
)
|
|
217
|
+
return matvec_gpu
|
flashdiffusion/kernel.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""
|
|
2
|
+
flashdiffusion/kernel.py
|
|
3
|
+
========================
|
|
4
|
+
The FlashDiffusion primitive.
|
|
5
|
+
|
|
6
|
+
FlashDiffusion(Q, K, V, beta, alpha, h, rscale_q, rscale_k, tile)
|
|
7
|
+
|
|
8
|
+
Computes, tile by tile, without materialising the O(N²) kernel matrix:
|
|
9
|
+
|
|
10
|
+
score(i,j) = beta * ||q_i - k_j||² (Gaussian, default)
|
|
11
|
+
| score_mod(q_i, k_j) (custom, future)
|
|
12
|
+
|
|
13
|
+
K(i,j) = exp(-score(i,j))
|
|
14
|
+
|
|
15
|
+
out_i = rscale_q_i · Σⱼ K(i,j) · rscale_k_j · (h_j · v_j)
|
|
16
|
+
|
|
17
|
+
where rscale_{q,k} encode the Coifman-Lafon normalisation and h is an
|
|
18
|
+
optional Doob potential (default h=1, no transform).
|
|
19
|
+
|
|
20
|
+
Modes
|
|
21
|
+
-----
|
|
22
|
+
DMAP matvec Q=K=X, rscale_q=rscale_k=rscale (precomputed by DiffusionMap)
|
|
23
|
+
AMAP matvec Q≠K, rscale_q/k separate (directed/NESS operator, DAC §3)
|
|
24
|
+
Doob mode h ≠ 1: h-transform of either operator (DAC §4, Theorem 5.1)
|
|
25
|
+
Prepass V=1 (or V=w), h=1: computes row sums D or D_alpha
|
|
26
|
+
|
|
27
|
+
Complexity
|
|
28
|
+
----------
|
|
29
|
+
Arithmetic : O(N_q · N_k · d) — same as dense, unavoidable
|
|
30
|
+
Memory : O((N_q + N_k) · tile) — never O(N²)
|
|
31
|
+
|
|
32
|
+
Current backend: NumPy (CPU reference).
|
|
33
|
+
CUDA target: CuTe SM90, fused prepass+matvec, tensor-core GEMM for
|
|
34
|
+
the xi·xj term, elementwise exp epilogue. No online
|
|
35
|
+
softmax needed — rscale is precomputed.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
import numpy as np
|
|
40
|
+
from typing import Optional
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
# Backend detection + dispatch
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
def _cuda_sm() -> int | None:
|
|
48
|
+
try:
|
|
49
|
+
import torch
|
|
50
|
+
if not torch.cuda.is_available():
|
|
51
|
+
return None
|
|
52
|
+
major, minor = torch.cuda.get_device_capability()
|
|
53
|
+
return major * 10 + minor
|
|
54
|
+
except ImportError:
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
# SM -> which kernel family to use
|
|
58
|
+
# SM120 (RTX 50xx) uses mma.sync (same family as SM80), not wgmma
|
|
59
|
+
_SM_BACKEND = {
|
|
60
|
+
80: "sm80", 86: "sm80", 89: "sm80",
|
|
61
|
+
90: "sm90",
|
|
62
|
+
100: "sm100",
|
|
63
|
+
103: "sm100",
|
|
64
|
+
120: "sm120", 121: "sm120",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
def _get_cuda_backend():
|
|
68
|
+
"""Return (precompute_fn, matvec_fn) or None if unavailable."""
|
|
69
|
+
sm = _cuda_sm()
|
|
70
|
+
if sm is None:
|
|
71
|
+
return None
|
|
72
|
+
backend_name = _SM_BACKEND.get(sm, "sm80")
|
|
73
|
+
|
|
74
|
+
if backend_name == "sm80":
|
|
75
|
+
try:
|
|
76
|
+
from .kernel_cuda import precompute_cuda, matvec_cuda
|
|
77
|
+
return precompute_cuda, matvec_cuda
|
|
78
|
+
except (ImportError, OSError):
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
elif backend_name == "sm90":
|
|
82
|
+
try:
|
|
83
|
+
from .kernel_cuda_sm90 import precompute_sm90, matvec_sm90
|
|
84
|
+
return precompute_sm90, matvec_sm90
|
|
85
|
+
except (ImportError, OSError):
|
|
86
|
+
try:
|
|
87
|
+
from .kernel_cuda import precompute_cuda, matvec_cuda
|
|
88
|
+
print("[FlashDiffusion] SM90 not found, falling back to SM80")
|
|
89
|
+
return precompute_cuda, matvec_cuda
|
|
90
|
+
except (ImportError, OSError):
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
elif backend_name == "sm100":
|
|
94
|
+
try:
|
|
95
|
+
from .kernel_cuda_sm100 import precompute_sm100, matvec_sm100
|
|
96
|
+
return precompute_sm100, matvec_sm100
|
|
97
|
+
except (ImportError, OSError):
|
|
98
|
+
try:
|
|
99
|
+
from .kernel_cuda import precompute_cuda, matvec_cuda
|
|
100
|
+
print("[FlashDiffusion] SM100 not found, falling back to SM80")
|
|
101
|
+
return precompute_cuda, matvec_cuda
|
|
102
|
+
except (ImportError, OSError):
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
elif backend_name == "sm120":
|
|
106
|
+
try:
|
|
107
|
+
from .kernel_cuda_sm120 import precompute_sm120, matvec_sm120
|
|
108
|
+
return precompute_sm120, matvec_sm120
|
|
109
|
+
except (ImportError, OSError):
|
|
110
|
+
try:
|
|
111
|
+
from .kernel_cuda import precompute_cuda, matvec_cuda
|
|
112
|
+
print("[FlashDiffusion] SM120 not found, falling back to SM80")
|
|
113
|
+
return precompute_cuda, matvec_cuda
|
|
114
|
+
except (ImportError, OSError):
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------------------
|
|
121
|
+
# Distance tile (shared by numpy prepass and matvec)
|
|
122
|
+
# ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def _dist2_tile(
|
|
125
|
+
Qi: np.ndarray, # (ti, d) float32
|
|
126
|
+
Kj: np.ndarray, # (tj, d) float32
|
|
127
|
+
sqi: np.ndarray, # (ti,)
|
|
128
|
+
sqk: np.ndarray, # (tj,)
|
|
129
|
+
) -> np.ndarray:
|
|
130
|
+
"""Squared Euclidean distances for one (Q-tile, K-tile) pair. float64 output."""
|
|
131
|
+
d2 = sqi[:, None] + sqk[None, :] - 2.0 * (Qi @ Kj.T)
|
|
132
|
+
np.maximum(d2, 0.0, out=d2)
|
|
133
|
+
return d2.astype(np.float64)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
# Prepass: row-sum reduction (used twice in precompute_normalization)
|
|
138
|
+
# ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
def prepass_rowsum(
|
|
141
|
+
Q: np.ndarray, # (N_q, d)
|
|
142
|
+
K: np.ndarray, # (N_k, d)
|
|
143
|
+
beta: float,
|
|
144
|
+
weights_k: Optional[np.ndarray] = None, # (N_k,) default = 1
|
|
145
|
+
tile: int = 512,
|
|
146
|
+
) -> np.ndarray:
|
|
147
|
+
"""
|
|
148
|
+
out_i = Σⱼ exp(-beta · ||q_i - k_j||²) · weights_k_j
|
|
149
|
+
|
|
150
|
+
Returns (N_q,) float64.
|
|
151
|
+
This is the primitive used for both normalisation passes:
|
|
152
|
+
pass 1: weights_k = np.ones(N) -> D_i (raw row sums)
|
|
153
|
+
pass 2: weights_k = w = D^{-α} -> D_alpha_i (before * w_i)
|
|
154
|
+
"""
|
|
155
|
+
N_q, d = Q.shape
|
|
156
|
+
N_k = K.shape[0]
|
|
157
|
+
if weights_k is None:
|
|
158
|
+
weights_k = np.ones(N_k, dtype=np.float64)
|
|
159
|
+
|
|
160
|
+
Q32 = Q.astype(np.float32)
|
|
161
|
+
K32 = K.astype(np.float32)
|
|
162
|
+
sqQ = (Q32 * Q32).sum(axis=1)
|
|
163
|
+
sqK = (K32 * K32).sum(axis=1)
|
|
164
|
+
|
|
165
|
+
out = np.zeros(N_q, dtype=np.float64)
|
|
166
|
+
|
|
167
|
+
for i0 in range(0, N_q, tile):
|
|
168
|
+
i1 = min(i0 + tile, N_q)
|
|
169
|
+
Qi = Q32[i0:i1]
|
|
170
|
+
sqi = sqQ[i0:i1]
|
|
171
|
+
|
|
172
|
+
for j0 in range(0, N_k, tile):
|
|
173
|
+
j1 = min(j0 + tile, N_k)
|
|
174
|
+
Kj = K32[j0:j1]
|
|
175
|
+
sqk = sqK[j0:j1]
|
|
176
|
+
|
|
177
|
+
d2 = _dist2_tile(Qi, Kj, sqi, sqk)
|
|
178
|
+
K_tile = np.exp(-beta * d2) # (ti, tj)
|
|
179
|
+
out[i0:i1] += K_tile @ weights_k[j0:j1]
|
|
180
|
+
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------------------
|
|
185
|
+
# Matvec: the core FlashDiffusion kernel
|
|
186
|
+
# ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
def FlashDiffusion(
|
|
189
|
+
Q: np.ndarray, # (N_q, d)
|
|
190
|
+
K: np.ndarray, # (N_k, d)
|
|
191
|
+
V: np.ndarray, # (N_k, r) r columns
|
|
192
|
+
beta: float,
|
|
193
|
+
rscale_q: Optional[np.ndarray] = None, # (N_q,) default = 1
|
|
194
|
+
rscale_k: Optional[np.ndarray] = None, # (N_k,) default = 1
|
|
195
|
+
h: Optional[np.ndarray] = None, # (N_k,) Doob potential
|
|
196
|
+
tile: int = 512,
|
|
197
|
+
coord_dtype = np.float32, # X tile dtype (f32/f16)
|
|
198
|
+
accum_dtype = np.float64, # accumulator dtype
|
|
199
|
+
) -> np.ndarray:
|
|
200
|
+
"""
|
|
201
|
+
FlashDiffusion numpy backend (CPU reference / fallback).
|
|
202
|
+
|
|
203
|
+
out_i = rscale_q_i · Σⱼ exp(-beta·||qᵢ-kⱼ||²) · rscale_k_j · h_j · v_j
|
|
204
|
+
|
|
205
|
+
Precision contract (numpy path)
|
|
206
|
+
--------------------------------
|
|
207
|
+
coord_dtype : X tile storage — fp32 default, fp16 for memory savings
|
|
208
|
+
accum_dtype : accumulator — fp64 for CPU reference correctness
|
|
209
|
+
GEMM (dot) : always fp32 regardless of coord_dtype (catastrophic
|
|
210
|
+
cancellation safety for dist² = sqi + sqj - 2*dot)
|
|
211
|
+
|
|
212
|
+
CUDA path (see kernel_cuda.py + csrc/flash_diffusion_sm80.cu)
|
|
213
|
+
---------------------------------------------------------------
|
|
214
|
+
coord_dtype -> fp16 smem (hardcoded in CUDA kernel)
|
|
215
|
+
GEMM -> mma.sync fp16->fp32 (SM80) / wgmma fp16->fp32 (SM90)
|
|
216
|
+
accum_dtype -> fp32 register tile
|
|
217
|
+
No online softmax: rscale precomputed, epilogue = scalar multiply.
|
|
218
|
+
No gradients: we compute the harmonic basis (eigenvectors), not a
|
|
219
|
+
differentiable layer. Use flexattention for the trained forward pass.
|
|
220
|
+
"""
|
|
221
|
+
N_q, d = Q.shape
|
|
222
|
+
N_k, r = V.shape
|
|
223
|
+
|
|
224
|
+
# GEMM always in fp32 for dist² numerical safety
|
|
225
|
+
Q32 = Q.astype(np.float32)
|
|
226
|
+
K32 = K.astype(np.float32)
|
|
227
|
+
sqQ = (Q32 * Q32).sum(axis=1)
|
|
228
|
+
sqK = (K32 * K32).sum(axis=1)
|
|
229
|
+
|
|
230
|
+
# pre-scale RHS: u_j = rscale_k_j · h_j · v_j
|
|
231
|
+
u = V.astype(accum_dtype)
|
|
232
|
+
if rscale_k is not None:
|
|
233
|
+
u = rscale_k[:, None] * u
|
|
234
|
+
if h is not None:
|
|
235
|
+
u = h[:, None] * u
|
|
236
|
+
|
|
237
|
+
out = np.zeros((N_q, r), dtype=accum_dtype)
|
|
238
|
+
|
|
239
|
+
for i0 in range(0, N_q, tile):
|
|
240
|
+
i1 = min(i0 + tile, N_q)
|
|
241
|
+
Qi = Q32[i0:i1]
|
|
242
|
+
sqi = sqQ[i0:i1]
|
|
243
|
+
|
|
244
|
+
for j0 in range(0, N_k, tile):
|
|
245
|
+
j1 = min(j0 + tile, N_k)
|
|
246
|
+
Kj = K32[j0:j1]
|
|
247
|
+
sqk = sqK[j0:j1]
|
|
248
|
+
|
|
249
|
+
d2 = _dist2_tile(Qi, Kj, sqi, sqk) # fp64
|
|
250
|
+
K_tile = np.exp(-beta * d2) # fp64 epilogue
|
|
251
|
+
out[i0:i1] += K_tile @ u[j0:j1]
|
|
252
|
+
|
|
253
|
+
if rscale_q is not None:
|
|
254
|
+
out *= rscale_q[:, None]
|
|
255
|
+
|
|
256
|
+
return out
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""
|
|
2
|
+
flashdiffusion/kernel_cuda.py
|
|
3
|
+
==============================
|
|
4
|
+
Python wrapper around flash_diffusion_cuda (the compiled SM80 extension).
|
|
5
|
+
|
|
6
|
+
This module is imported by kernel.py when CUDA is available.
|
|
7
|
+
It mirrors the numpy backend interface exactly — only the compute happens
|
|
8
|
+
on GPU. All tensors are managed here; the caller (kernel.py) stays backend-agnostic.
|
|
9
|
+
|
|
10
|
+
No gradients anywhere: we are computing eigenvectors of a fixed symmetric
|
|
11
|
+
operator (the harmonic basis). There is no training loop through this kernel.
|
|
12
|
+
If you later want to train a model that *uses* diffusion coordinates, that
|
|
13
|
+
goes through flexattention on the transformed coordinates, not through here.
|
|
14
|
+
|
|
15
|
+
Precision contract
|
|
16
|
+
------------------
|
|
17
|
+
X storage : fp16 (halved bandwidth vs fp32, safe because ||xi-xj||^2
|
|
18
|
+
is computed as sqi + sqj - 2*dot with fp32 accum)
|
|
19
|
+
dot product : fp32 (mma.sync fp16->fp32, avoids catastrophic cancellation)
|
|
20
|
+
exp, accum : fp32
|
|
21
|
+
rscale, D : fp32
|
|
22
|
+
Lanczos vec : fp32 on GPU, float64 orthogonalisation on CPU (unchanged)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
import numpy as np
|
|
27
|
+
import torch
|
|
28
|
+
from typing import Optional
|
|
29
|
+
|
|
30
|
+
# Lazy import — only loaded if CUDA is available and extension is compiled
|
|
31
|
+
_ext = None
|
|
32
|
+
|
|
33
|
+
def _load_ext():
|
|
34
|
+
global _ext
|
|
35
|
+
if _ext is None:
|
|
36
|
+
try:
|
|
37
|
+
import flash_diffusion_cuda as ext
|
|
38
|
+
_ext = ext
|
|
39
|
+
except ImportError as e:
|
|
40
|
+
raise ImportError(
|
|
41
|
+
"flash_diffusion_cuda extension not compiled. "
|
|
42
|
+
"Run: pip install -e '.[cuda]' or "
|
|
43
|
+
"cd csrc && nvcc -arch=sm_80 ... "
|
|
44
|
+
) from e
|
|
45
|
+
return _ext
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _to_gpu_fp16(X: np.ndarray) -> torch.Tensor:
|
|
49
|
+
"""Move coordinate array to GPU as fp16."""
|
|
50
|
+
return torch.from_numpy(np.asarray(X, dtype=np.float16)).cuda()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _to_gpu_fp32(x: np.ndarray) -> torch.Tensor:
|
|
54
|
+
return torch.from_numpy(np.asarray(x, dtype=np.float32)).cuda()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class CUDAState:
|
|
58
|
+
"""
|
|
59
|
+
Cached GPU tensors for a fixed (X, beta, alpha).
|
|
60
|
+
Analogous to the 'norm' dict in the numpy backend, but lives on GPU.
|
|
61
|
+
|
|
62
|
+
Built once by precompute_cuda(), reused across all Lanczos iterations.
|
|
63
|
+
The K-side tensors (X_fp16, sq_X, rscale) are the "KV cache" —
|
|
64
|
+
they never change while only the Lanczos vector v changes.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
X_fp16: torch.Tensor, # (N, d) fp16 on GPU
|
|
70
|
+
sq_X: torch.Tensor, # (N,) fp32 on GPU
|
|
71
|
+
rscale: torch.Tensor, # (N,) fp32 on GPU
|
|
72
|
+
D: torch.Tensor, # (N,) fp32 on GPU — raw row sums
|
|
73
|
+
D_alpha: torch.Tensor, # (N,) fp32 on GPU
|
|
74
|
+
beta: float,
|
|
75
|
+
alpha: float,
|
|
76
|
+
):
|
|
77
|
+
self.X_fp16 = X_fp16
|
|
78
|
+
self.sq_X = sq_X
|
|
79
|
+
self.rscale = rscale
|
|
80
|
+
self.D = D
|
|
81
|
+
self.D_alpha = D_alpha
|
|
82
|
+
self.beta = beta
|
|
83
|
+
self.alpha = alpha
|
|
84
|
+
self.N = X_fp16.shape[0]
|
|
85
|
+
self.d = X_fp16.shape[1]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def precompute_cuda(
|
|
89
|
+
X: np.ndarray,
|
|
90
|
+
beta: float,
|
|
91
|
+
alpha: float = 0.5,
|
|
92
|
+
) -> CUDAState:
|
|
93
|
+
"""
|
|
94
|
+
Two-pass precomputation on GPU. Mirrors precompute() in kernel.py.
|
|
95
|
+
|
|
96
|
+
Pass 1: D = K @ ones (raw row sums)
|
|
97
|
+
Pass 2: D_alpha = (K @ w) * w where w = D^{-alpha}
|
|
98
|
+
rscale = D_alpha^{-1/2} * w
|
|
99
|
+
|
|
100
|
+
Returns a CUDAState with all GPU tensors cached.
|
|
101
|
+
"""
|
|
102
|
+
ext = _load_ext()
|
|
103
|
+
N, d = X.shape
|
|
104
|
+
|
|
105
|
+
print(f"[precompute_cuda] N={N} d={d} beta={beta} alpha={alpha}")
|
|
106
|
+
|
|
107
|
+
# Move X to GPU as fp16 — stays there for the entire eigensolver run
|
|
108
|
+
X_fp16 = _to_gpu_fp16(X)
|
|
109
|
+
|
|
110
|
+
# Precompute sq norms (fp32, stays on GPU)
|
|
111
|
+
sq_X = ext.compute_sq_norms(X_fp16)
|
|
112
|
+
|
|
113
|
+
# Pass 1: D_i = Σ_j K(i,j) (w = 1)
|
|
114
|
+
w1 = torch.ones(N, dtype=torch.float32, device='cuda')
|
|
115
|
+
D = ext.prepass(X_fp16, w1, sq_X, beta)
|
|
116
|
+
|
|
117
|
+
# w = D^{-alpha}
|
|
118
|
+
w = D.pow(-alpha)
|
|
119
|
+
|
|
120
|
+
# Pass 2: D_alpha_i = (Σ_j K(i,j) * w_j) * w_i
|
|
121
|
+
D_alpha = ext.prepass(X_fp16, w, sq_X, beta) * w
|
|
122
|
+
|
|
123
|
+
# Combined diagonal
|
|
124
|
+
rscale = D_alpha.pow(-0.5) * w
|
|
125
|
+
|
|
126
|
+
return CUDAState(X_fp16, sq_X, rscale, D, D_alpha, beta, alpha)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def matvec_cuda(state: CUDAState, v: np.ndarray) -> np.ndarray:
|
|
130
|
+
"""
|
|
131
|
+
Apply M to a single Lanczos vector v (N,) float64.
|
|
132
|
+
|
|
133
|
+
v arrives as numpy float64 (from ARPACK).
|
|
134
|
+
We cast to float32, push to GPU, run the kernel, pull back as float64.
|
|
135
|
+
|
|
136
|
+
The CPU<->GPU transfer for v is O(N) floats — negligible vs O(N²) compute.
|
|
137
|
+
The K-side (X_fp16, sq_X, rscale) never moves — it's the KV cache.
|
|
138
|
+
"""
|
|
139
|
+
ext = _load_ext()
|
|
140
|
+
v_gpu = _to_gpu_fp32(v.astype(np.float32))
|
|
141
|
+
|
|
142
|
+
with torch.no_grad():
|
|
143
|
+
out_gpu = ext.matvec(
|
|
144
|
+
state.X_fp16,
|
|
145
|
+
v_gpu,
|
|
146
|
+
state.rscale,
|
|
147
|
+
state.sq_X,
|
|
148
|
+
state.beta,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Pull back to CPU as float64 for ARPACK orthogonalisation
|
|
152
|
+
return out_gpu.cpu().numpy().astype(np.float64)
|