flashdiffusion 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flashdiffusion/cdc.py ADDED
@@ -0,0 +1,168 @@
1
+ """
2
+ flashdiffusion/cdc.py
3
+ =====================
4
+ Carré du Champ (CDC) operator and diffusion metric tensor.
5
+
6
+ The Carré du Champ operator of the diffusion semigroup is:
7
+
8
+ Γ(f, g)(x) = ½ [L(fg)(x) - f(x)Lg(x) - g(x)Lf(x)]
9
+
10
+ where L = I - P⁺ is the (infinitesimal) generator of the diffusion.
11
+ For discrete diffusion maps this becomes:
12
+
13
+ Γ(φₖ, φₗ)(i) = ½ Σⱼ P⁺(i,j) [φₖ(j) - φₖ(i)] [φₗ(j) - φₗ(i)]
14
+ = ½ [Mₖₗ - λₖ φₖ(i) φₗ(i) - λₗ φₗ(i) φₖ(i)] (*)
15
+
16
+ where Mₖₗ(i) = (P⁺ φₖ φₗ)(i) — the diffusion applied to the pointwise product.
17
+
18
+ (*) uses the fact that P⁺ φₖ = λₖ φₖ.
19
+
20
+ The Diffusion Metric Tensor at point i is:
21
+
22
+ G^i_{kl} = Γ(φₖ, φₗ)(i)
23
+
24
+ and the global Riemannian metric on the embedding space is:
25
+
26
+ M = Σᵢ Gⁱ (Gⁱ)ᵀ (summed over data points)
27
+
28
+ This gives a data-driven geometry that is intrinsic to the diffusion —
29
+ it captures how much uncertainty/variance each direction in embedding
30
+ space has relative to the local transition structure.
31
+
32
+ References
33
+ ----------
34
+ - Coifman & Lafon (2006), §3
35
+ - Singer & Coifman (2008) — diffusion distance and CDC
36
+ - Nadler, Lafon, Coifman, Kevrekidis (2006) — diffusion maps for data analysis
37
+ """
38
+
39
+ from __future__ import annotations
40
+ import numpy as np
41
+ from typing import Optional
42
+
43
+ from .kernel import FlashDiffusion
44
+
45
+
46
+ def carre_du_champ(
47
+ dm, # fitted DiffusionMap instance
48
+ phi_k: np.ndarray, # (N,) eigenvector k
49
+ phi_l: np.ndarray, # (N,) eigenvector l (may equal phi_k)
50
+ lambda_k: float,
51
+ lambda_l: float,
52
+ ) -> np.ndarray:
53
+ """
54
+ Compute Γ(φₖ, φₗ)(i) for all i.
55
+
56
+ Uses the identity (*):
57
+ Γ(φₖ, φₗ)(i) = ½ [(P⁺ φₖφₗ)(i) - λₖ φₖ(i)φₗ(i) - λₗ φₗ(i)φₖ(i)]
58
+
59
+ Only ONE additional FlashDiffusion matvec is needed (for P⁺ φₖφₗ),
60
+ beyond the eigenvectors already computed by DiffusionMap.transform().
61
+
62
+ Parameters
63
+ ----------
64
+ dm : fitted DiffusionMap (after transform(), so rscale_ is set)
65
+ phi_k/l : eigenvectors of the *row-normalised* operator P+
66
+ (i.e. vecs / rscale, as returned by dmap_coords)
67
+ lambda_k/l : corresponding eigenvalues
68
+
69
+ Returns
70
+ -------
71
+ gamma : (N,) pointwise Carré du Champ values
72
+ """
73
+ # pointwise product of the two eigenfunctions
74
+ phi_kl = phi_k * phi_l # (N,)
75
+
76
+ # apply P⁺ to phi_kl via FlashDiffusion
77
+ # P⁺ f = (1/D_alpha) * K_alpha * f
78
+ # = rscale * K * (rscale * f) (using our normalisation)
79
+ # but phi_k/l are already in the P⁺-eigenvector basis, so we apply
80
+ # the DMAP matvec directly
81
+ P_phi_kl = dm.matvec(phi_kl) # (N,) = M applied to (phi_kl/rscale) * rscale
82
+ # correction: dm.matvec applies the SYMMETRIC M, not P⁺.
83
+ # We need P⁺ = D_alpha^{-1} K_alpha = rscale/d_half * M / rscale * d_half
84
+ # But phi_k/l are P⁺ eigenvectors: P⁺ φ = λ φ.
85
+ # For Γ we need (P⁺ φₖφₗ)(i), i.e. row-normalised application.
86
+ # The row-normalised operator applied to f is:
87
+ # (P⁺ f)_i = rscale_i * Σⱼ K(i,j) * rscale_j * (f_j / rscale_j) * rscale_j
88
+ # Wait — let's be explicit. With our notation:
89
+ # P⁺_{ij} = K_alpha(i,j) / D_alpha_i
90
+ # and rscale_i = D_alpha_i^{-1/2} * w_i, so:
91
+ # (P⁺ f)_i = Σⱼ [K(i,j)*w_i*w_j / D_alpha_i] * f_j
92
+ # = [rscale_i/w_i]² * Σⱼ K(i,j) * (rscale_j/w_j)^{-1} * rscale_j * f_j ... complex
93
+ # Simplest: use matvec (symmetric M) and note M = D_alpha^{-1/2} P⁺_sym D_alpha^{1/2}
94
+ # For the CDC formula (*) with phi_k in P⁺ basis, apply P⁺ directly:
95
+ P_phi_kl = _apply_Pplus(dm, phi_kl)
96
+
97
+ gamma = 0.5 * (P_phi_kl
98
+ - lambda_k * phi_k * phi_l
99
+ - lambda_l * phi_l * phi_k)
100
+ return gamma
101
+
102
+
103
+ def _apply_Pplus(dm, f: np.ndarray) -> np.ndarray:
104
+ """
105
+ Apply the row-normalised operator P⁺ to a function f.
106
+
107
+ P⁺ f_i = Σⱼ K_alpha(i,j) / D_alpha_i · f_j
108
+ = (1/D_alpha_i) · w_i · Σⱼ K(i,j) · w_j · f_j
109
+
110
+ This is a FlashDiffusion call with rscale_q = 1/D_alpha (not d_half*w).
111
+ """
112
+ N = dm.X_.shape[0]
113
+ # rscale_k for right side: w (density correction only)
114
+ # rscale_q for left side: 1/D_alpha (full row normalisation)
115
+ w = dm.D_ ** (-dm.alpha)
116
+ inv_Dalpha = dm.D_alpha_ ** (-1.0)
117
+
118
+ out = FlashDiffusion(
119
+ Q = dm.X_,
120
+ K = dm.X_,
121
+ V = f[:, None],
122
+ beta = dm.beta,
123
+ rscale_q = inv_Dalpha * w, # (D_alpha^{-1}) * w = P⁺ left normaliser
124
+ rscale_k = w, # right: w_j factor
125
+ tile = dm.tile,
126
+ )
127
+ return out.ravel()
128
+
129
+
130
+ def metric_tensor(
131
+ dm,
132
+ eigenvalues: np.ndarray, # (k,)
133
+ eigenvectors: np.ndarray, # (N, k) in P⁺ basis
134
+ pairs: Optional[list] = None, # list of (k, l) index pairs; default all
135
+ ) -> np.ndarray:
136
+ """
137
+ Compute the diffusion metric tensor G (N x k x k) where:
138
+
139
+ G[i, k, l] = Γ(φₖ, φₗ)(i)
140
+
141
+ and the global Riemannian metric M = Σᵢ G[i] G[i]ᵀ (k x k).
142
+
143
+ For large k, pass `pairs` to compute only the entries you need.
144
+
145
+ Returns
146
+ -------
147
+ G : (N, k, k) pointwise metric tensor (symmetric)
148
+ M : (k, k) global Riemannian metric
149
+ """
150
+ k = eigenvalues.shape[0]
151
+ N = eigenvectors.shape[0]
152
+ G = np.zeros((N, k, k), dtype=np.float64)
153
+
154
+ if pairs is None:
155
+ pairs = [(i, j) for i in range(k) for j in range(i, k)]
156
+
157
+ for (ki, li) in pairs:
158
+ gamma = carre_du_champ(
159
+ dm,
160
+ eigenvectors[:, ki], eigenvectors[:, li],
161
+ eigenvalues[ki], eigenvalues[li],
162
+ )
163
+ G[:, ki, li] = gamma
164
+ G[:, li, ki] = gamma
165
+
166
+ # global metric: M_kl = Σᵢ G[i,k,:] · G[i,l,:] — batched einsum
167
+ M = np.einsum('ikm,ilm->kl', G, G)
168
+ return G, M
flashdiffusion/dmap.py ADDED
@@ -0,0 +1,321 @@
1
+ """
2
+ flashdiffusion/dmap.py
3
+ ======================
4
+ DiffusionMap class: Coifman-Lafon diffusion maps via FlashDiffusion kernel.
5
+
6
+ Usage
7
+ -----
8
+ dm = DiffusionMap(beta=1.0, alpha=0.5, n_components=8)
9
+ dm.fit(X) # precompute rscale (two kernel passes, O(N·tile) mem)
10
+ coords = dm.transform() # Lanczos eigensolver -> diffusion coordinates
11
+ new = dm.transform(X_new) # Nyström out-of-sample extension
12
+
13
+ Relationship to DAC paper
14
+ --------------------------
15
+ With Q=K=X and symmetric W (W=Wᵀ), this is the canonical EQ Schrödinger
16
+ bridge (Proposition 5.2). The operator M = D_α^{-1/2} K_α D_α^{-1/2} is
17
+ the symmetrised DMAP forward operator. Its eigenvectors give the diffusion
18
+ map embedding.
19
+
20
+ The Coifman-Lafon α-normalisation is an exact Doob h-transform
21
+ (Corollary 4.2, DAC): h = D^{-α}, so the EQ class is preserved.
22
+ """
23
+
24
+ from __future__ import annotations
25
+ import numpy as np
26
+ from typing import Optional
27
+ import time
28
+
29
+ from .kernel import FlashDiffusion, prepass_rowsum
30
+
31
+
32
+ class DiffusionMap:
33
+ """
34
+ Coifman-Lafon diffusion maps.
35
+
36
+ Parameters
37
+ ----------
38
+ beta : float
39
+ Kernel bandwidth: K(i,j) = exp(-beta · ||xi - xj||²).
40
+ Use utils.median_bandwidth(X) for automatic selection.
41
+ alpha : float
42
+ Density normalisation exponent (0 = no correction, 0.5 = default,
43
+ 1.0 = Fokker-Planck normalisation).
44
+ n_components : int
45
+ Number of eigenvectors to compute (including trivial λ=1).
46
+ tile : int
47
+ Tile size for the kernel. Controls peak memory: O(N · tile · d · 4 bytes).
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ beta: float = 1.0,
53
+ alpha: float = 1.0,
54
+ n_components: int = 8,
55
+ tile: int = 512,
56
+ ):
57
+ self.beta = beta
58
+ self.alpha = alpha
59
+ self.n_components = n_components
60
+ self.tile = tile
61
+
62
+ # set after fit()
63
+ self.X_: Optional[np.ndarray] = None
64
+ self.rscale_: Optional[np.ndarray] = None
65
+ self.D_: Optional[np.ndarray] = None
66
+ self.D_alpha_: Optional[np.ndarray] = None
67
+ self._cuda_state: Optional[object] = None # CUDAState if GPU used
68
+
69
+ # set after transform()
70
+ self.eigenvalues_: Optional[np.ndarray] = None
71
+ self.eigenvectors_: Optional[np.ndarray] = None
72
+ self.embedding_: Optional[np.ndarray] = None
73
+
74
+ # ------------------------------------------------------------------
75
+ # fit: two prepass reductions, O(N·tile) memory
76
+ # ------------------------------------------------------------------
77
+
78
+ def fit(self, X: np.ndarray) -> "DiffusionMap":
79
+ """
80
+ Precompute Coifman-Lafon normalisation for dataset X.
81
+
82
+ Uses CUDA backend (two GPU prepass kernels) if available,
83
+ otherwise numpy CPU fallback. Either way the interface is identical.
84
+ """
85
+ N = X.shape[0]
86
+ self.X_ = X.astype(np.float64)
87
+ beta, alpha, tile = self.beta, self.alpha, self.tile
88
+
89
+ print(f"[DiffusionMap.fit] N={N} beta={beta} alpha={alpha}")
90
+ t0 = time.perf_counter()
91
+
92
+ # Try CUDA first
93
+ from .kernel import _get_cuda_backend
94
+ cuda = _get_cuda_backend()
95
+ if cuda is not None:
96
+ precompute_fn, matvec_fn = cuda
97
+ self._cuda_state = precompute_fn(X, beta, alpha)
98
+ self._matvec_fn = matvec_fn
99
+ # Mirror numpy fields from GPU tensors for CDC / Doob / Nyström
100
+ self.D_ = self._cuda_state.D.cpu().numpy().astype(np.float64)
101
+ self.D_alpha_ = self._cuda_state.D_alpha.cpu().numpy().astype(np.float64)
102
+ self.rscale_ = self._cuda_state.rscale.cpu().numpy().astype(np.float64)
103
+ print(f" precompute done ({self._cuda_state.__class__.__name__}) in {time.perf_counter()-t0:.3f}s")
104
+ return self
105
+
106
+ # Numpy fallback
107
+ self._cuda_state = None
108
+ D = prepass_rowsum(X, X, beta,
109
+ weights_k=np.ones(N, np.float64), tile=tile)
110
+ self.D_ = D
111
+ w = D ** (-alpha)
112
+ D_alpha = prepass_rowsum(X, X, beta, weights_k=w, tile=tile) * w
113
+ self.D_alpha_ = D_alpha
114
+ d_half = D_alpha ** (-0.5)
115
+ self.rscale_ = d_half * w
116
+ print(f" precompute done (numpy) in {time.perf_counter()-t0:.3f}s")
117
+ return self
118
+
119
+ def matvec(self, v: np.ndarray) -> np.ndarray:
120
+ """
121
+ Apply M to v. Uses CUDA kernel if available, numpy otherwise.
122
+ Called every Lanczos iteration — v is the only thing that changes.
123
+ """
124
+ self._check_fitted()
125
+
126
+ if self._cuda_state is not None:
127
+ return self._matvec_fn(self._cuda_state, v)
128
+
129
+ # numpy path
130
+ v2d = v.reshape(-1, 1)
131
+ out = FlashDiffusion(
132
+ Q=self.X_, K=self.X_, V=v2d, beta=self.beta,
133
+ rscale_q=self.rscale_, rscale_k=self.rscale_,
134
+ tile=self.tile,
135
+ )
136
+ return out.ravel()
137
+
138
+ # ------------------------------------------------------------------
139
+ # transform: Lanczos eigensolver -> diffusion coordinates
140
+ # ------------------------------------------------------------------
141
+
142
+ def transform(
143
+ self,
144
+ X_new: Optional[np.ndarray] = None,
145
+ t: int = 1,
146
+ tol: float = 0.0,
147
+ maxiter: Optional[int] = None,
148
+ use_gpu_lanczos: bool = True, # ← new flag, default on
149
+ ) -> np.ndarray:
150
+ """
151
+ Compute diffusion map coordinates.
152
+
153
+ If X_new is None: eigensolver on training set (fit must be called first).
154
+ If X_new is given: Nyström out-of-sample extension (see utils.nystrom).
155
+
156
+ Parameters
157
+ ----------
158
+ X_new : (M, d) new points, or None for training set
159
+ t : diffusion time (eigenvalues raised to power t)
160
+ tol : ARPACK tolerance (0 = machine precision), fallback only
161
+ maxiter : ARPACK max iterations, fallback only
162
+ use_gpu_lanczos : use GPU Lanczos if CUDA state available (default True)
163
+
164
+ Returns
165
+ -------
166
+ coords : (N, n_components-1) — drops the trivial first eigenvector
167
+ """
168
+ self._check_fitted()
169
+
170
+ if X_new is not None:
171
+ from .utils import nystrom_extend
172
+ return nystrom_extend(self, X_new, t=t)
173
+
174
+ # ── eigensolver dispatch ─────────────────────────────────────────────
175
+ vals, vecs = self._solve_eigenproblem(
176
+ tol=tol, maxiter=maxiter, use_gpu_lanczos=use_gpu_lanczos)
177
+
178
+ self.eigenvalues_ = vals
179
+ self.eigenvectors_ = vecs
180
+
181
+ # convert symmetric-M eigenvectors → row-normalised P+ eigenvectors
182
+ psi = vecs / self.rscale_[:, None]
183
+ psi /= np.linalg.norm(psi, axis=0, keepdims=True)
184
+
185
+ # diffusion map embedding: scale by λ^t, drop trivial first vector
186
+ coords = psi[:, 1:] * (vals[1:] ** t)[None, :]
187
+ self.embedding_ = coords
188
+ return coords
189
+
190
+
191
+ def _solve_eigenproblem(
192
+ self,
193
+ tol: float = 0.0,
194
+ maxiter: Optional[int] = None,
195
+ use_gpu_lanczos: bool = True,
196
+ ) -> tuple:
197
+ """
198
+ Dispatch to GPU Lanczos or scipy ARPACK.
199
+ Returns (vals, vecs) as numpy arrays.
200
+ """
201
+ N = self.X_.shape[0]
202
+ k = self.n_components
203
+
204
+ # ── GPU Lanczos path ─────────────────────────────────────────────────
205
+ if use_gpu_lanczos and self._cuda_state is not None:
206
+ try:
207
+ import sys
208
+ import torch
209
+ from .eigensolver_gpu import gpu_lanczos, make_gpu_matvec
210
+
211
+ # find the ext module that was injected by the notebook build
212
+ _EXT_NAMES = {
213
+ 'CUDAState': 'flash_diffusion_cuda',
214
+ 'CUDAStateSM90': 'flash_diffusion_sm90',
215
+ 'CUDAStateSM100': 'flash_diffusion_sm100',
216
+ 'CUDAStateSM120': 'flash_diffusion_sm120',
217
+ }
218
+ ext_name = _EXT_NAMES.get(
219
+ type(self._cuda_state).__name__, 'flash_diffusion_cuda')
220
+ ext = sys.modules.get(ext_name)
221
+
222
+ if ext is None:
223
+ raise RuntimeError(
224
+ f"{ext_name} not in sys.modules — "
225
+ "build the kernel first then call dm.fit()")
226
+
227
+ matvec_gpu = make_gpu_matvec(self._cuda_state, ext)
228
+
229
+ # in the GPU Lanczos branch:
230
+ q0 = torch.from_numpy(
231
+ np.sqrt(self._cuda_state.D_alpha.cpu().numpy())
232
+ ).to(device='cuda', dtype=torch.float32)
233
+ q0 /= q0.norm()
234
+
235
+ vals, vecs = gpu_lanczos(matvec_gpu, N=N, k=k, tol=1e-6, q0=q0)
236
+ return vals, vecs
237
+
238
+ except Exception as e:
239
+ print(f"[DiffusionMap] GPU Lanczos failed ({e}), "
240
+ f"falling back to ARPACK")
241
+
242
+ # ── scipy ARPACK fallback ────────────────────────────────────────────
243
+ from .eigensolver import lanczos_eigsh
244
+ return lanczos_eigsh(
245
+ self.matvec,
246
+ N = N,
247
+ k = k,
248
+ tol = tol,
249
+ maxiter = maxiter,
250
+ )
251
+
252
+ # ------------------------------------------------------------------
253
+ # Doob h-transform: returns a new DiffusionMap-like matvec
254
+ # ------------------------------------------------------------------
255
+
256
+ def doob_transform(self, h: np.ndarray) -> "DoobTransformedMap":
257
+ """
258
+ Apply a Doob h-transform to the current operator.
259
+
260
+ By Theorem 5.1 (DAC): if the current operator is EQ (symmetric K),
261
+ the transformed operator is also EQ. The new stationary distribution
262
+ is π_h ∝ π · h · (P+h).
263
+
264
+ Returns a DoobTransformedMap with a matvec() method compatible
265
+ with eigensolver.py.
266
+ """
267
+ self._check_fitted()
268
+ return DoobTransformedMap(self, h)
269
+
270
+ # ------------------------------------------------------------------
271
+
272
+ def _check_fitted(self):
273
+ if self.rscale_ is None:
274
+ raise RuntimeError("Call fit(X) before transform() or matvec().")
275
+
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # Doob-transformed operator (wraps DiffusionMap with an h-potential)
279
+ # ---------------------------------------------------------------------------
280
+
281
+ class DoobTransformedMap:
282
+ """
283
+ Doob h-transform of a DiffusionMap operator.
284
+
285
+ (M_h v)_i = rscale_i · Σⱼ K(i,j) · rscale_j · h_j · v_j
286
+ / (P+ h)_i (row-renormalisation)
287
+
288
+ By Theorem 5.1 (DAC), this preserves the EQ class when K is symmetric.
289
+ The new rscale absorbs h into the kernel normalisation.
290
+ """
291
+
292
+ def __init__(self, base: DiffusionMap, h: np.ndarray):
293
+ self.base = base
294
+ self.h = np.asarray(h, dtype=np.float64)
295
+
296
+ # precompute (P+ h)_i = rscale_i * Σⱼ K(i,j) * rscale_j * h_j
297
+ # = one FlashDiffusion call with V=h
298
+ Ph = FlashDiffusion(
299
+ Q = base.X_,
300
+ K = base.X_,
301
+ V = self.h[:, None],
302
+ beta = base.beta,
303
+ rscale_q = base.rscale_,
304
+ rscale_k = base.rscale_,
305
+ tile = base.tile,
306
+ ).ravel()
307
+ self.Ph_ = Ph # normaliser for the Doob transform
308
+
309
+ def matvec(self, v: np.ndarray) -> np.ndarray:
310
+ """Apply Doob-transformed operator to v."""
311
+ h = self.h
312
+ out = FlashDiffusion(
313
+ Q = self.base.X_,
314
+ K = self.base.X_,
315
+ V = (h * v)[:, None],
316
+ beta = self.base.beta,
317
+ rscale_q = self.base.rscale_,
318
+ rscale_k = self.base.rscale_,
319
+ tile = self.base.tile,
320
+ ).ravel()
321
+ return out / self.Ph_ # row-renormalise
@@ -0,0 +1,131 @@
1
+ """
2
+ flashdiffusion/eigensolver.py
3
+ =============================
4
+ Mixed-precision Krylov eigensolver for the FlashDiffusion operator.
5
+
6
+ ARPACK (via scipy.sparse.linalg.eigsh) handles the Lanczos recurrence
7
+ internally. It calls our matvec() on each iteration and manages
8
+ orthogonalisation in float64. Convergence for diffusion maps is typically
9
+ fast because:
10
+ - The spectrum is bounded in [0, 1] with a clear gap after k eigenvectors
11
+ - ARPACK uses implicit restarting (IRLM) with a Krylov space much larger
12
+ than k, achieving near-optimal convergence per matvec
13
+ - The trivial λ=1 eigenvector is found immediately
14
+
15
+ Precision ramp
16
+ --------------
17
+ matvec arithmetic : float32 GEMM (dist2) + float64 exp + float64 accumulate
18
+ Krylov basis : float64 (ARPACK internal)
19
+ orthogonalisation : float64 QR (ARPACK internal, O(N k²) per restart)
20
+ eigenvalue output : float64
21
+
22
+ This is the same split as FA4: tensor-core GEMM in low precision,
23
+ correction/accumulation in high precision.
24
+ """
25
+
26
+ from __future__ import annotations
27
+ import numpy as np
28
+ from scipy.sparse.linalg import eigsh, LinearOperator
29
+ from typing import Callable, Optional, Tuple
30
+ import time
31
+
32
+
33
+ def lanczos_eigsh(
34
+ matvec: Callable[[np.ndarray], np.ndarray],
35
+ N: int,
36
+ k: int = 8,
37
+ tol: float = 0.0,
38
+ maxiter: Optional[int] = None,
39
+ ncv: Optional[int] = None,
40
+ ) -> Tuple[np.ndarray, np.ndarray]:
41
+ """
42
+ Compute top-k eigenpairs via ARPACK Lanczos (implicitly restarted).
43
+
44
+ Parameters
45
+ ----------
46
+ matvec : callable (N,) -> (N,), applies the symmetric operator M
47
+ N : problem dimension
48
+ k : number of eigenpairs
49
+ tol : ARPACK convergence tolerance (0 = machine eps)
50
+ maxiter : max ARPACK iterations (default: 10 * N)
51
+ ncv : Krylov space size (default: min(max(2k+1, 20), N))
52
+ Larger ncv -> faster convergence, more memory
53
+
54
+ Returns
55
+ -------
56
+ eigenvalues : (k,) float64, descending
57
+ eigenvectors : (N, k) float64
58
+ """
59
+ if ncv is None:
60
+ ncv = min(max(2 * k + 1, 20), N)
61
+
62
+ op = LinearOperator(
63
+ shape = (N, N),
64
+ matvec = lambda v: matvec(np.asarray(v, dtype=np.float64).ravel()),
65
+ dtype = np.float64,
66
+ )
67
+
68
+ t0 = time.perf_counter()
69
+ vals, vecs = eigsh(
70
+ op,
71
+ k = k,
72
+ which = 'LM',
73
+ tol = tol,
74
+ maxiter = maxiter,
75
+ ncv = ncv,
76
+ )
77
+ dt = time.perf_counter() - t0
78
+
79
+ idx = np.argsort(vals)[::-1]
80
+ vals = vals[idx]
81
+ vecs = vecs[:, idx]
82
+
83
+ print(f"[lanczos_eigsh] k={k} N={N} time={dt:.3f}s")
84
+ print(f" eigenvalues: {vals}")
85
+ return vals, vecs
86
+
87
+
88
+ def lobpcg_eigsh(
89
+ matvec: Callable[[np.ndarray], np.ndarray],
90
+ N: int,
91
+ k: int = 8,
92
+ tol: float = 1e-8,
93
+ maxiter: int = 300,
94
+ seed: int = 42,
95
+ ) -> Tuple[np.ndarray, np.ndarray]:
96
+ """
97
+ Compute top-k eigenpairs via LOBPCG.
98
+
99
+ LOBPCG carries the previous search direction (conjugate gradient step),
100
+ giving superlinear convergence for clustered spectra. Preferred over
101
+ Lanczos when k is large relative to the spectral gap.
102
+
103
+ orthogonalisation: float64 QR inside the k x k projected problem.
104
+ Each outer iteration: one matvec + O(N k²) ortho (cheap).
105
+ """
106
+ from scipy.sparse.linalg import lobpcg
107
+
108
+ rng = np.random.default_rng(seed)
109
+ # float64 initial subspace, orthonormalised
110
+ X0 = np.linalg.qr(rng.standard_normal((N, k)))[0]
111
+
112
+ op = LinearOperator(
113
+ shape = (N, N),
114
+ matvec = lambda v: matvec(np.asarray(v, dtype=np.float64).ravel()),
115
+ dtype = np.float64,
116
+ )
117
+
118
+ t0 = time.perf_counter()
119
+ vals, vecs = lobpcg(
120
+ op,
121
+ X0,
122
+ tol = tol,
123
+ maxiter = maxiter,
124
+ largest = True,
125
+ )
126
+ dt = time.perf_counter() - t0
127
+
128
+ idx = np.argsort(vals)[::-1]
129
+ print(f"[lobpcg_eigsh] k={k} N={N} time={dt:.3f}s")
130
+ print(f" eigenvalues: {vals[idx]}")
131
+ return vals[idx], vecs[:, idx]