flashdiffusion 0.2.0__tar.gz → 0.2.1__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.1}/PKG-INFO +3 -2
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/README.md +2 -1
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/pyproject.toml +1 -1
- flashdiffusion-0.2.1/src/flashdiffusion/__init__.py +13 -0
- flashdiffusion-0.2.1/src/flashdiffusion/bandwidth.py +273 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/flashdiffusion.py +51 -38
- flashdiffusion-0.2.1/src/flashdiffusion/heuristics.py +88 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/mfstar.py +156 -3
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1/src/flashdiffusion.egg-info}/PKG-INFO +3 -2
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion.egg-info/SOURCES.txt +2 -0
- flashdiffusion-0.2.1/tests/test_bandwidth.py +94 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/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.1}/LICENSE +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/setup.cfg +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/dense.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/energy.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/knn.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion/spectral.py +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion.egg-info/dependency_links.txt +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion.egg-info/requires.txt +0 -0
- {flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/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.1
|
|
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.1"
|
|
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"
|
|
@@ -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']
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# src/flashdiffusion/heuristics.py
|
|
2
|
+
"""Standard bandwidth heuristics, for comparison with MF*.
|
|
3
|
+
|
|
4
|
+
Kernel convention: K = exp(-beta * d^2).
|
|
5
|
+
|
|
6
|
+
select_bandwidth_median(X) median heuristic, from sampled pairs
|
|
7
|
+
select_bandwidth_berry_harlim(X) exact Berry-Harlim (Coifman et al.) criterion
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
import math
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class HeuristicResult:
|
|
19
|
+
beta: float
|
|
20
|
+
passes: int # O(N^2) kernel passes used (0 for sampled-pair methods)
|
|
21
|
+
method: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _median_d2(X, seed, pairs):
|
|
25
|
+
X = np.asarray(X)
|
|
26
|
+
rng = np.random.default_rng(seed)
|
|
27
|
+
i = rng.integers(len(X), size=pairs)
|
|
28
|
+
j = rng.integers(len(X), size=pairs)
|
|
29
|
+
keep = i != j
|
|
30
|
+
diff = X[i[keep]].astype(np.float64) - X[j[keep]].astype(np.float64)
|
|
31
|
+
return float(np.median(np.sum(diff * diff, axis=1)))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def select_bandwidth_median(X, *, seed=7, pairs=200_000):
|
|
35
|
+
"""Median heuristic: exp(-d^2 / 2 sigma^2) with sigma^2 = median squared distance."""
|
|
36
|
+
return HeuristicResult(1.0 / (2.0 * _median_d2(X, seed, pairs)), 0, "median")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def select_bandwidth_berry_harlim(X, *, seed=7, grid=36, span=(-2.0, 5.0), xtol=1e-4,
|
|
40
|
+
pairs=200_000, backend="auto"):
|
|
41
|
+
"""Exact Berry-Harlim: the beta extremizing d log S / d log beta, S = 1^T K 1.
|
|
42
|
+
|
|
43
|
+
With t = log beta and M_p = 1^T (K o H^p) 1 from one rbf_moments pass
|
|
44
|
+
(orders 0-2 on the all-ones vector):
|
|
45
|
+
s(t) = -beta M1 / S
|
|
46
|
+
s'(t) = s + beta^2 (M2/S - (M1/S)^2)
|
|
47
|
+
The slope's minimum (the largest dimension estimate, -2s) is located on a log
|
|
48
|
+
grid scaled by the median squared distance, then refined by Brent on s' = 0.
|
|
49
|
+
Every evaluation is exact at full N.
|
|
50
|
+
"""
|
|
51
|
+
import jax.numpy as jnp
|
|
52
|
+
from scipy.optimize import brentq
|
|
53
|
+
from xgemm import rbf_moments
|
|
54
|
+
|
|
55
|
+
x = jnp.asarray(X, dtype=jnp.float32)
|
|
56
|
+
x = x - x.mean(axis=0)
|
|
57
|
+
ones = jnp.ones(x.shape[0], dtype=jnp.float32)
|
|
58
|
+
cache = {}
|
|
59
|
+
|
|
60
|
+
def stats(t):
|
|
61
|
+
t = float(t)
|
|
62
|
+
if t not in cache:
|
|
63
|
+
beta = math.exp(t)
|
|
64
|
+
M = np.asarray(rbf_moments(x, ones, beta=beta, order=2, backend=backend),
|
|
65
|
+
dtype=np.float64).sum(axis=0)
|
|
66
|
+
S, M1, M2 = M
|
|
67
|
+
s = -beta * M1 / S
|
|
68
|
+
cache[t] = (s, s + beta**2 * (M2 / S - (M1 / S) ** 2))
|
|
69
|
+
return cache[t]
|
|
70
|
+
|
|
71
|
+
t_mid = math.log(1.0 / _median_d2(X, seed, pairs))
|
|
72
|
+
ts = t_mid + math.log(10) * np.linspace(span[0], span[1], grid)
|
|
73
|
+
slopes = [stats(t)[0] for t in ts]
|
|
74
|
+
k = int(np.argmin(slopes))
|
|
75
|
+
if k == 0 or k == grid - 1:
|
|
76
|
+
raise RuntimeError("Berry-Harlim slope extremum at the edge of the grid; widen span")
|
|
77
|
+
derivs = {i: stats(ts[i])[1] for i in (k - 1, k, k + 1)}
|
|
78
|
+
if derivs[k - 1] < 0 < derivs[k]:
|
|
79
|
+
a, b = ts[k - 1], ts[k]
|
|
80
|
+
elif derivs[k] < 0 < derivs[k + 1]:
|
|
81
|
+
a, b = ts[k], ts[k + 1]
|
|
82
|
+
else:
|
|
83
|
+
return HeuristicResult(math.exp(ts[k]), len(cache), "berry_harlim")
|
|
84
|
+
t_star = brentq(lambda t: stats(t)[1], a, b, xtol=xtol)
|
|
85
|
+
return HeuristicResult(math.exp(t_star), len(cache), "berry_harlim")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
__all__ = ["HeuristicResult", "select_bandwidth_median", "select_bandwidth_berry_harlim"]
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# src/flashdiffusion/mfstar.py
|
|
2
|
-
"""
|
|
2
|
+
"""Bandwidth selection from the MF* cliff: full search and N-ladder."""
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from dataclasses import dataclass
|
|
@@ -79,7 +79,7 @@ def select_bandwidth_mfstar(X, alpha=1.0, *, n_probes=64, seed=7,
|
|
|
79
79
|
backend="auto", tol=1e-5, maxiter=50,
|
|
80
80
|
cliff_steps=12, peak_steps=80,
|
|
81
81
|
cliff_factor=1.8, peak_factor=1.35,
|
|
82
|
-
moments=None):
|
|
82
|
+
cliff_xtol=1e-3, moments=None):
|
|
83
83
|
"""Experimental MF* search; no user-supplied absolute beta interval.
|
|
84
84
|
|
|
85
85
|
Finds a descending inflection near a sampled-neighbor seed, then walks
|
|
@@ -87,6 +87,7 @@ def select_bandwidth_mfstar(X, alpha=1.0, *, n_probes=64, seed=7,
|
|
|
87
87
|
Neither the principal-cliff identification nor absence of missed narrow
|
|
88
88
|
peaks is guaranteed for arbitrary heterogeneous data.
|
|
89
89
|
|
|
90
|
+
cliff_xtol : tolerance in log beta for the cliff inflection (an anchor only).
|
|
90
91
|
moments : optional kernel-moment callable, passed to energy_jet
|
|
91
92
|
(the dense solver supplies one backed by a cached distance matrix).
|
|
92
93
|
"""
|
|
@@ -151,7 +152,7 @@ def select_bandwidth_mfstar(X, alpha=1.0, *, n_probes=64, seed=7,
|
|
|
151
152
|
raise RuntimeError("No descending cliff inflection bracketed near MF* seed")
|
|
152
153
|
a,b = min(found, key=lambda ab: abs(0.5*(ab[0]+ab[1])-anchor))
|
|
153
154
|
# Solve h(t)=0 by Brent: Newton here would require a third derivative.
|
|
154
|
-
tc = float(brentq(lambda t: evaluate(t)[2], a,b, xtol=
|
|
155
|
+
tc = float(brentq(lambda t: evaluate(t)[2], a,b, xtol=cliff_xtol, maxiter=maxiter))
|
|
155
156
|
E,g,h = evaluate(tc)
|
|
156
157
|
if not (E > 0 and g < 0):
|
|
157
158
|
raise RuntimeError("Candidate cliff is not a descending inflection")
|
|
@@ -201,3 +202,155 @@ def select_bandwidth_mfstar(X, alpha=1.0, *, n_probes=64, seed=7,
|
|
|
201
202
|
seed_evaluations=seed_count, cliff_evaluations=cliff_count,
|
|
202
203
|
peak_evaluations=len(cache)-seed_count-cliff_count, trace=tuple(trace),
|
|
203
204
|
peak_method=peak_method)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# --------------------------------------------------------------------- ladder
|
|
208
|
+
|
|
209
|
+
@dataclass(frozen=True)
|
|
210
|
+
class Rung:
|
|
211
|
+
n: int
|
|
212
|
+
stride: int
|
|
213
|
+
beta: float
|
|
214
|
+
energy: float
|
|
215
|
+
evaluations: int
|
|
216
|
+
method: str # "search", "newton", "bounded", or "fallback: <reason>"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@dataclass(frozen=True)
|
|
220
|
+
class LadderResult:
|
|
221
|
+
beta: float
|
|
222
|
+
energy: float
|
|
223
|
+
peak: StationaryPoint
|
|
224
|
+
rungs: tuple
|
|
225
|
+
base: MFStarResult # full search on the smallest rung
|
|
226
|
+
evaluations: int # energy-jet evaluations at full N
|
|
227
|
+
full_equivalent_evaluations: float # sum over rungs of evaluations * (n / N)^2
|
|
228
|
+
trace: tuple # (stride, stage, beta, E, g, h)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class _LadderFallback(Exception):
|
|
232
|
+
pass
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def ladder_strides(n, *, min_size=4096, ratio=8):
|
|
236
|
+
"""Strides for nested subsets X[::s], smallest subset first; [1] means one rung.
|
|
237
|
+
|
|
238
|
+
The smallest rung has at least min_size points; each rung is ratio times
|
|
239
|
+
larger, ending at the full data.
|
|
240
|
+
"""
|
|
241
|
+
if not isinstance(ratio, int) or ratio < 2:
|
|
242
|
+
raise ValueError("ratio must be an integer >= 2")
|
|
243
|
+
if n < min_size * ratio:
|
|
244
|
+
return [1]
|
|
245
|
+
k = int(math.floor(math.log(n / min_size) / math.log(ratio)))
|
|
246
|
+
return [ratio**j for j in range(k, -1, -1)]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def select_bandwidth_ladder(X, alpha=1.0, *, min_size=4096, ratio=8, shuffle=False,
|
|
250
|
+
seed=7, backend="auto", tol=1e-5, maxiter=50,
|
|
251
|
+
cliff_xtol=0.05, max_doublings=8, moments=None, **search):
|
|
252
|
+
"""MF* via a ladder of nested strided subsets, certified at full N.
|
|
253
|
+
|
|
254
|
+
The smallest subset gets the full MF* search. Each larger subset starts from
|
|
255
|
+
the previous peak, which beta* exceeds because beta* grows with N: it checks
|
|
256
|
+
g > 0 there, expands to the right until g < 0 (capped at the previous cliff
|
|
257
|
+
scaled by (n_j / n_{j-1})^(2/d)), and solves g = 0 by Newton in that bracket.
|
|
258
|
+
Any failed check falls back to the full search at that rung.
|
|
259
|
+
|
|
260
|
+
The final evaluations are on the full, unshuffled data, so the result is a
|
|
261
|
+
full-N stationary point at the same tolerance as select_bandwidth_mfstar.
|
|
262
|
+
|
|
263
|
+
moments : full-data moment callable (dense solver); used for the final rung only.
|
|
264
|
+
search : extra keyword arguments for select_bandwidth_mfstar (n_probes, ...).
|
|
265
|
+
"""
|
|
266
|
+
X = np.asarray(X, dtype=np.float32)
|
|
267
|
+
n = len(X)
|
|
268
|
+
strides = ladder_strides(n, min_size=min_size, ratio=ratio)
|
|
269
|
+
Xp = X[np.random.default_rng(seed).permutation(n)] if shuffle else X
|
|
270
|
+
|
|
271
|
+
def subset(s):
|
|
272
|
+
return X if s == 1 else Xp[::s]
|
|
273
|
+
|
|
274
|
+
def full_search(Xs, last):
|
|
275
|
+
return select_bandwidth_mfstar(Xs, alpha, seed=seed, backend=backend, tol=tol,
|
|
276
|
+
maxiter=maxiter, cliff_xtol=cliff_xtol,
|
|
277
|
+
moments=moments if last else None, **search)
|
|
278
|
+
|
|
279
|
+
trace, rungs = [], []
|
|
280
|
+
|
|
281
|
+
# Rung 0: full search on the smallest subset.
|
|
282
|
+
s0 = strides[0]
|
|
283
|
+
X0 = subset(s0)
|
|
284
|
+
base = full_search(X0, last=(len(strides) == 1))
|
|
285
|
+
trace += [(s0, *row) for row in base.trace]
|
|
286
|
+
rungs.append(Rung(len(X0), s0, base.beta, base.energy, base.evaluations, "search"))
|
|
287
|
+
full_eq = base.evaluations * (len(X0) / n) ** 2
|
|
288
|
+
peak = base.peak
|
|
289
|
+
beta_cliff = base.beta_cliff
|
|
290
|
+
d = max(base.dimension_energy, 0.5)
|
|
291
|
+
n_prev = len(X0)
|
|
292
|
+
last_evals = base.evaluations if len(strides) == 1 else 0
|
|
293
|
+
|
|
294
|
+
for s in strides[1:]:
|
|
295
|
+
Xs = subset(s)
|
|
296
|
+
m = len(Xs)
|
|
297
|
+
last = s == 1
|
|
298
|
+
mom = moments if last else None
|
|
299
|
+
cache = {}
|
|
300
|
+
|
|
301
|
+
def evaluate(t, Xs=Xs, mom=mom, cache=cache, s=s):
|
|
302
|
+
t = float(t)
|
|
303
|
+
if t not in cache:
|
|
304
|
+
beta = math.exp(t)
|
|
305
|
+
values = tuple(float(v) for v in energy_jet(Xs, beta, alpha, backend=backend,
|
|
306
|
+
moments=mom))
|
|
307
|
+
if not np.isfinite(values).all():
|
|
308
|
+
raise FloatingPointError(f"Nonfinite energy jet at beta={beta}")
|
|
309
|
+
cache[t] = values
|
|
310
|
+
trace.append((s, "ladder", beta, *values))
|
|
311
|
+
return cache[t]
|
|
312
|
+
|
|
313
|
+
beta_cliff *= (m / n_prev) ** (2.0 / d)
|
|
314
|
+
t_cap = math.log(beta_cliff)
|
|
315
|
+
t_lo = math.log(peak.beta)
|
|
316
|
+
try:
|
|
317
|
+
if evaluate(t_lo)[1] <= 0:
|
|
318
|
+
raise _LadderFallback("gradient not positive at previous peak")
|
|
319
|
+
t_hi, step = None, math.log(2.0)
|
|
320
|
+
for _ in range(max_doublings):
|
|
321
|
+
cand = min(t_lo + step, t_cap)
|
|
322
|
+
if cand <= t_lo:
|
|
323
|
+
raise _LadderFallback("previous peak beyond cliff estimate")
|
|
324
|
+
if evaluate(cand)[1] < 0:
|
|
325
|
+
t_hi = cand
|
|
326
|
+
break
|
|
327
|
+
if cand >= t_cap:
|
|
328
|
+
raise _LadderFallback("no descent before cliff estimate")
|
|
329
|
+
t_lo, step = cand, 2 * step
|
|
330
|
+
if t_hi is None:
|
|
331
|
+
raise _LadderFallback("upper bound not found")
|
|
332
|
+
try:
|
|
333
|
+
new_peak, method = _newton(evaluate, t_lo, t_hi, tol=tol, maxiter=maxiter), "newton"
|
|
334
|
+
except RuntimeError:
|
|
335
|
+
new_peak = None
|
|
336
|
+
if new_peak is None or new_peak.hessian >= 0:
|
|
337
|
+
new_peak, method = _bounded_peak(evaluate, t_lo, t_hi), "bounded"
|
|
338
|
+
evals = len(cache)
|
|
339
|
+
except _LadderFallback as why:
|
|
340
|
+
res = full_search(Xs, last)
|
|
341
|
+
trace += [(s, *row) for row in res.trace]
|
|
342
|
+
new_peak, method = res.peak, f"fallback: {why}"
|
|
343
|
+
evals = len(cache) + res.evaluations
|
|
344
|
+
beta_cliff = res.beta_cliff
|
|
345
|
+
d = max(res.dimension_energy, 0.5)
|
|
346
|
+
|
|
347
|
+
peak = new_peak
|
|
348
|
+
rungs.append(Rung(m, s, peak.beta, peak.energy, evals, method))
|
|
349
|
+
full_eq += evals * (m / n) ** 2
|
|
350
|
+
n_prev = m
|
|
351
|
+
if last:
|
|
352
|
+
last_evals = evals
|
|
353
|
+
|
|
354
|
+
return LadderResult(beta=peak.beta, energy=peak.energy, peak=peak, rungs=tuple(rungs),
|
|
355
|
+
base=base, evaluations=last_evals,
|
|
356
|
+
full_equivalent_evaluations=full_eq, trace=tuple(trace))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flashdiffusion
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
|
@@ -6,6 +6,7 @@ src/flashdiffusion/bandwidth.py
|
|
|
6
6
|
src/flashdiffusion/dense.py
|
|
7
7
|
src/flashdiffusion/energy.py
|
|
8
8
|
src/flashdiffusion/flashdiffusion.py
|
|
9
|
+
src/flashdiffusion/heuristics.py
|
|
9
10
|
src/flashdiffusion/knn.py
|
|
10
11
|
src/flashdiffusion/mfstar.py
|
|
11
12
|
src/flashdiffusion/spectral.py
|
|
@@ -14,4 +15,5 @@ src/flashdiffusion.egg-info/SOURCES.txt
|
|
|
14
15
|
src/flashdiffusion.egg-info/dependency_links.txt
|
|
15
16
|
src/flashdiffusion.egg-info/requires.txt
|
|
16
17
|
src/flashdiffusion.egg-info/top_level.txt
|
|
18
|
+
tests/test_bandwidth.py
|
|
17
19
|
tests/test_simple.py
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# tests/test_bandwidth.py
|
|
2
|
+
"""The bandwidth methods and the FlashDiffusion API around them.
|
|
3
|
+
|
|
4
|
+
pytest -q -s tests/test_bandwidth.py
|
|
5
|
+
"""
|
|
6
|
+
import math
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from conftest import sphere
|
|
12
|
+
|
|
13
|
+
GAP = 2 * math.pi
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_method_names():
|
|
17
|
+
from flashdiffusion.bandwidth import METHODS, _canonical
|
|
18
|
+
assert METHODS == ("ladder", "mfstar", "berryharlim", "median")
|
|
19
|
+
for alias in ("berry_harlim", "Berry-Harlim", "BerryHarlim", "berryharlim"):
|
|
20
|
+
assert _canonical(alias) == "berryharlim"
|
|
21
|
+
with pytest.raises(ValueError):
|
|
22
|
+
_canonical("silverman")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.mark.parametrize("method", ["ladder", "mfstar", "berryharlim", "median"])
|
|
26
|
+
def test_results_well_formed(method):
|
|
27
|
+
from flashdiffusion import select_bandwidth
|
|
28
|
+
r = select_bandwidth(sphere(2**13), method)
|
|
29
|
+
print(f"\n{method}: beta={r.beta:.6g} passes={r.passes:.1f} {r.seconds:.2f}s")
|
|
30
|
+
assert r.method == method
|
|
31
|
+
assert math.isfinite(r.beta) and r.beta > 0
|
|
32
|
+
assert r.passes >= 0 and r.seconds >= 0
|
|
33
|
+
if method == "median":
|
|
34
|
+
assert r.passes == 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_ladder_matches_mfstar():
|
|
38
|
+
"""Two rungs at N = 2^15: same answer as the full-N search, at lower cost."""
|
|
39
|
+
from flashdiffusion import select_bandwidth
|
|
40
|
+
X = sphere(2**15)
|
|
41
|
+
lad, full = select_bandwidth(X, "ladder"), select_bandwidth(X, "mfstar")
|
|
42
|
+
rel = abs(lad.beta / full.beta - 1)
|
|
43
|
+
print(f"\nladder {lad.beta:.6g} ({lad.passes:.1f} passes), "
|
|
44
|
+
f"mfstar {full.beta:.6g} ({full.passes:.1f} passes), rel {rel:.2e}")
|
|
45
|
+
assert len(lad.details.rungs) >= 2
|
|
46
|
+
assert rel < 1e-3
|
|
47
|
+
assert lad.passes < full.passes
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_berryharlim_grid_matches_gradient():
|
|
51
|
+
"""On a single-scale manifold both searches find the same steepest point."""
|
|
52
|
+
from flashdiffusion import select_bandwidth
|
|
53
|
+
X = sphere(2**14)
|
|
54
|
+
grid = select_bandwidth(X, "berryharlim", search="grid")
|
|
55
|
+
grad = select_bandwidth(X, "berryharlim", search="gradient")
|
|
56
|
+
rel = abs(grid.beta / grad.beta - 1)
|
|
57
|
+
print(f"\ngrid {grid.beta:.6g} ({grid.passes} passes, minima {grid.details['minima']}), "
|
|
58
|
+
f"gradient {grad.beta:.6g} ({grad.passes} passes), rel {rel:.2e}")
|
|
59
|
+
assert rel < 1e-3
|
|
60
|
+
assert grid.details["newton_iterations"] > 0, "Newton did not refine the grid minimum"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_berryharlim_takes_the_coarse_scale_on_the_roll(roll):
|
|
64
|
+
"""Berry-Harlim targets the steepest slope (the mountain), MF* the cliff.
|
|
65
|
+
|
|
66
|
+
On the roll the steepest slope is at a coarser scale than the MF* peak.
|
|
67
|
+
"""
|
|
68
|
+
from flashdiffusion import select_bandwidth
|
|
69
|
+
X, _, _ = roll
|
|
70
|
+
bh, lad = select_bandwidth(X, "berryharlim"), select_bandwidth(X, "ladder")
|
|
71
|
+
for name, r in (("berryharlim", bh), ("ladder", lad)):
|
|
72
|
+
sigma = 1 / math.sqrt(2 * r.beta)
|
|
73
|
+
print(f"\n{name}: beta={r.beta:.6g} sigma={sigma:.3f} gap={GAP:.3f}")
|
|
74
|
+
print(f"berryharlim minima (beta, dimension): {bh.details['minima']}")
|
|
75
|
+
assert bh.beta < lad.beta
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_dense_moments_match_xgemm(roll):
|
|
79
|
+
"""Berry-Harlim through the dense solver's cached distances gives the same beta."""
|
|
80
|
+
from flashdiffusion import FlashDiffusion, select_bandwidth
|
|
81
|
+
X, _, _ = roll
|
|
82
|
+
free = select_bandwidth(X, "berryharlim")
|
|
83
|
+
dense = FlashDiffusion(X, beta_method="berryharlim", solver="dense", verbose=False)
|
|
84
|
+
assert abs(dense.beta_ / free.beta - 1) < 1e-3, (dense.beta_, free.beta)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_given_beta_and_aliases():
|
|
88
|
+
from flashdiffusion import FlashDiffusion
|
|
89
|
+
model = FlashDiffusion(sphere(2**12), beta=2.0, verbose=False)
|
|
90
|
+
assert model.beta_ == 2.0 and model.bandwidth_ is None
|
|
91
|
+
assert model.info_["beta_method"] == "given"
|
|
92
|
+
assert FlashDiffusion.fit is FlashDiffusion.solve
|
|
93
|
+
with pytest.raises(ValueError):
|
|
94
|
+
FlashDiffusion(sphere(2**12), beta_method="silverman", verbose=False)
|
|
@@ -7,8 +7,9 @@ on that rectangle: eigenfunctions cos(pi m s / L) cos(pi n h / W), eigenvalues
|
|
|
7
7
|
pi^2 (m^2 / L^2 + n^2 / W^2). With W = 15 the first five nontrivial modes are
|
|
8
8
|
pure along-roll modes m = 1..5; the test checks m = 1..4.
|
|
9
9
|
|
|
10
|
-
Runs the full pipeline
|
|
11
|
-
|
|
10
|
+
Runs the full pipeline with the defaults, FlashDiffusion(X) then solve(): the
|
|
11
|
+
ladder bandwidth search, the eigensolver and its verification, for both solvers,
|
|
12
|
+
then checks that the two solvers agree with each other.
|
|
12
13
|
|
|
13
14
|
pytest -q -s tests/test_simple.py
|
|
14
15
|
"""
|
|
@@ -17,19 +18,8 @@ import math
|
|
|
17
18
|
import numpy as np
|
|
18
19
|
import pytest
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
try:
|
|
23
|
-
if cp.cuda.runtime.getDeviceCount() < 1:
|
|
24
|
-
pytest.skip("No CUDA device", allow_module_level=True)
|
|
25
|
-
except cp.cuda.runtime.CUDARuntimeError:
|
|
26
|
-
pytest.skip("No CUDA device", allow_module_level=True)
|
|
27
|
-
|
|
28
|
-
N = 16384
|
|
29
|
-
HEIGHT = 15.0
|
|
30
|
-
T0, T1 = 1.5 * math.pi, 4.5 * math.pi # the standard 1.5-turn Swiss roll
|
|
31
|
-
GAP = 2 * math.pi # radial distance between neighbouring turns
|
|
32
|
-
MODES = 4 # along-roll harmonics checked: m = 1..MODES
|
|
21
|
+
GAP = 2 * math.pi # radial distance between neighbouring turns
|
|
22
|
+
MODES = 4 # along-roll harmonics checked: m = 1..MODES
|
|
33
23
|
SEED = 7
|
|
34
24
|
|
|
35
25
|
MIN_CORR = 0.97 # |correlation| with the exact harmonic, per mode
|
|
@@ -40,52 +30,29 @@ AGREE_LAMBDA = 1e-2 # dense vs matrix-free: relative eigenvalue difference
|
|
|
40
30
|
AGREE_R2 = 0.999 # dense vs matrix-free: mean squared cosine of principal angles
|
|
41
31
|
|
|
42
32
|
SOLVERS = ["dense", "matrix_free"]
|
|
33
|
+
_SOLVED = {}
|
|
43
34
|
|
|
44
35
|
|
|
45
|
-
def
|
|
46
|
-
"""
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def swiss_roll(n, seed):
|
|
51
|
-
"""Points uniform in area on the roll, with their arc-length coordinate."""
|
|
52
|
-
rng = np.random.default_rng(seed)
|
|
53
|
-
grid = np.linspace(T0, T1, 200_001)
|
|
54
|
-
s_grid = _arclength(grid) - _arclength(T0)
|
|
55
|
-
L = float(s_grid[-1])
|
|
56
|
-
s = rng.uniform(0.0, L, n)
|
|
57
|
-
t = np.interp(s, s_grid, grid)
|
|
58
|
-
h = rng.uniform(0.0, HEIGHT, n)
|
|
59
|
-
X = np.stack([t * np.cos(t), h, t * np.sin(t)], axis=1)
|
|
60
|
-
return X.astype(np.float32), s, L
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
_FITTED = {}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def fitted(solver, X):
|
|
67
|
-
"""Fit each solver once per module; both tests and the comparison reuse it."""
|
|
68
|
-
if solver not in _FITTED:
|
|
36
|
+
def solved(solver, X):
|
|
37
|
+
"""Run each solver once per session; the tests and the comparison reuse it."""
|
|
38
|
+
if solver not in _SOLVED:
|
|
69
39
|
from flashdiffusion import FlashDiffusion
|
|
70
40
|
model = FlashDiffusion(X, alpha=1.0, seed=SEED, solver=solver, verbose=True)
|
|
71
|
-
model.
|
|
72
|
-
|
|
73
|
-
return
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
@pytest.fixture(scope="module")
|
|
77
|
-
def roll():
|
|
78
|
-
return swiss_roll(N, SEED)
|
|
41
|
+
model.solve(n_modes=8)
|
|
42
|
+
_SOLVED[solver] = model
|
|
43
|
+
return _SOLVED[solver]
|
|
79
44
|
|
|
80
45
|
|
|
81
46
|
@pytest.fixture(scope="module", params=SOLVERS)
|
|
82
47
|
def model(request, roll):
|
|
83
48
|
X, _, _ = roll
|
|
84
|
-
return
|
|
49
|
+
return solved(request.param, X)
|
|
85
50
|
|
|
86
51
|
|
|
87
|
-
def
|
|
52
|
+
def test_defaults(model):
|
|
88
53
|
assert model.solver_ in SOLVERS
|
|
54
|
+
assert model.info_["beta_method"] == "ladder"
|
|
55
|
+
assert model.bandwidth_ is not None and model.bandwidth_.method == "ladder"
|
|
89
56
|
|
|
90
57
|
|
|
91
58
|
def test_bandwidth_resolves_roll(model):
|
|
@@ -126,10 +93,10 @@ def test_solvers_agree(roll):
|
|
|
126
93
|
"""Same data, same criterion: dense and matrix-free must give the same answer.
|
|
127
94
|
|
|
128
95
|
This also checks that DenseKernel.moments follows xgemm.rbf_moments'
|
|
129
|
-
convention; if it didn't,
|
|
96
|
+
convention; if it didn't, the search would select a different beta.
|
|
130
97
|
"""
|
|
131
98
|
X, _, _ = roll
|
|
132
|
-
a, b =
|
|
99
|
+
a, b = solved("dense", X), solved("matrix_free", X)
|
|
133
100
|
|
|
134
101
|
assert abs(a.beta_ / b.beta_ - 1.0) < AGREE_BETA, (a.beta_, b.beta_)
|
|
135
102
|
|
|
@@ -1,10 +0,0 @@
|
|
|
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 select_bandwidth, BandwidthResult, StationaryPoint
|
|
6
|
-
from .flashdiffusion import FlashDiffusion
|
|
7
|
-
|
|
8
|
-
__version__ = version('flashdiffusion')
|
|
9
|
-
__all__ = ['FlashDiffusion', 'energy', 'energy_jet', 'Jet',
|
|
10
|
-
'select_bandwidth', 'BandwidthResult', 'StationaryPoint']
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
# src/flashdiffusion/bandwidth.py
|
|
2
|
-
|
|
3
|
-
"""Bandwidth selection using safeguarded analytic Newton iterations."""
|
|
4
|
-
|
|
5
|
-
from dataclasses import dataclass
|
|
6
|
-
|
|
7
|
-
import numpy as np
|
|
8
|
-
|
|
9
|
-
from .energy import energy_jet
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
@dataclass(frozen=True)
|
|
13
|
-
class StationaryPoint:
|
|
14
|
-
beta: float
|
|
15
|
-
energy: float
|
|
16
|
-
gradient: float
|
|
17
|
-
hessian: float
|
|
18
|
-
iterations: int
|
|
19
|
-
kind: str
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
@dataclass(frozen=True)
|
|
23
|
-
class BandwidthResult:
|
|
24
|
-
beta: float
|
|
25
|
-
energy: float
|
|
26
|
-
stationary_points: tuple
|
|
27
|
-
scan: tuple
|
|
28
|
-
evaluations: int
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def _newton(evaluate, lo, hi, *, tol, maxiter):
|
|
32
|
-
"""Find a stationary point inside a log-beta bracket."""
|
|
33
|
-
|
|
34
|
-
_, ga, _ = evaluate(lo)
|
|
35
|
-
_, gb, _ = evaluate(hi)
|
|
36
|
-
|
|
37
|
-
if ga * gb > 0:
|
|
38
|
-
raise ValueError("Gradient does not change sign")
|
|
39
|
-
|
|
40
|
-
t = 0.5 * (lo + hi)
|
|
41
|
-
|
|
42
|
-
for iteration in range(1, maxiter + 1):
|
|
43
|
-
|
|
44
|
-
E, g, h = evaluate(t)
|
|
45
|
-
|
|
46
|
-
if abs(g) <= tol:
|
|
47
|
-
return StationaryPoint(
|
|
48
|
-
beta=float(np.exp(t)),
|
|
49
|
-
energy=E,
|
|
50
|
-
gradient=g,
|
|
51
|
-
hessian=h,
|
|
52
|
-
iterations=iteration,
|
|
53
|
-
kind="maximum" if h < 0 else "minimum",
|
|
54
|
-
)
|
|
55
|
-
|
|
56
|
-
# Update the stationary-point bracket.
|
|
57
|
-
if ga * g > 0:
|
|
58
|
-
lo, ga = t, g
|
|
59
|
-
else:
|
|
60
|
-
hi, gb = t, g
|
|
61
|
-
|
|
62
|
-
# Analytic Newton step.
|
|
63
|
-
if np.isfinite(h) and abs(h) > 1e-12:
|
|
64
|
-
candidate = t - g / h
|
|
65
|
-
else:
|
|
66
|
-
candidate = np.nan
|
|
67
|
-
|
|
68
|
-
# Safeguard against leaving the bracket.
|
|
69
|
-
if not lo < candidate < hi:
|
|
70
|
-
candidate = 0.5 * (lo + hi)
|
|
71
|
-
|
|
72
|
-
t = candidate
|
|
73
|
-
|
|
74
|
-
raise RuntimeError(
|
|
75
|
-
"Newton iteration did not converge"
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
def select_bandwidth(
|
|
80
|
-
X,
|
|
81
|
-
alpha=1.0,
|
|
82
|
-
*,
|
|
83
|
-
beta_min=1e-4,
|
|
84
|
-
beta_max=1e4,
|
|
85
|
-
scan_points=96,
|
|
86
|
-
tol=1e-5,
|
|
87
|
-
maxiter=50,
|
|
88
|
-
backend="auto",
|
|
89
|
-
):
|
|
90
|
-
"""Select the largest-beta resolved local energy maximum."""
|
|
91
|
-
|
|
92
|
-
if not 0 < beta_min < beta_max:
|
|
93
|
-
raise ValueError("Invalid bandwidth interval")
|
|
94
|
-
|
|
95
|
-
if scan_points < 3:
|
|
96
|
-
raise ValueError("At least three scan points required")
|
|
97
|
-
|
|
98
|
-
cache = {}
|
|
99
|
-
|
|
100
|
-
def evaluate(t):
|
|
101
|
-
t = float(t)
|
|
102
|
-
|
|
103
|
-
if t not in cache:
|
|
104
|
-
beta = float(np.exp(t))
|
|
105
|
-
|
|
106
|
-
jet = energy_jet(
|
|
107
|
-
X,
|
|
108
|
-
beta,
|
|
109
|
-
alpha,
|
|
110
|
-
backend=backend,
|
|
111
|
-
)
|
|
112
|
-
|
|
113
|
-
values = tuple(float(x) for x in jet)
|
|
114
|
-
|
|
115
|
-
if not np.all(np.isfinite(values)):
|
|
116
|
-
raise FloatingPointError(
|
|
117
|
-
f"Nonfinite energy derivatives at beta={beta}"
|
|
118
|
-
)
|
|
119
|
-
|
|
120
|
-
cache[t] = values
|
|
121
|
-
|
|
122
|
-
return cache[t]
|
|
123
|
-
|
|
124
|
-
grid = np.linspace(
|
|
125
|
-
np.log(beta_min),
|
|
126
|
-
np.log(beta_max),
|
|
127
|
-
scan_points,
|
|
128
|
-
)
|
|
129
|
-
|
|
130
|
-
scan = [evaluate(t) for t in grid]
|
|
131
|
-
|
|
132
|
-
points = []
|
|
133
|
-
|
|
134
|
-
for i in range(len(grid) - 1):
|
|
135
|
-
|
|
136
|
-
ga = scan[i][1]
|
|
137
|
-
gb = scan[i + 1][1]
|
|
138
|
-
|
|
139
|
-
if ga * gb >= 0:
|
|
140
|
-
continue
|
|
141
|
-
|
|
142
|
-
point = _newton(
|
|
143
|
-
evaluate,
|
|
144
|
-
float(grid[i]),
|
|
145
|
-
float(grid[i + 1]),
|
|
146
|
-
tol=tol,
|
|
147
|
-
maxiter=maxiter,
|
|
148
|
-
)
|
|
149
|
-
|
|
150
|
-
points.append(point)
|
|
151
|
-
|
|
152
|
-
maxima = [
|
|
153
|
-
p for p in points
|
|
154
|
-
if p.kind == "maximum"
|
|
155
|
-
]
|
|
156
|
-
|
|
157
|
-
if not maxima:
|
|
158
|
-
raise RuntimeError(
|
|
159
|
-
"No local energy maximum resolved"
|
|
160
|
-
)
|
|
161
|
-
|
|
162
|
-
best = max(maxima, key=lambda p: p.beta)
|
|
163
|
-
|
|
164
|
-
return BandwidthResult(
|
|
165
|
-
beta=best.beta,
|
|
166
|
-
energy=best.energy,
|
|
167
|
-
stationary_points=tuple(points),
|
|
168
|
-
scan=tuple(
|
|
169
|
-
(float(np.exp(t)), *values)
|
|
170
|
-
for t, values in zip(grid, scan)
|
|
171
|
-
),
|
|
172
|
-
evaluations=len(cache),
|
|
173
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{flashdiffusion-0.2.0 → flashdiffusion-0.2.1}/src/flashdiffusion.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|