flashdiffusion 0.1.2__py3-none-any.whl → 0.2.1__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/__init__.py +12 -27
- flashdiffusion/bandwidth.py +273 -0
- flashdiffusion/dense.py +87 -0
- flashdiffusion/energy.py +150 -0
- flashdiffusion/flashdiffusion.py +272 -0
- flashdiffusion/heuristics.py +88 -0
- flashdiffusion/knn.py +111 -0
- flashdiffusion/mfstar.py +356 -0
- flashdiffusion/spectral.py +134 -0
- flashdiffusion-0.2.1.dist-info/METADATA +303 -0
- flashdiffusion-0.2.1.dist-info/RECORD +14 -0
- {flashdiffusion-0.1.2.dist-info → flashdiffusion-0.2.1.dist-info}/WHEEL +1 -1
- {flashdiffusion-0.1.2.dist-info → flashdiffusion-0.2.1.dist-info}/licenses/LICENSE +1 -1
- flashdiffusion/ROPE.py +0 -597
- flashdiffusion/cdc.py +0 -168
- flashdiffusion/csrc/flash_diffusion_sm120.cu +0 -328
- flashdiffusion/csrc/flash_diffusion_sm120X.cu +0 -312
- flashdiffusion/csrc/flash_diffusion_sm120_.cu +0 -204
- flashdiffusion/csrc/flash_diffusion_sm80.cu +0 -324
- flashdiffusion/csrc/flash_diffusion_sm80X.cu +0 -293
- flashdiffusion/csrc/flash_diffusion_sm80_.cu +0 -238
- flashdiffusion/dmap.py +0 -321
- flashdiffusion/eigensolver.py +0 -131
- flashdiffusion/eigensolver_gpu.py +0 -217
- flashdiffusion/kernel.py +0 -256
- flashdiffusion/kernel_cuda.py +0 -154
- flashdiffusion/kernel_cuda_sm120.py +0 -94
- flashdiffusion/kernel_jit.py +0 -160
- flashdiffusion/utils.py +0 -134
- flashdiffusion-0.1.2.dist-info/METADATA +0 -169
- flashdiffusion-0.1.2.dist-info/RECORD +0 -22
- {flashdiffusion-0.1.2.dist-info → flashdiffusion-0.2.1.dist-info}/top_level.txt +0 -0
flashdiffusion/__init__.py
CHANGED
|
@@ -1,28 +1,13 @@
|
|
|
1
1
|
# src/flashdiffusion/__init__.py
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if not torch.cuda.is_available():
|
|
15
|
-
return
|
|
16
|
-
major, minor = torch.cuda.get_device_capability()
|
|
17
|
-
sm = major * 10 + minor
|
|
18
|
-
|
|
19
|
-
# package_dir = .../flashdiffusion/ (works for both pip and editable)
|
|
20
|
-
package_dir = os.path.dirname(os.path.abspath(__file__))
|
|
21
|
-
|
|
22
|
-
from .kernel_jit import _build_kernel
|
|
23
|
-
try:
|
|
24
|
-
_build_kernel(sm, package_dir)
|
|
25
|
-
except Exception as e:
|
|
26
|
-
print(f'[FlashDiffusion] JIT build failed ({e}), CPU fallback only')
|
|
27
|
-
|
|
28
|
-
_jit_init()
|
|
2
|
+
"""Matrix-free diffusion geometry: bandwidth, spectrum, and calculus."""
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
from .energy import energy, energy_jet, Jet
|
|
5
|
+
from .bandwidth import (METHODS, BandwidthResult, StationaryPoint, select_bandwidth,
|
|
6
|
+
select_bandwidth_berry_harlim, select_bandwidth_median)
|
|
7
|
+
from .mfstar import select_bandwidth_ladder, select_bandwidth_mfstar
|
|
8
|
+
from .flashdiffusion import FlashDiffusion
|
|
9
|
+
|
|
10
|
+
__version__ = version('flashdiffusion')
|
|
11
|
+
__all__ = ['FlashDiffusion', 'energy', 'energy_jet', 'Jet', 'METHODS', 'BandwidthResult',
|
|
12
|
+
'StationaryPoint', 'select_bandwidth', 'select_bandwidth_ladder',
|
|
13
|
+
'select_bandwidth_mfstar', 'select_bandwidth_berry_harlim', 'select_bandwidth_median']
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
# src/flashdiffusion/bandwidth.py
|
|
2
|
+
"""Bandwidth selection: one entry point for every method.
|
|
3
|
+
|
|
4
|
+
select_bandwidth(X) # 'ladder', the default
|
|
5
|
+
select_bandwidth(X, "mfstar") # MF* searched at full N throughout
|
|
6
|
+
select_bandwidth(X, "berryharlim") # steepest log-log slope of the kernel sum
|
|
7
|
+
select_bandwidth(X, "median") # median heuristic
|
|
8
|
+
|
|
9
|
+
Kernel convention: K = exp(-beta * |x - y|^2).
|
|
10
|
+
|
|
11
|
+
The methods target different scales. MF* ('ladder', 'mfstar') anchors on the
|
|
12
|
+
fission cliff, where the sample stops resolving the geometry, and returns the last
|
|
13
|
+
energy maximum before it: the finest resolvable scale. Berry-Harlim returns the
|
|
14
|
+
steepest point of log S(beta), S = 1^T K 1: on data with several scales (a Swiss
|
|
15
|
+
roll: a solid lump at coarse scale, a sheet at fine scale) that is the coarse one.
|
|
16
|
+
The median heuristic ignores the geometry and the sample size.
|
|
17
|
+
|
|
18
|
+
Every method returns a BandwidthResult with the same fields, so costs compare
|
|
19
|
+
directly: `passes` counts O(N^2) kernel passes at full N, with passes on ladder
|
|
20
|
+
subsets converted to full-N equivalents.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
import math
|
|
26
|
+
from time import perf_counter
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
|
|
30
|
+
METHODS = ("ladder", "mfstar", "berryharlim", "median")
|
|
31
|
+
DEFAULT_METHOD = "ladder"
|
|
32
|
+
PASSES_PER_JET = 7 # rbf_moments calls per MF* energy-jet evaluation
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class BandwidthResult:
|
|
37
|
+
beta: float
|
|
38
|
+
method: str # one of METHODS
|
|
39
|
+
passes: float # O(N^2) kernel passes, full-N equivalents
|
|
40
|
+
evaluations: int # objective evaluations at full N
|
|
41
|
+
seconds: float
|
|
42
|
+
details: object = None # LadderResult, MFStarResult, or a dict
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class StationaryPoint:
|
|
47
|
+
beta: float
|
|
48
|
+
energy: float # the objective: MF* energy E, or Berry-Harlim slope s
|
|
49
|
+
gradient: float
|
|
50
|
+
hessian: float
|
|
51
|
+
iterations: int
|
|
52
|
+
kind: str # 'maximum' or 'minimum'
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _canonical(method):
|
|
56
|
+
"""'berry_harlim', 'Berry-Harlim', 'BerryHarlim' -> 'berryharlim'."""
|
|
57
|
+
name = str(method).lower().replace("_", "").replace("-", "").replace(" ", "")
|
|
58
|
+
if name not in METHODS:
|
|
59
|
+
raise ValueError(f"Unknown beta_method {method!r}; choose from {METHODS}")
|
|
60
|
+
return name
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ----------------------------------------------------------------- shared Newton
|
|
64
|
+
|
|
65
|
+
def _newton(evaluate, lo, hi, *, tol, maxiter):
|
|
66
|
+
"""Root of g inside a log-beta bracket, where evaluate(t) -> (f, g, h) and h = g'.
|
|
67
|
+
|
|
68
|
+
Safeguarded Newton: steps that would leave the bracket become bisection.
|
|
69
|
+
Used for the MF* energy (f = E) and for the Berry-Harlim slope (f = s).
|
|
70
|
+
"""
|
|
71
|
+
_, ga, _ = evaluate(lo)
|
|
72
|
+
_, gb, _ = evaluate(hi)
|
|
73
|
+
if ga * gb > 0:
|
|
74
|
+
raise ValueError("Gradient does not change sign in the bracket")
|
|
75
|
+
t = 0.5 * (lo + hi)
|
|
76
|
+
for iteration in range(1, maxiter + 1):
|
|
77
|
+
f, g, h = evaluate(t)
|
|
78
|
+
if abs(g) <= tol:
|
|
79
|
+
return StationaryPoint(float(np.exp(t)), f, g, h, iteration,
|
|
80
|
+
"maximum" if h < 0 else "minimum")
|
|
81
|
+
if ga * g > 0:
|
|
82
|
+
lo, ga = t, g
|
|
83
|
+
else:
|
|
84
|
+
hi, gb = t, g
|
|
85
|
+
candidate = t - g / h if np.isfinite(h) and abs(h) > 1e-12 else np.nan
|
|
86
|
+
if not lo < candidate < hi:
|
|
87
|
+
candidate = 0.5 * (lo + hi)
|
|
88
|
+
t = candidate
|
|
89
|
+
raise RuntimeError("Newton iteration did not converge")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ----------------------------------------------------------------- median
|
|
93
|
+
|
|
94
|
+
def _median_d2(X, seed, pairs):
|
|
95
|
+
X = np.asarray(X)
|
|
96
|
+
rng = np.random.default_rng(seed)
|
|
97
|
+
i = rng.integers(len(X), size=pairs)
|
|
98
|
+
j = rng.integers(len(X), size=pairs)
|
|
99
|
+
keep = i != j
|
|
100
|
+
diff = X[i[keep]].astype(np.float64) - X[j[keep]].astype(np.float64)
|
|
101
|
+
return float(np.median(np.sum(diff * diff, axis=1)))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def select_bandwidth_median(X, *, seed=7, pairs=200_000):
|
|
105
|
+
"""Median heuristic: exp(-d^2 / 2 sigma^2), sigma^2 the median squared distance.
|
|
106
|
+
|
|
107
|
+
Estimated from `pairs` random pairs; no kernel passes.
|
|
108
|
+
"""
|
|
109
|
+
start = perf_counter()
|
|
110
|
+
d2 = _median_d2(X, seed, pairs)
|
|
111
|
+
return BandwidthResult(1.0 / (2.0 * d2), "median", 0, 0, perf_counter() - start,
|
|
112
|
+
dict(median_d2=d2, pairs=pairs))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ----------------------------------------------------------------- Berry-Harlim
|
|
116
|
+
|
|
117
|
+
def select_bandwidth_berry_harlim(X, *, seed=7, search="grid", tol=1e-6, maxiter=50,
|
|
118
|
+
grid=36, span=(-2.0, 5.0), max_steps=24,
|
|
119
|
+
pairs=200_000, backend="auto", moments=None):
|
|
120
|
+
"""Berry-Harlim: the beta where log S(beta) falls most steeply, S = 1^T K 1.
|
|
121
|
+
|
|
122
|
+
Criterion of Coifman et al. (2008) and Berry & Harlim (2016): the global
|
|
123
|
+
minimum of the log-log slope s, equivalently the largest dimension estimate
|
|
124
|
+
-2s. With t = log beta and kappa_1..3 the mean, variance and third central
|
|
125
|
+
moment of the squared distances under the kernel weights, all from one
|
|
126
|
+
rbf_moments pass of order 3 on the all-ones vector:
|
|
127
|
+
|
|
128
|
+
s = d log S / dt = -beta kappa_1
|
|
129
|
+
s' = s + beta^2 kappa_2
|
|
130
|
+
s'' = s' + 2 beta^2 kappa_2 - beta^3 kappa_3
|
|
131
|
+
|
|
132
|
+
search : "grid" (default; the published criterion) scans `grid` points over
|
|
133
|
+
`span` decades around the median bandwidth, refines every local minimum of
|
|
134
|
+
s by safeguarded Newton on s' = 0, and returns the steepest. "gradient"
|
|
135
|
+
walks from the median bandwidth to the NEAREST minimum of s; it is cheaper
|
|
136
|
+
but is not Berry-Harlim's criterion, so do not use it as the baseline.
|
|
137
|
+
moments : optional callable (v, beta, order) -> (N, order+1), as in energy_jet;
|
|
138
|
+
the dense solver passes one backed by its cached distance matrix.
|
|
139
|
+
|
|
140
|
+
details["minima"] lists every refined minimum as (beta, dimension estimate),
|
|
141
|
+
in increasing beta, so multiscale data show all of their steep regions.
|
|
142
|
+
"""
|
|
143
|
+
import jax.numpy as jnp
|
|
144
|
+
if search not in ("grid", "gradient"):
|
|
145
|
+
raise ValueError("search must be 'grid' or 'gradient'")
|
|
146
|
+
start = perf_counter()
|
|
147
|
+
x = jnp.asarray(X, dtype=jnp.float32)
|
|
148
|
+
x = x - x.mean(axis=0)
|
|
149
|
+
ones = jnp.ones(x.shape[0], dtype=jnp.float32)
|
|
150
|
+
if moments is None:
|
|
151
|
+
from xgemm import rbf_moments
|
|
152
|
+
|
|
153
|
+
def moments(v, beta, order):
|
|
154
|
+
return rbf_moments(x, v, beta=beta, order=order, backend=backend)
|
|
155
|
+
|
|
156
|
+
cache, trace = {}, []
|
|
157
|
+
|
|
158
|
+
def evaluate(t):
|
|
159
|
+
t = float(t)
|
|
160
|
+
if t not in cache:
|
|
161
|
+
beta = math.exp(t)
|
|
162
|
+
M = np.asarray(moments(ones, beta, 3), dtype=np.float64).sum(axis=0)
|
|
163
|
+
m1, m2, m3 = M[1] / M[0], M[2] / M[0], M[3] / M[0]
|
|
164
|
+
k2 = m2 - m1 * m1
|
|
165
|
+
k3 = m3 - 3 * m2 * m1 + 2 * m1 ** 3
|
|
166
|
+
s = -beta * m1
|
|
167
|
+
ds = s + beta ** 2 * k2
|
|
168
|
+
d2s = ds + 2 * beta ** 2 * k2 - beta ** 3 * k3
|
|
169
|
+
if not np.isfinite([s, ds, d2s]).all():
|
|
170
|
+
raise FloatingPointError(f"Nonfinite Berry-Harlim slope at beta={beta}")
|
|
171
|
+
cache[t] = (s, ds, d2s)
|
|
172
|
+
trace.append((beta, s, ds, d2s))
|
|
173
|
+
return cache[t]
|
|
174
|
+
|
|
175
|
+
def refine(lo, hi):
|
|
176
|
+
"""Newton on s' = 0 in [lo, hi]; the lower grid point if Newton cannot."""
|
|
177
|
+
try:
|
|
178
|
+
p = _newton(evaluate, lo, hi, tol=tol, maxiter=maxiter)
|
|
179
|
+
if p.kind == "minimum":
|
|
180
|
+
return p
|
|
181
|
+
except (RuntimeError, ValueError):
|
|
182
|
+
pass
|
|
183
|
+
t = min((lo, hi), key=lambda u: evaluate(u)[0])
|
|
184
|
+
s, ds, d2s = evaluate(t)
|
|
185
|
+
return StationaryPoint(math.exp(t), s, ds, d2s, 0, "minimum")
|
|
186
|
+
|
|
187
|
+
t0 = math.log(1.0 / _median_d2(X, seed, pairs))
|
|
188
|
+
points = []
|
|
189
|
+
if search == "grid":
|
|
190
|
+
ts = t0 + math.log(10) * np.linspace(span[0], span[1], grid)
|
|
191
|
+
s = np.array([evaluate(t)[0] for t in ts])
|
|
192
|
+
k_best = int(np.argmin(s))
|
|
193
|
+
if k_best == 0 or k_best == grid - 1:
|
|
194
|
+
raise RuntimeError("Berry-Harlim: steepest point at the edge of the grid; "
|
|
195
|
+
"widen span")
|
|
196
|
+
for k in range(1, grid - 1):
|
|
197
|
+
if s[k] <= s[k - 1] and s[k] <= s[k + 1]: # local minimum of the slope
|
|
198
|
+
lo, hi = (ts[k - 1], ts[k]) if evaluate(ts[k])[1] > 0 else (ts[k], ts[k + 1])
|
|
199
|
+
points.append(refine(lo, hi))
|
|
200
|
+
else:
|
|
201
|
+
t, step = t0, math.log(2.0)
|
|
202
|
+
direction = 1.0 if evaluate(t)[1] < 0 else -1.0 # walk downhill in s
|
|
203
|
+
for _ in range(max_steps):
|
|
204
|
+
nxt = t + direction * step
|
|
205
|
+
if np.sign(evaluate(nxt)[1]) != np.sign(evaluate(t)[1]):
|
|
206
|
+
points.append(refine(min(t, nxt), max(t, nxt)))
|
|
207
|
+
break
|
|
208
|
+
t, step = nxt, 2.0 * step
|
|
209
|
+
if not points:
|
|
210
|
+
raise RuntimeError("Berry-Harlim: no minimum of the slope found from the "
|
|
211
|
+
"median bandwidth")
|
|
212
|
+
|
|
213
|
+
# Neighbouring grid minima on a flat stretch can refine to the same point.
|
|
214
|
+
points.sort(key=lambda p: p.beta)
|
|
215
|
+
unique = []
|
|
216
|
+
for p in points:
|
|
217
|
+
if unique and abs(math.log(p.beta / unique[-1].beta)) < 1e-3:
|
|
218
|
+
if p.energy < unique[-1].energy:
|
|
219
|
+
unique[-1] = p
|
|
220
|
+
else:
|
|
221
|
+
unique.append(p)
|
|
222
|
+
|
|
223
|
+
best = min(unique, key=lambda p: p.energy) # steepest = lowest s
|
|
224
|
+
return BandwidthResult(
|
|
225
|
+
best.beta, "berryharlim", len(cache), len(cache), perf_counter() - start,
|
|
226
|
+
dict(dimension=-2.0 * best.energy, slope=best.energy, curvature=best.hessian,
|
|
227
|
+
search=search, minima=tuple((p.beta, -2.0 * p.energy) for p in unique),
|
|
228
|
+
newton_iterations=best.iterations, trace=tuple(trace)))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ----------------------------------------------------------------- entry point
|
|
232
|
+
|
|
233
|
+
def select_bandwidth(X, method=DEFAULT_METHOD, *, alpha=1.0, seed=7, backend="auto",
|
|
234
|
+
moments=None, **options):
|
|
235
|
+
"""Select the kernel bandwidth beta for X.
|
|
236
|
+
|
|
237
|
+
method : 'ladder' (default), 'mfstar', 'berryharlim' or 'median'; spelling
|
|
238
|
+
variants such as 'berry_harlim' are accepted.
|
|
239
|
+
'ladder' MF* on nested subsets X[::s], certified at full N.
|
|
240
|
+
'mfstar' the same criterion searched at full N throughout; slower,
|
|
241
|
+
same answer, kept for comparison.
|
|
242
|
+
'berryharlim' steepest log-log slope of the kernel sum.
|
|
243
|
+
'median' median heuristic.
|
|
244
|
+
alpha : density normalization; used by the MF* methods only (the other two
|
|
245
|
+
look at the raw kernel).
|
|
246
|
+
moments : optional dense-kernel moment callable (FlashDiffusion's dense solver).
|
|
247
|
+
options : passed to the method, e.g. min_size / ratio for 'ladder',
|
|
248
|
+
search='gradient' for 'berryharlim', pairs for 'median'.
|
|
249
|
+
"""
|
|
250
|
+
method = _canonical(method)
|
|
251
|
+
if method == "median":
|
|
252
|
+
return select_bandwidth_median(X, seed=seed, **options)
|
|
253
|
+
if method == "berryharlim":
|
|
254
|
+
return select_bandwidth_berry_harlim(X, seed=seed, backend=backend,
|
|
255
|
+
moments=moments, **options)
|
|
256
|
+
|
|
257
|
+
from .mfstar import select_bandwidth_ladder, select_bandwidth_mfstar
|
|
258
|
+
start = perf_counter()
|
|
259
|
+
if method == "ladder":
|
|
260
|
+
r = select_bandwidth_ladder(X, alpha, seed=seed, backend=backend,
|
|
261
|
+
moments=moments, **options)
|
|
262
|
+
return BandwidthResult(r.beta, "ladder",
|
|
263
|
+
r.full_equivalent_evaluations * PASSES_PER_JET,
|
|
264
|
+
r.evaluations, perf_counter() - start, r)
|
|
265
|
+
r = select_bandwidth_mfstar(X, alpha, seed=seed, backend=backend, moments=moments,
|
|
266
|
+
**options)
|
|
267
|
+
return BandwidthResult(r.beta, "mfstar", r.evaluations * PASSES_PER_JET,
|
|
268
|
+
r.evaluations, perf_counter() - start, r)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
__all__ = ["METHODS", "DEFAULT_METHOD", "PASSES_PER_JET", "BandwidthResult",
|
|
272
|
+
"StationaryPoint", "select_bandwidth", "select_bandwidth_median",
|
|
273
|
+
"select_bandwidth_berry_harlim"]
|
flashdiffusion/dense.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# src/flashdiffusion/dense.py
|
|
2
|
+
"""Dense GPU kernel for moderate N: cached squared distances, exact moments.
|
|
3
|
+
|
|
4
|
+
Memory is O(N^2): one float32 distance matrix H, plus K(beta) once the
|
|
5
|
+
eigensolver needs it. The energy jet, MF*, normalization and eigensolver are
|
|
6
|
+
shared with the matrix-free path; only the kernel moments come from here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def dense_fits(n, *, fraction=0.5):
|
|
11
|
+
"""True if H and K (two float32 N x N arrays) fit in the free device memory."""
|
|
12
|
+
import cupy as cp
|
|
13
|
+
free, _ = cp.cuda.runtime.memGetInfo()
|
|
14
|
+
return 2 * 4 * n * n <= fraction * free
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _to_cupy(v):
|
|
18
|
+
import cupy as cp
|
|
19
|
+
import jax
|
|
20
|
+
jax.block_until_ready(v)
|
|
21
|
+
return cp.ascontiguousarray(cp.from_dlpack(v), dtype=cp.float32)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _to_jax(a):
|
|
25
|
+
import cupy as cp
|
|
26
|
+
import jax
|
|
27
|
+
cp.cuda.Device().synchronize()
|
|
28
|
+
return jax.dlpack.from_dlpack(cp.ascontiguousarray(a))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DenseKernel:
|
|
32
|
+
"""Gaussian kernel exp(-beta H) with H = squared distances, cached on the GPU."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, X, *, tile=2048):
|
|
35
|
+
import cupy as cp
|
|
36
|
+
x = cp.asarray(X, dtype=cp.float64)
|
|
37
|
+
x -= x.mean(axis=0)
|
|
38
|
+
n = int(x.shape[0])
|
|
39
|
+
q = cp.sum(x * x, axis=1)
|
|
40
|
+
H = cp.empty((n, n), dtype=cp.float32)
|
|
41
|
+
for i in range(0, n, tile):
|
|
42
|
+
j = min(i + tile, n)
|
|
43
|
+
block = q[i:j, None] + q[None, :] - 2.0 * (x[i:j] @ x.T)
|
|
44
|
+
H[i:j] = cp.maximum(block, 0.0).astype(cp.float32)
|
|
45
|
+
cp.fill_diagonal(H, 0.0)
|
|
46
|
+
self.H, self.n, self.tile = H, n, int(tile)
|
|
47
|
+
self._beta = self._K = None
|
|
48
|
+
|
|
49
|
+
def moments(self, v, beta, order):
|
|
50
|
+
"""(K ⊙ H^p) @ v for p = 0..order, the same layout as xgemm.rbf_moments."""
|
|
51
|
+
import cupy as cp
|
|
52
|
+
v = _to_cupy(v)
|
|
53
|
+
b = cp.float32(beta)
|
|
54
|
+
out = cp.empty((self.n, order + 1), dtype=cp.float32)
|
|
55
|
+
for i in range(0, self.n, self.tile):
|
|
56
|
+
j = min(i + self.tile, self.n)
|
|
57
|
+
h = self.H[i:j]
|
|
58
|
+
w = cp.exp(-b * h)
|
|
59
|
+
out[i:j, 0] = w @ v
|
|
60
|
+
for p in range(1, order + 1):
|
|
61
|
+
w *= h
|
|
62
|
+
out[i:j, p] = w @ v
|
|
63
|
+
return _to_jax(out)
|
|
64
|
+
|
|
65
|
+
def operator(self, beta):
|
|
66
|
+
"""CuPy matvec v -> K(beta) v; K is materialized once per beta."""
|
|
67
|
+
import cupy as cp
|
|
68
|
+
beta = float(beta)
|
|
69
|
+
if self._beta != beta:
|
|
70
|
+
self._K = None
|
|
71
|
+
cp.get_default_memory_pool().free_all_blocks()
|
|
72
|
+
K = cp.empty_like(self.H)
|
|
73
|
+
b = cp.float32(beta)
|
|
74
|
+
for i in range(0, self.n, self.tile):
|
|
75
|
+
j = min(i + self.tile, self.n)
|
|
76
|
+
K[i:j] = cp.exp(-b * self.H[i:j])
|
|
77
|
+
self._K, self._beta = K, beta
|
|
78
|
+
K = self._K
|
|
79
|
+
return lambda v: K @ cp.asarray(v, dtype=cp.float32)
|
|
80
|
+
|
|
81
|
+
def jax_kernel(self, beta):
|
|
82
|
+
"""JAX-in, JAX-out version of operator(), for markov() and the calculus."""
|
|
83
|
+
apply = self.operator(beta)
|
|
84
|
+
return lambda v: _to_jax(apply(_to_cupy(v)))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
__all__ = ['DenseKernel', 'dense_fits']
|
flashdiffusion/energy.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# src/flashdiffusion/energy.py
|
|
2
|
+
"""Matrix-free Dirichlet energy and analytic log-bandwidth derivatives."""
|
|
3
|
+
|
|
4
|
+
from typing import NamedTuple
|
|
5
|
+
import jax.numpy as jnp
|
|
6
|
+
from xgemm import rbf_moments
|
|
7
|
+
|
|
8
|
+
class Jet(NamedTuple):
|
|
9
|
+
value: object
|
|
10
|
+
gradient: object
|
|
11
|
+
hessian: object
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _mul(a, b):
|
|
15
|
+
return Jet(
|
|
16
|
+
a.value * b.value,
|
|
17
|
+
a.gradient * b.value + a.value * b.gradient,
|
|
18
|
+
a.hessian * b.value
|
|
19
|
+
+ 2 * a.gradient * b.gradient
|
|
20
|
+
+ a.value * b.hessian,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _pow(a, p):
|
|
25
|
+
if p == 0:
|
|
26
|
+
return Jet(
|
|
27
|
+
jnp.ones_like(a.value),
|
|
28
|
+
jnp.zeros_like(a.value),
|
|
29
|
+
jnp.zeros_like(a.value),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
y = a.value ** p
|
|
33
|
+
g = a.gradient / a.value
|
|
34
|
+
h = a.hessian / a.value
|
|
35
|
+
|
|
36
|
+
return Jet(
|
|
37
|
+
y,
|
|
38
|
+
p * y * g,
|
|
39
|
+
p * y * (h + (p - 1) * g**2),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _sum(a):
|
|
44
|
+
return Jet(*(jnp.sum(x) for x in a))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _apply(mom, v, beta):
|
|
48
|
+
"""Second-order jet of K(beta) @ v(beta)."""
|
|
49
|
+
|
|
50
|
+
m0, m1, m2 = mom(v.value, 2)
|
|
51
|
+
g0, g1 = mom(v.gradient, 1)
|
|
52
|
+
h0, = mom(v.hessian, 0)
|
|
53
|
+
|
|
54
|
+
return Jet(
|
|
55
|
+
m0,
|
|
56
|
+
g0 - beta * m1,
|
|
57
|
+
h0
|
|
58
|
+
- 2 * beta * g1
|
|
59
|
+
+ beta**2 * m2
|
|
60
|
+
- beta * m1,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def energy_jet(X, beta, alpha=1.0, *, backend="auto", moments=None):
|
|
65
|
+
"""Return energy, gradient and Hessian with respect to log(beta).
|
|
66
|
+
|
|
67
|
+
moments : callable (v, beta, order) -> (N, order+1) array, optional
|
|
68
|
+
Supplies the kernel moments (K ⊙ H^p) v for p = 0..order. Defaults to
|
|
69
|
+
the matrix-free xgemm.rbf_moments; the dense solver passes
|
|
70
|
+
DenseKernel.moments, which reads a cached distance matrix.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
X = jnp.asarray(X, dtype=jnp.float32)
|
|
74
|
+
|
|
75
|
+
if X.ndim != 2 or X.shape[0] < 2:
|
|
76
|
+
raise ValueError("Expected X of shape (N, D), N >= 2")
|
|
77
|
+
|
|
78
|
+
beta = float(beta)
|
|
79
|
+
|
|
80
|
+
if not 0 < beta < float("inf"):
|
|
81
|
+
raise ValueError("beta must be finite and positive")
|
|
82
|
+
|
|
83
|
+
# Center coordinates without changing pairwise distances.
|
|
84
|
+
X = X - X.mean(axis=0)
|
|
85
|
+
|
|
86
|
+
def mom(v, order):
|
|
87
|
+
if moments is not None:
|
|
88
|
+
M = moments(v, beta, order)
|
|
89
|
+
else:
|
|
90
|
+
M = rbf_moments(X, v, beta=beta, order=order, backend=backend)
|
|
91
|
+
return tuple(M[:, p] for p in range(order + 1))
|
|
92
|
+
|
|
93
|
+
ones = jnp.ones(X.shape[0], dtype=X.dtype)
|
|
94
|
+
|
|
95
|
+
# q = K @ 1
|
|
96
|
+
q0, q1, q2 = mom(ones, 2)
|
|
97
|
+
|
|
98
|
+
q = Jet(
|
|
99
|
+
q0,
|
|
100
|
+
-beta * q1,
|
|
101
|
+
beta**2 * q2 - beta * q1,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Density normalization.
|
|
105
|
+
a = _pow(q, -alpha)
|
|
106
|
+
|
|
107
|
+
# d = a * (K @ a)
|
|
108
|
+
if alpha == 0:
|
|
109
|
+
d = q
|
|
110
|
+
else:
|
|
111
|
+
d = _mul(a, _apply(mom, a, beta))
|
|
112
|
+
|
|
113
|
+
# S = diag(s) K diag(s)
|
|
114
|
+
s = _mul(a, _pow(d, -0.5))
|
|
115
|
+
|
|
116
|
+
# Moments for the energy numerator and denominator.
|
|
117
|
+
m = mom(s.value, 3)
|
|
118
|
+
g = mom(s.gradient, 2)
|
|
119
|
+
h = mom(s.hessian, 1)
|
|
120
|
+
|
|
121
|
+
def moment_jet(p):
|
|
122
|
+
return Jet(
|
|
123
|
+
m[p],
|
|
124
|
+
g[p] - beta * m[p + 1],
|
|
125
|
+
h[p]
|
|
126
|
+
- 2 * beta * g[p + 1]
|
|
127
|
+
+ beta**2 * m[p + 2]
|
|
128
|
+
- beta * m[p + 1],
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
F0 = _sum(_mul(s, moment_jet(0)))
|
|
132
|
+
F1 = _sum(_mul(s, moment_jet(1)))
|
|
133
|
+
|
|
134
|
+
beta_jet = Jet(beta, beta, beta)
|
|
135
|
+
|
|
136
|
+
# E = 2 beta F1 / F0
|
|
137
|
+
result = _mul(
|
|
138
|
+
_mul(beta_jet, F1),
|
|
139
|
+
_pow(F0, -1),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
return Jet(*(2 * x for x in result))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def energy(X, beta, alpha=1.0, *, backend="auto", moments=None):
|
|
146
|
+
"""Return the coordinate Dirichlet energy."""
|
|
147
|
+
|
|
148
|
+
return energy_jet(
|
|
149
|
+
X, beta, alpha, backend=backend, moments=moments
|
|
150
|
+
).value
|