flashdiffusion 0.2.0__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {flashdiffusion-0.2.0/src/flashdiffusion.egg-info → flashdiffusion-0.2.2}/PKG-INFO +3 -2
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/README.md +2 -1
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/pyproject.toml +4 -3
- flashdiffusion-0.2.2/src/flashdiffusion/__init__.py +13 -0
- flashdiffusion-0.2.2/src/flashdiffusion/bandwidth.py +273 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/flashdiffusion.py +51 -38
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/mfstar.py +156 -3
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2/src/flashdiffusion.egg-info}/PKG-INFO +3 -2
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion.egg-info/SOURCES.txt +8 -0
- flashdiffusion-0.2.2/src/manifolds/__init__.py +5 -0
- flashdiffusion-0.2.2/src/manifolds/manifold_demo.py +256 -0
- flashdiffusion-0.2.2/src/manifolds/manifolds.py +1524 -0
- flashdiffusion-0.2.2/src/manifolds/quintic.py +627 -0
- flashdiffusion-0.2.2/src/manifolds/scoring.py +145 -0
- flashdiffusion-0.2.2/src/manifolds/spectra.py +540 -0
- flashdiffusion-0.2.2/src/manifolds/spectral_api.py +98 -0
- flashdiffusion-0.2.2/tests/test_bandwidth.py +94 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/tests/test_simple.py +18 -51
- flashdiffusion-0.2.0/src/flashdiffusion/__init__.py +0 -10
- flashdiffusion-0.2.0/src/flashdiffusion/bandwidth.py +0 -173
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/LICENSE +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/setup.cfg +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/dense.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/energy.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/knn.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion/spectral.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion.egg-info/dependency_links.txt +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion.egg-info/requires.txt +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.2}/src/flashdiffusion.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flashdiffusion
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Matrix-free bandwidth optimization and diffusion geometry on the GPU
|
|
5
5
|
Author: Sparse Trace LLC
|
|
6
6
|
License: MIT
|
|
@@ -28,7 +28,8 @@ Requires-Dist: matplotlib; extra == "examples"
|
|
|
28
28
|
Dynamic: license-file
|
|
29
29
|
|
|
30
30
|
# Optimizing Diffusion-Map Bandwidth Using Dirichlet Energy
|
|
31
|
-
|
|
31
|
+
|
|
32
|
+
[](https://arxiv.org/pdf/2609.38198)
|
|
32
33
|
|
|
33
34
|
## 1. Motivation
|
|
34
35
|
|
|
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
|
|
|
5
5
|
|
|
6
6
|
[project]
|
|
7
7
|
name = "flashdiffusion"
|
|
8
|
-
version = "0.2.
|
|
8
|
+
version = "0.2.2"
|
|
9
9
|
description = "Matrix-free bandwidth optimization and diffusion geometry on the GPU"
|
|
10
10
|
readme = "README.md"
|
|
11
11
|
requires-python = ">=3.11,<3.14"
|
|
@@ -41,8 +41,9 @@ examples = ["matplotlib"]
|
|
|
41
41
|
Repository = "https://github.com/sparsetrace/FlashDiffusion"
|
|
42
42
|
|
|
43
43
|
[tool.setuptools]
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
# src/manifolds/ ships inside the wheel as flashdiffusion.manifolds; the folder stays where it is.
|
|
45
|
+
package-dir = {"" = "src", "flashdiffusion.manifolds" = "src/manifolds"}
|
|
46
|
+
packages = ["flashdiffusion", "flashdiffusion.manifolds"]
|
|
46
47
|
|
|
47
48
|
[tool.pytest.ini_options]
|
|
48
49
|
testpaths = ["tests"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# src/flashdiffusion/__init__.py
|
|
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"]
|
|
@@ -1,20 +1,19 @@
|
|
|
1
1
|
# src/flashdiffusion/flashdiffusion.py
|
|
2
2
|
"""The diffusion operator of a point cloud, its spectrum, and its calculus.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
Pf =
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
All returned arrays are JAX arrays.
|
|
4
|
+
dmap = FlashDiffusion(X) # bandwidth search, default beta_method="ladder"
|
|
5
|
+
Pf = dmap.markov(f) # usable immediately, no diagonalization
|
|
6
|
+
dmap.solve(n_modes=16) # harmonics
|
|
7
|
+
dmap.harmonics_, dmap.laplacian_
|
|
8
|
+
|
|
9
|
+
Pipeline:
|
|
10
|
+
construction beta search (or a given beta); nothing is diagonalized
|
|
11
|
+
solve() 'matrix_free': exact self-kNN list -> sparse kNN eigensolve
|
|
12
|
+
(a warm start) -> full-N eigensolve on the exact kernel via xgemm
|
|
13
|
+
'dense': full-N eigensolve on the stored kernel
|
|
14
|
+
|
|
15
|
+
Both solvers share one operator definition, one bandwidth criterion and one
|
|
16
|
+
normalization. All returned arrays are JAX arrays.
|
|
18
17
|
"""
|
|
19
18
|
from time import perf_counter
|
|
20
19
|
import math
|
|
@@ -30,12 +29,19 @@ class FlashDiffusion:
|
|
|
30
29
|
X : (N, D) array
|
|
31
30
|
Observations.
|
|
32
31
|
beta : float or None
|
|
33
|
-
Kernel bandwidth in exp(-beta |x - y|^2). If
|
|
34
|
-
|
|
32
|
+
Kernel bandwidth in exp(-beta |x - y|^2). If given, no search is run.
|
|
33
|
+
beta_method : {'ladder', 'mfstar', 'berryharlim', 'median'}
|
|
34
|
+
Bandwidth search when beta is None. 'ladder' (default) is MF* on nested
|
|
35
|
+
subsets, certified at full N; 'mfstar' is the same criterion searched at
|
|
36
|
+
full N throughout (slower, same answer); 'berryharlim' is the steepest
|
|
37
|
+
log-log slope of the kernel sum; 'median' is the median heuristic.
|
|
38
|
+
beta_options : dict or None
|
|
39
|
+
Extra keyword arguments for the search, e.g. {'min_size': 4096} for the
|
|
40
|
+
ladder or {'search': 'gradient'} for Berry-Harlim.
|
|
35
41
|
alpha : float
|
|
36
42
|
Density normalization exponent; alpha = 1 removes the sampling density.
|
|
37
43
|
seed : int
|
|
38
|
-
Seed for
|
|
44
|
+
Seed for the search and the eigensolver starting vectors.
|
|
39
45
|
backend : str
|
|
40
46
|
xgemm backend (matrix-free solver).
|
|
41
47
|
solver : {'auto', 'dense', 'matrix_free'}
|
|
@@ -46,20 +52,21 @@ class FlashDiffusion:
|
|
|
46
52
|
|
|
47
53
|
Attributes
|
|
48
54
|
----------
|
|
49
|
-
beta_ : float
|
|
50
|
-
bandwidth_ :
|
|
51
|
-
solver_ : str
|
|
52
|
-
degree_ : (N,) array
|
|
55
|
+
beta_ : float Bandwidth (selected or given).
|
|
56
|
+
bandwidth_ : BandwidthResult Search result (method, passes, details), or None.
|
|
57
|
+
solver_ : str 'dense' or 'matrix_free'.
|
|
58
|
+
degree_ : (N,) array Normalized degrees, after the first operator call.
|
|
53
59
|
|
|
54
|
-
After
|
|
60
|
+
After solve(n_modes):
|
|
55
61
|
eigenvalues_ : (n_modes,) Markov eigenvalues 1 > mu_1 >= mu_2 >= ...
|
|
56
62
|
laplacian_ : (n_modes,) 4 beta (1 - mu_k), Laplace-Beltrami estimates.
|
|
57
63
|
harmonics_ : (N, n_modes) Markov eigenfunctions (right eigenvectors).
|
|
58
64
|
info_ : dict Timings, solver counts, verification.
|
|
59
65
|
"""
|
|
60
66
|
|
|
61
|
-
def __init__(self, X, *, beta=None,
|
|
62
|
-
solver='auto', dense_max=32768,
|
|
67
|
+
def __init__(self, X, *, beta=None, beta_method='ladder', beta_options=None,
|
|
68
|
+
alpha=1.0, seed=7, backend='auto', solver='auto', dense_max=32768,
|
|
69
|
+
verbose=True):
|
|
63
70
|
X = np.ascontiguousarray(X, dtype=np.float32)
|
|
64
71
|
if X.ndim != 2 or len(X) < 4 or X.shape[1] < 1 or not np.isfinite(X).all():
|
|
65
72
|
raise ValueError('X must be a finite (N, D) array with N >= 4')
|
|
@@ -84,10 +91,11 @@ class FlashDiffusion:
|
|
|
84
91
|
from .dense import DenseKernel
|
|
85
92
|
self._dense = DenseKernel(X)
|
|
86
93
|
if beta is None:
|
|
87
|
-
from .
|
|
94
|
+
from .bandwidth import select_bandwidth
|
|
88
95
|
moments = self._dense.moments if self._dense is not None else None
|
|
89
|
-
self.bandwidth_ =
|
|
90
|
-
|
|
96
|
+
self.bandwidth_ = select_bandwidth(X, beta_method, alpha=self.alpha, seed=seed,
|
|
97
|
+
backend=backend, moments=moments,
|
|
98
|
+
**(beta_options or {}))
|
|
91
99
|
beta = self.bandwidth_.beta
|
|
92
100
|
else:
|
|
93
101
|
self.bandwidth_ = None
|
|
@@ -95,16 +103,18 @@ class FlashDiffusion:
|
|
|
95
103
|
if not math.isfinite(beta) or beta <= 0:
|
|
96
104
|
raise ValueError('beta must be finite and positive')
|
|
97
105
|
self.beta_ = beta
|
|
106
|
+
self.info_['beta_method'] = self.bandwidth_.method if self.bandwidth_ else 'given'
|
|
98
107
|
self.info_['beta_seconds'] = perf_counter() - start
|
|
108
|
+
self.info_['beta_passes'] = self.bandwidth_.passes if self.bandwidth_ else 0
|
|
99
109
|
if verbose:
|
|
100
|
-
|
|
101
|
-
|
|
110
|
+
print(f'[FlashDiffusion] beta={beta:.9g} ({self.info_["beta_method"]}, '
|
|
111
|
+
f'{self.solver_})', flush=True)
|
|
102
112
|
|
|
103
113
|
def __repr__(self):
|
|
104
|
-
|
|
114
|
+
solved = f', n_modes={self.n_modes_}' if self.n_modes_ else ''
|
|
105
115
|
return (f'FlashDiffusion(N={self.n}, D={self.X.shape[1]}, '
|
|
106
|
-
f'beta={self.beta_:.6g}, alpha={self.alpha:g}, '
|
|
107
|
-
f'solver={self.solver_!r}{
|
|
116
|
+
f'beta={self.beta_:.6g} ({self.info_["beta_method"]}), alpha={self.alpha:g}, '
|
|
117
|
+
f'solver={self.solver_!r}{solved})')
|
|
108
118
|
|
|
109
119
|
# ------------------------------------------------------------ operator
|
|
110
120
|
|
|
@@ -176,13 +186,14 @@ class FlashDiffusion:
|
|
|
176
186
|
free, _ = cp.cuda.runtime.memGetInfo()
|
|
177
187
|
return int(fraction * free * 8 / 20)
|
|
178
188
|
|
|
179
|
-
def
|
|
180
|
-
"""Compute the leading n_modes nonstationary harmonics.
|
|
189
|
+
def solve(self, n_modes=16, *, buffer=16, tol=1e-5, maxiter=1000, strict=True):
|
|
190
|
+
"""Compute the leading n_modes nonstationary harmonics at beta_.
|
|
181
191
|
|
|
182
|
-
|
|
183
|
-
start, then the exact
|
|
184
|
-
|
|
185
|
-
|
|
192
|
+
Matrix-free solver: exact self-kNN list, sparse kNN eigensolve as a warm
|
|
193
|
+
start, then the full-N eigensolve on the exact kernel via xgemm. Dense
|
|
194
|
+
solver: the full-N eigensolve on the stored kernel. Both solve
|
|
195
|
+
n_modes + buffer modes and return the leading n_modes, so degenerate
|
|
196
|
+
multiplets at the cutoff are not silently split.
|
|
186
197
|
"""
|
|
187
198
|
import cupy as cp
|
|
188
199
|
import jax
|
|
@@ -255,5 +266,7 @@ class FlashDiffusion:
|
|
|
255
266
|
f'converged={converged}', flush=True)
|
|
256
267
|
return self
|
|
257
268
|
|
|
269
|
+
fit = solve # backwards-compatible name
|
|
270
|
+
|
|
258
271
|
|
|
259
272
|
__all__ = ['FlashDiffusion']
|