htfa 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.
- htfa/__init__.py +39 -0
- htfa/_download.py +34 -0
- htfa/_engines.py +562 -0
- htfa/_kernels.py +1532 -0
- htfa/_lazy.py +437 -0
- htfa/_matching.py +71 -0
- htfa/_spatial.py +145 -0
- htfa/_validation.py +13 -0
- htfa/brainnet.py +2257 -0
- htfa/connectivity.py +137 -0
- htfa/datasets.py +457 -0
- htfa/fit.py +115 -0
- htfa/groups.py +677 -0
- htfa/htfa.py +1158 -0
- htfa/io.py +444 -0
- htfa/results.py +1265 -0
- htfa/stats.py +149 -0
- htfa/synthetic.py +453 -0
- htfa/tfa.py +1149 -0
- htfa/timecourse.py +254 -0
- htfa-0.1.0.dist-info/METADATA +234 -0
- htfa-0.1.0.dist-info/RECORD +25 -0
- htfa-0.1.0.dist-info/WHEEL +5 -0
- htfa-0.1.0.dist-info/licenses/LICENSE +20 -0
- htfa-0.1.0.dist-info/top_level.txt +1 -0
htfa/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Hierarchical Topographic Factor Analysis."""
|
|
2
|
+
|
|
3
|
+
from . import datasets as datasets
|
|
4
|
+
from . import stats as stats
|
|
5
|
+
from ._lazy import require, set_autoinstall
|
|
6
|
+
from .brainnet import animate_network, plot_network
|
|
7
|
+
from .connectivity import dynamic_connectivity, isfc, static_connectivity
|
|
8
|
+
from .fit import fit
|
|
9
|
+
from .groups import group_permutation_test
|
|
10
|
+
from .htfa import HTFA
|
|
11
|
+
from .io import Subject, load
|
|
12
|
+
from .results import HTFAResults
|
|
13
|
+
from .synthetic import make_group_data, make_htfa_data, make_tfa_data
|
|
14
|
+
from .tfa import TFA
|
|
15
|
+
from .timecourse import plot_timecourse
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"HTFA",
|
|
21
|
+
"HTFAResults",
|
|
22
|
+
"Subject",
|
|
23
|
+
"TFA",
|
|
24
|
+
"animate_network",
|
|
25
|
+
"dynamic_connectivity",
|
|
26
|
+
"fit",
|
|
27
|
+
"group_permutation_test",
|
|
28
|
+
"isfc",
|
|
29
|
+
"load",
|
|
30
|
+
"make_group_data",
|
|
31
|
+
"make_htfa_data",
|
|
32
|
+
"make_tfa_data",
|
|
33
|
+
"plot_network",
|
|
34
|
+
"plot_timecourse",
|
|
35
|
+
"require",
|
|
36
|
+
"set_autoinstall",
|
|
37
|
+
"static_connectivity",
|
|
38
|
+
"stats",
|
|
39
|
+
]
|
htfa/_download.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Where htfa caches downloaded files, and their checksums."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
DATA_DIR_ENV = "HTFA_DATA_DIR"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def data_dir() -> Path:
|
|
14
|
+
"""Root folder for files htfa downloads.
|
|
15
|
+
|
|
16
|
+
``$HTFA_DATA_DIR`` if that variable is set, otherwise ``%LOCALAPPDATA%\\htfa``
|
|
17
|
+
on Windows and ``${XDG_CACHE_HOME:-~/.cache}/htfa`` elsewhere.
|
|
18
|
+
"""
|
|
19
|
+
root = os.environ.get(DATA_DIR_ENV)
|
|
20
|
+
if root:
|
|
21
|
+
return Path(root).expanduser()
|
|
22
|
+
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
|
|
23
|
+
return Path(os.environ["LOCALAPPDATA"]) / "htfa"
|
|
24
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
25
|
+
return Path(base).expanduser() / "htfa"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sha256(path: Path) -> str:
|
|
29
|
+
"""Hex SHA-256 digest of the file at ``path``."""
|
|
30
|
+
h = hashlib.sha256()
|
|
31
|
+
with open(path, "rb") as f:
|
|
32
|
+
for block in iter(lambda: f.read(1 << 20), b""):
|
|
33
|
+
h.update(block)
|
|
34
|
+
return h.hexdigest()
|
htfa/_engines.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
"""Compute engines for the heavy matrix products in the TFA residual and Jacobian.
|
|
2
|
+
|
|
3
|
+
An engine holds the (possibly compressed) data ``X`` (V, T) and weights ``W`` (K, T).
|
|
4
|
+
It provides the three products the matrix-free residual and Jacobian need (scipy
|
|
5
|
+
path), and the data term's robust-loss cost, gradient and Gauss-Newton matrix for
|
|
6
|
+
the structured solver (see `gauss_newton`). Prior terms and the mapping to the
|
|
7
|
+
parameter vector are handled by :class:`htfa._kernels.ResidualProblem`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import ctypes
|
|
11
|
+
import importlib.util
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import warnings
|
|
15
|
+
from collections import deque
|
|
16
|
+
from collections.abc import Callable, Iterator
|
|
17
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from contextvars import ContextVar
|
|
20
|
+
from functools import cache
|
|
21
|
+
from typing import Any, Protocol
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
from numpy.typing import NDArray
|
|
25
|
+
from threadpoolctl import threadpool_limits
|
|
26
|
+
|
|
27
|
+
BACKENDS = ("auto", "numpy", "cpu", "torch", "cuda", "mps")
|
|
28
|
+
# Minimum V*T*K for the automatic GPU heuristic. Hardware and solver workloads
|
|
29
|
+
# vary; explicit backend comparisons are needed for performance claims.
|
|
30
|
+
GPU_MIN_WORK = int(5e8)
|
|
31
|
+
# Elements per voxel chunk (chunk rows * max(T, K**2)) in the structured solver's
|
|
32
|
+
# data-term passes: bounds the (chunk, T) and (K, K, chunk) temporaries to 16 MB
|
|
33
|
+
# each in float64 per NumPy thread, and to 32 MB each in float32 on a GPU (fewer,
|
|
34
|
+
# larger kernels).
|
|
35
|
+
CHUNK_ELEMENTS = 2**21
|
|
36
|
+
# Rows per chunk never fall below this, so that the (rows, T) x (T, K(K+1)/2)
|
|
37
|
+
# product stays an efficient GEMM at large K (K=200: 52 rows by the element
|
|
38
|
+
# budget alone).
|
|
39
|
+
MIN_CHUNK_ROWS = 128
|
|
40
|
+
GPU_CHUNK_ELEMENTS = 2**23
|
|
41
|
+
_THREADS: ContextVar[int | None] = ContextVar("htfa_engine_threads", default=None)
|
|
42
|
+
_ONE_BLAS_THREAD: ContextVar[bool] = ContextVar("htfa_one_blas_thread", default=False)
|
|
43
|
+
# Accelerate's BLASSetThreading mode for one thread (BLAS_THREADING_SINGLE_THREADED).
|
|
44
|
+
ACCELERATE_SINGLE_THREADED = 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@contextmanager
|
|
48
|
+
def thread_limit(n: int) -> Iterator[None]:
|
|
49
|
+
"""Limit the threads of NumPy engines created inside the block to ``n``.
|
|
50
|
+
|
|
51
|
+
`htfa.htfa.HTFA` uses this (with ``threadpoolctl.threadpool_limits``) so that
|
|
52
|
+
parallel subject fits do not oversubscribe the CPU.
|
|
53
|
+
"""
|
|
54
|
+
token = _THREADS.set(max(1, int(n)))
|
|
55
|
+
try:
|
|
56
|
+
yield
|
|
57
|
+
finally:
|
|
58
|
+
_THREADS.reset(token)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@cache
|
|
62
|
+
def _accelerate() -> Any:
|
|
63
|
+
"""macOS Accelerate with ``BLASSetThreading`` (macOS 15+), else None.
|
|
64
|
+
|
|
65
|
+
threadpoolctl does not see Accelerate (NumPy's and SciPy's BLAS on macOS),
|
|
66
|
+
and Accelerate reads ``VECLIB_MAXIMUM_THREADS`` only when it loads; its
|
|
67
|
+
per-thread mode can still be set at run time.
|
|
68
|
+
"""
|
|
69
|
+
if sys.platform != "darwin":
|
|
70
|
+
return None
|
|
71
|
+
try:
|
|
72
|
+
lib = ctypes.CDLL("/System/Library/Frameworks/Accelerate.framework/Accelerate")
|
|
73
|
+
get, put = lib.BLASGetThreading, lib.BLASSetThreading
|
|
74
|
+
except (OSError, AttributeError):
|
|
75
|
+
return None
|
|
76
|
+
get.restype, put.restype = ctypes.c_int, ctypes.c_int
|
|
77
|
+
put.argtypes = [ctypes.c_int]
|
|
78
|
+
return lib
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@cache
|
|
82
|
+
def _warn_threading_unsupported(mode: int, rc: int) -> None:
|
|
83
|
+
"""One warning per (mode, return code) that Accelerate rejected a mode."""
|
|
84
|
+
warnings.warn(
|
|
85
|
+
f"Accelerate's BLASSetThreading({mode}) returned {rc} (unsupported); BLAS "
|
|
86
|
+
"keeps its current threading, so HTFA results may depend on n_jobs on "
|
|
87
|
+
"this system.",
|
|
88
|
+
RuntimeWarning,
|
|
89
|
+
stacklevel=4,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _single_threaded_accelerate(mode: int = ACCELERATE_SINGLE_THREADED) -> int | None:
|
|
94
|
+
"""Set Accelerate's threading ``mode`` (default: one thread) in the calling
|
|
95
|
+
thread; return the previous mode, or None without Accelerate or when it
|
|
96
|
+
rejects the mode (return code -1: the fit continues with the current mode,
|
|
97
|
+
after a one-time RuntimeWarning)."""
|
|
98
|
+
lib = _accelerate()
|
|
99
|
+
if lib is None:
|
|
100
|
+
return None
|
|
101
|
+
previous = int(lib.BLASGetThreading())
|
|
102
|
+
rc = int(lib.BLASSetThreading(mode))
|
|
103
|
+
if rc != 0:
|
|
104
|
+
_warn_threading_unsupported(mode, rc)
|
|
105
|
+
return None
|
|
106
|
+
return previous
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@contextmanager
|
|
110
|
+
def single_threaded_accelerate() -> Iterator[None]:
|
|
111
|
+
"""Accelerate on one thread in the calling thread inside the block (its mode
|
|
112
|
+
is per thread); no effect without Accelerate."""
|
|
113
|
+
previous = _single_threaded_accelerate()
|
|
114
|
+
try:
|
|
115
|
+
yield
|
|
116
|
+
finally:
|
|
117
|
+
if previous is not None:
|
|
118
|
+
_accelerate().BLASSetThreading(previous)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@contextmanager
|
|
122
|
+
def one_blas_thread_here() -> Iterator[None]:
|
|
123
|
+
"""The per-thread half of `one_blas_thread`: Accelerate on one thread in the
|
|
124
|
+
calling thread, and the NumPy engines created in the block start their
|
|
125
|
+
chunk threads the same way. Changes no process-wide setting, so worker
|
|
126
|
+
threads can enter it concurrently; it relies on the caller's process-wide
|
|
127
|
+
one-thread BLAS limit (`one_blas_thread`) for the other BLAS libraries."""
|
|
128
|
+
token = _ONE_BLAS_THREAD.set(True)
|
|
129
|
+
try:
|
|
130
|
+
with single_threaded_accelerate():
|
|
131
|
+
yield
|
|
132
|
+
finally:
|
|
133
|
+
_ONE_BLAS_THREAD.reset(token)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@contextmanager
|
|
137
|
+
def one_blas_thread() -> Iterator[None]:
|
|
138
|
+
"""Run BLAS on one thread inside the block, here and in the chunk threads
|
|
139
|
+
of NumPy engines.
|
|
140
|
+
|
|
141
|
+
BLAS rounds differently with one thread than with several (Accelerate:
|
|
142
|
+
one vs any other count; OpenBLAS: from one count to the next, 1e-13 on CI).
|
|
143
|
+
`htfa.htfa.HTFA` fits every subject inside this block, serial or on worker
|
|
144
|
+
threads, so that its results do not depend on ``n_jobs``. It sets the
|
|
145
|
+
process-wide threadpoolctl limit (OpenBLAS, MKL, BLIS: one thread) and,
|
|
146
|
+
for this thread, `one_blas_thread_here`; HTFA's worker threads enter only
|
|
147
|
+
`one_blas_thread_here`. The engine's chunk threads still run in parallel
|
|
148
|
+
(see `thread_limit`); their chunks do not depend on the thread count.
|
|
149
|
+
(K-means runs single-threaded on any thread; see `htfa._kernels.kmeans`.)
|
|
150
|
+
"""
|
|
151
|
+
with threadpool_limits(limits=1, user_api="blas"), one_blas_thread_here():
|
|
152
|
+
yield
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def default_threads() -> int:
|
|
156
|
+
"""Threads for a new NumPy engine: the `thread_limit` in effect, else all
|
|
157
|
+
CPUs."""
|
|
158
|
+
limit = _THREADS.get()
|
|
159
|
+
return limit if limit is not None else (os.cpu_count() or 1)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# scipy.optimize.least_squares losses rho(z) of the squared residual z (f_scale=1).
|
|
163
|
+
LOSS_NAMES = ("linear", "soft_l1", "huber", "cauchy", "arctan")
|
|
164
|
+
# scipy's floor for the Gauss-Newton loss weight rho' + 2 z rho''.
|
|
165
|
+
EPS = float(np.finfo(np.float64).eps)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def loss_terms(loss: str, z: Any, xp: Any = np) -> tuple[Any, Any, Any]:
|
|
169
|
+
"""Robust loss ``rho(z)`` and its first two derivatives at ``z = r**2``.
|
|
170
|
+
|
|
171
|
+
The same formulas as ``scipy.optimize.least_squares`` (``f_scale=1``), written
|
|
172
|
+
with the array namespace ``xp`` (``numpy`` or ``torch``) so that they run on
|
|
173
|
+
NumPy arrays and torch tensors alike.
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
----------
|
|
177
|
+
loss : {'linear', 'soft_l1', 'huber', 'cauchy', 'arctan'}
|
|
178
|
+
Loss name.
|
|
179
|
+
z : array or tensor
|
|
180
|
+
Squared residuals (non-negative).
|
|
181
|
+
xp : module, default=numpy
|
|
182
|
+
``numpy`` or ``torch``, matching the type of ``z``.
|
|
183
|
+
|
|
184
|
+
Returns
|
|
185
|
+
-------
|
|
186
|
+
rho, rho1, rho2 : arrays shaped like ``z``
|
|
187
|
+
``rho(z)``, ``rho'(z)`` and ``rho''(z)``.
|
|
188
|
+
|
|
189
|
+
Raises
|
|
190
|
+
------
|
|
191
|
+
ValueError
|
|
192
|
+
For an unknown loss name.
|
|
193
|
+
"""
|
|
194
|
+
if loss == "linear":
|
|
195
|
+
return z, xp.ones_like(z), xp.zeros_like(z)
|
|
196
|
+
# Square roots and divisions instead of fractional powers: NumPy's pow is
|
|
197
|
+
# about 25x slower than sqrt (76 ms vs 3 ms for the three soft_l1 terms of
|
|
198
|
+
# 4.2e6 residuals); the results agree to rounding.
|
|
199
|
+
if loss == "soft_l1":
|
|
200
|
+
t = 1 + z
|
|
201
|
+
root = xp.sqrt(t)
|
|
202
|
+
rho1 = 1 / root
|
|
203
|
+
return 2 * (root - 1), rho1, -0.5 * rho1 / t
|
|
204
|
+
if loss == "huber":
|
|
205
|
+
mask = z <= 1
|
|
206
|
+
zs = xp.where(mask, 1.0, z) # keeps 1 / sqrt(z) finite where it is unused
|
|
207
|
+
root = xp.sqrt(zs)
|
|
208
|
+
return (
|
|
209
|
+
xp.where(mask, z, 2 * root - 1),
|
|
210
|
+
xp.where(mask, 1.0, 1 / root),
|
|
211
|
+
xp.where(mask, 0.0, -0.5 / (root * zs)),
|
|
212
|
+
)
|
|
213
|
+
if loss == "cauchy":
|
|
214
|
+
t = 1 + z
|
|
215
|
+
return xp.log1p(z), 1 / t, -1 / t**2
|
|
216
|
+
if loss == "arctan":
|
|
217
|
+
t = 1 + z**2
|
|
218
|
+
return xp.arctan(z), 1 / t, -2 * z / t**2
|
|
219
|
+
raise ValueError(f"loss must be one of {LOSS_NAMES}, got {loss!r}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Engine(Protocol):
|
|
223
|
+
"""What :class:`htfa._kernels.ResidualProblem` needs from an engine."""
|
|
224
|
+
|
|
225
|
+
name: str
|
|
226
|
+
eps: float
|
|
227
|
+
|
|
228
|
+
def set(self, X: NDArray[np.float64], W: NDArray[np.float64]) -> None: ...
|
|
229
|
+
|
|
230
|
+
def set_weights(self, W: NDArray[np.float64]) -> None: ...
|
|
231
|
+
|
|
232
|
+
def residual(self, F: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
|
233
|
+
|
|
234
|
+
def times_w(self, A: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
|
235
|
+
|
|
236
|
+
def times_wt(self, u: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
|
237
|
+
|
|
238
|
+
def data_cost(self, F: NDArray[np.float64], s: float, loss: str) -> float: ...
|
|
239
|
+
|
|
240
|
+
def gauss_newton(
|
|
241
|
+
self, F: NDArray[np.float64], G: NDArray[np.floating], s: float, loss: str
|
|
242
|
+
) -> tuple[float, NDArray[np.float64], NDArray[np.float64]]: ...
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _ChunkedDataTerm:
|
|
246
|
+
"""Data-term cost, ``(rho' r) W^T`` and Gauss-Newton matrix, in voxel chunks.
|
|
247
|
+
|
|
248
|
+
Subclasses set ``_xp`` (array namespace), ``_X`` and ``_W`` (device arrays),
|
|
249
|
+
``_W64`` (float64 NumPy copy of ``W``) and implement ``_put`` and ``_get``.
|
|
250
|
+
Chunks run on `n_threads` threads (NumPy releases the GIL in
|
|
251
|
+
its array operations); each chunk's temporaries hold about
|
|
252
|
+
``chunk_elements`` elements.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
_xp: Any
|
|
256
|
+
_X: Any
|
|
257
|
+
_W: Any
|
|
258
|
+
_W64: NDArray[np.float64]
|
|
259
|
+
chunk_elements: int = CHUNK_ELEMENTS
|
|
260
|
+
min_chunk_rows: int = MIN_CHUNK_ROWS
|
|
261
|
+
n_threads: int = 1
|
|
262
|
+
|
|
263
|
+
def _put(self, a: NDArray[np.floating]) -> Any:
|
|
264
|
+
raise NotImplementedError
|
|
265
|
+
|
|
266
|
+
@staticmethod
|
|
267
|
+
def _get(t: Any) -> NDArray[np.float64]:
|
|
268
|
+
raise NotImplementedError
|
|
269
|
+
|
|
270
|
+
def _reset_cache(self) -> None:
|
|
271
|
+
self._pairs: tuple[Any, Any] | None = None
|
|
272
|
+
|
|
273
|
+
def _chunks(self, width: int) -> list[slice]:
|
|
274
|
+
V = self._X.shape[0]
|
|
275
|
+
step = max(self.min_chunk_rows, self.chunk_elements // max(1, width), 1)
|
|
276
|
+
return [slice(i, min(i + step, V)) for i in range(0, V, step)]
|
|
277
|
+
|
|
278
|
+
def _imap(self, fn: Callable[[slice], Any], slices: list[slice]) -> Iterator[Any]:
|
|
279
|
+
"""``fn`` over ``slices``, yielded in order, with at most ``2 n_threads``
|
|
280
|
+
chunks in flight so that unconsumed partial results stay bounded."""
|
|
281
|
+
if self.n_threads <= 1 or len(slices) <= 1:
|
|
282
|
+
yield from (fn(sl) for sl in slices)
|
|
283
|
+
return
|
|
284
|
+
window = 2 * self.n_threads
|
|
285
|
+
one = _ONE_BLAS_THREAD.get()
|
|
286
|
+
with ThreadPoolExecutor(
|
|
287
|
+
min(self.n_threads, len(slices)),
|
|
288
|
+
initializer=_single_threaded_accelerate if one else None,
|
|
289
|
+
) as pool:
|
|
290
|
+
pending: deque[Any] = deque()
|
|
291
|
+
for sl in slices:
|
|
292
|
+
pending.append(pool.submit(fn, sl))
|
|
293
|
+
if len(pending) >= window:
|
|
294
|
+
yield pending.popleft().result()
|
|
295
|
+
while pending:
|
|
296
|
+
yield pending.popleft().result()
|
|
297
|
+
|
|
298
|
+
def _weight_pairs(self) -> tuple[Any, Any]:
|
|
299
|
+
"""``(T, K(K+1)/2)`` products ``W_kt W_lt`` (k <= l) and the (K, K) map
|
|
300
|
+
from ``(k, l)`` to their column, both on the device (cached per `set`)."""
|
|
301
|
+
if self._pairs is None:
|
|
302
|
+
K = self._W64.shape[0]
|
|
303
|
+
iu, ju = np.triu_indices(K)
|
|
304
|
+
index = np.empty((K, K), dtype=np.int64)
|
|
305
|
+
index[iu, ju] = index[ju, iu] = np.arange(iu.size)
|
|
306
|
+
pairs = np.ascontiguousarray((self._W64[iu] * self._W64[ju]).T)
|
|
307
|
+
self._pairs = (self._put(pairs), self._put_index(index))
|
|
308
|
+
return self._pairs
|
|
309
|
+
|
|
310
|
+
def _put_index(self, index: NDArray[np.int64]) -> Any:
|
|
311
|
+
return index
|
|
312
|
+
|
|
313
|
+
def _residual_chunk(self, Fd: Any, sl: slice, s: float, loss: str) -> Any:
|
|
314
|
+
E = s * (self._X[sl] - Fd[sl] @ self._W)
|
|
315
|
+
return E, loss_terms(loss, E * E, self._xp)
|
|
316
|
+
|
|
317
|
+
def data_cost(self, F: NDArray[np.float64], s: float, loss: str) -> float:
|
|
318
|
+
"""``0.5 * sum(rho(r**2))`` for the data residual ``r = s (X - F W)``."""
|
|
319
|
+
Fd = self._put(F)
|
|
320
|
+
|
|
321
|
+
def chunk(sl: slice) -> float:
|
|
322
|
+
_, (rho, _, _) = self._residual_chunk(Fd, sl, s, loss)
|
|
323
|
+
return float(np.sum(self._get(rho.sum(1))))
|
|
324
|
+
|
|
325
|
+
# The chunks of `gauss_newton`'s robust-loss pass: about 10x more than a
|
|
326
|
+
# (chunk, T) element budget alone gives at fMRI sizes, so that the pass
|
|
327
|
+
# spreads over the engine's threads (T=168, K=50, V=25k: 30 chunks, not 2).
|
|
328
|
+
K, T = self._W64.shape
|
|
329
|
+
return 0.5 * sum(self._imap(chunk, self._chunks(max(T, K * K))))
|
|
330
|
+
|
|
331
|
+
def gauss_newton(
|
|
332
|
+
self, F: NDArray[np.float64], G: NDArray[np.floating], s: float, loss: str
|
|
333
|
+
) -> tuple[float, NDArray[np.float64], NDArray[np.float64]]:
|
|
334
|
+
"""Data-term cost, ``(rho' r) W^T`` and Gauss-Newton matrix.
|
|
335
|
+
|
|
336
|
+
Parameters
|
|
337
|
+
----------
|
|
338
|
+
F : ndarray, shape (V, K)
|
|
339
|
+
Factors.
|
|
340
|
+
G : ndarray, shape (K, A, V)
|
|
341
|
+
``G[k, a, v] = dF[v, k] / dtheta[k, a]`` for factor ``k``'s ``A``
|
|
342
|
+
parameters. float32 (the solver's mode 'fast', linear loss) forms
|
|
343
|
+
the NumPy engine's ``G G^T`` products in float32; they are summed
|
|
344
|
+
into the float64 result.
|
|
345
|
+
s : float
|
|
346
|
+
Residual scale, ``r = s (X - F W)``.
|
|
347
|
+
loss : str
|
|
348
|
+
Name in `LOSS_NAMES`.
|
|
349
|
+
|
|
350
|
+
Returns
|
|
351
|
+
-------
|
|
352
|
+
cost : float
|
|
353
|
+
``0.5 * sum(rho(r**2))``.
|
|
354
|
+
M : ndarray, shape (V, K)
|
|
355
|
+
``(rho'(r**2) r) W^T``; the gradient is ``-s sum_v G[k, a, v] M[v, k]``.
|
|
356
|
+
H : ndarray, shape (K, A, K, A)
|
|
357
|
+
``H[k, a, l, b] = s**2 sum_v G[k, a, v] G[l, b, v] Q_v[k, l]`` with
|
|
358
|
+
``Q_v = W diag(u_v) W^T`` and scipy's loss weights
|
|
359
|
+
``u = max(rho' + 2 r**2 rho'', EPS)``. For the linear loss ``u = 1``,
|
|
360
|
+
so ``H = (G G^T) * (W W^T)``: one O(V K^2 A^2) product, independent of
|
|
361
|
+
T. Otherwise ``Q_v`` costs one O(V T K^2 / 2) product and the
|
|
362
|
+
contraction O(V K^2 A^2).
|
|
363
|
+
"""
|
|
364
|
+
K, T = self._W64.shape
|
|
365
|
+
V, A = self._X.shape[0], G.shape[1]
|
|
366
|
+
Fd, Gd = self._put(F), self._put(G)
|
|
367
|
+
linear = loss == "linear"
|
|
368
|
+
if not linear:
|
|
369
|
+
pairs, index = self._weight_pairs()
|
|
370
|
+
|
|
371
|
+
def chunk(sl: slice) -> tuple[float, slice, Any, Any]:
|
|
372
|
+
E, (rho, rho1, rho2) = self._residual_chunk(Fd, sl, s, loss)
|
|
373
|
+
cost = float(np.sum(self._get(rho.sum(1))))
|
|
374
|
+
M = self._get((rho1 * E) @ self._W.T)
|
|
375
|
+
Gc = Gd[:, :, sl] # (K, A, B)
|
|
376
|
+
if linear:
|
|
377
|
+
Gs = Gc.reshape(K * A, -1) # [(k, a), v]
|
|
378
|
+
return cost, sl, M, self._get(Gs @ Gs.T)
|
|
379
|
+
u = (rho1 + 2 * (E * E) * rho2).clip(min=EPS)
|
|
380
|
+
Q = (u @ pairs).T[index] # (K, K, B) = Q_v[l, k], symmetric
|
|
381
|
+
# acc[a][l, k, b - a] = sum_v Q_v[l, k] G[k, a, v] G[l, b, v], b >= a.
|
|
382
|
+
GcT = Gc.swapaxes(1, 2) # (K, B, A) view
|
|
383
|
+
acc = [self._get((Q * Gc[None, :, a, :]) @ GcT[:, :, a:]) for a in range(A)]
|
|
384
|
+
return cost, sl, M, acc
|
|
385
|
+
|
|
386
|
+
width = max(T, A * K) if linear else max(T, K * K)
|
|
387
|
+
cost = 0.0
|
|
388
|
+
M = np.empty((V, K))
|
|
389
|
+
H = np.zeros((K, A, K, A))
|
|
390
|
+
for c, sl, M_c, part in self._imap(chunk, self._chunks(width)):
|
|
391
|
+
cost += c
|
|
392
|
+
M[sl] = M_c
|
|
393
|
+
if linear:
|
|
394
|
+
H += part.reshape(K, A, K, A)
|
|
395
|
+
else:
|
|
396
|
+
for a in range(A):
|
|
397
|
+
H[:, a, :, a:] += np.transpose(part[a], (1, 0, 2))
|
|
398
|
+
if linear:
|
|
399
|
+
H *= (self._W64 @ self._W64.T)[:, None, :, None]
|
|
400
|
+
else:
|
|
401
|
+
for a in range(A):
|
|
402
|
+
for b in range(a + 1, A):
|
|
403
|
+
H[:, b, :, a] = H[:, a, :, b].T
|
|
404
|
+
return 0.5 * cost, M, s**2 * H
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
class NumpyEngine(_ChunkedDataTerm):
|
|
408
|
+
"""Engine backed by NumPy (BLAS) float64 matrix products."""
|
|
409
|
+
|
|
410
|
+
name = "numpy"
|
|
411
|
+
_xp = np
|
|
412
|
+
eps = EPS
|
|
413
|
+
|
|
414
|
+
def __init__(self, n_threads: int | None = None) -> None:
|
|
415
|
+
self.n_threads = default_threads() if n_threads is None else n_threads
|
|
416
|
+
self._X: NDArray[np.float64] = np.empty((0, 0))
|
|
417
|
+
self._W: NDArray[np.float64] = np.empty((0, 0))
|
|
418
|
+
self._W64 = self._W
|
|
419
|
+
self._reset_cache()
|
|
420
|
+
|
|
421
|
+
def _put(self, a: NDArray[np.floating]) -> NDArray[np.floating]:
|
|
422
|
+
return a
|
|
423
|
+
|
|
424
|
+
@staticmethod
|
|
425
|
+
def _get(t: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
426
|
+
return t
|
|
427
|
+
|
|
428
|
+
def set(self, X: NDArray[np.float64], W: NDArray[np.float64]) -> None:
|
|
429
|
+
"""Store data ``X`` (V, T) and weights ``W`` (K, T) as float64."""
|
|
430
|
+
self._X = np.ascontiguousarray(X, dtype=np.float64)
|
|
431
|
+
self.set_weights(W)
|
|
432
|
+
|
|
433
|
+
def set_weights(self, W: NDArray[np.float64]) -> None:
|
|
434
|
+
"""Replace the weights ``W`` (K, T), keeping the data."""
|
|
435
|
+
self._W = np.ascontiguousarray(W, dtype=np.float64)
|
|
436
|
+
self._W64 = self._W
|
|
437
|
+
self._reset_cache()
|
|
438
|
+
|
|
439
|
+
def residual(self, F: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
440
|
+
"""Return ``(X - F @ W).ravel()`` for factors ``F`` (V, K)."""
|
|
441
|
+
out = self._X - F @ self._W
|
|
442
|
+
return out.ravel()
|
|
443
|
+
|
|
444
|
+
def times_w(self, A: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
445
|
+
"""Return ``(A @ W).ravel()`` for ``A`` (V, K)."""
|
|
446
|
+
return (A @ self._W).ravel()
|
|
447
|
+
|
|
448
|
+
def times_wt(self, u: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
449
|
+
"""Return ``u.reshape(V, T) @ W.T`` (V, K) for a raveled (V*T,) vector."""
|
|
450
|
+
return np.reshape(u, (self._X.shape[0], self._W.shape[1])) @ self._W.T
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
class TorchEngine(_ChunkedDataTerm):
|
|
454
|
+
"""Engine backed by torch on ``cpu``, ``cuda`` or ``mps``.
|
|
455
|
+
|
|
456
|
+
``X`` and ``W`` stay resident on the device (float32 on MPS, which has no
|
|
457
|
+
float64; float64 elsewhere). Each call moves in only the V x K-sized operands
|
|
458
|
+
and returns float64 NumPy. In the structured solver's passes, sums over
|
|
459
|
+
samples and over the voxels of one chunk run in the device dtype (float32 on
|
|
460
|
+
MPS); per-voxel costs and per-chunk partial sums are accumulated in float64.
|
|
461
|
+
`eps` is the device dtype's machine epsilon.
|
|
462
|
+
"""
|
|
463
|
+
|
|
464
|
+
def __init__(self, device: str) -> None:
|
|
465
|
+
import torch
|
|
466
|
+
|
|
467
|
+
self._torch: Any = torch
|
|
468
|
+
self._xp = torch
|
|
469
|
+
self.chunk_elements = GPU_CHUNK_ELEMENTS
|
|
470
|
+
self.device = device
|
|
471
|
+
self.name = f"torch-{device}"
|
|
472
|
+
self._dtype = torch.float32 if device == "mps" else torch.float64
|
|
473
|
+
self.eps = float(torch.finfo(self._dtype).eps)
|
|
474
|
+
self._X = torch.empty((0, 0), dtype=self._dtype, device=device)
|
|
475
|
+
self._W = torch.empty((0, 0), dtype=self._dtype, device=device)
|
|
476
|
+
self._W64 = np.empty((0, 0))
|
|
477
|
+
self._reset_cache()
|
|
478
|
+
|
|
479
|
+
def _put_index(self, index: NDArray[np.int64]) -> Any:
|
|
480
|
+
return self._torch.from_numpy(index).to(self.device)
|
|
481
|
+
|
|
482
|
+
def _put(self, a: NDArray[np.floating]) -> Any:
|
|
483
|
+
t = self._torch.from_numpy(np.ascontiguousarray(a, dtype=np.float64))
|
|
484
|
+
return t.to(device=self.device, dtype=self._dtype)
|
|
485
|
+
|
|
486
|
+
@staticmethod
|
|
487
|
+
def _get(t: Any) -> NDArray[np.float64]:
|
|
488
|
+
return np.asarray(t.cpu().numpy(), dtype=np.float64)
|
|
489
|
+
|
|
490
|
+
def set(self, X: NDArray[np.float64], W: NDArray[np.float64]) -> None:
|
|
491
|
+
"""Store data ``X`` (V, T) and weights ``W`` (K, T) on the device."""
|
|
492
|
+
self._X = self._put(X)
|
|
493
|
+
self.set_weights(W)
|
|
494
|
+
|
|
495
|
+
def set_weights(self, W: NDArray[np.float64]) -> None:
|
|
496
|
+
"""Replace the weights ``W`` (K, T) on the device, keeping the data."""
|
|
497
|
+
self._W = self._put(W)
|
|
498
|
+
self._W64 = np.array(W, dtype=np.float64)
|
|
499
|
+
self._reset_cache()
|
|
500
|
+
|
|
501
|
+
def residual(self, F: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
502
|
+
"""Return ``(X - F @ W).ravel()`` for factors ``F`` (V, K)."""
|
|
503
|
+
return self._get((self._X - self._put(F) @ self._W).reshape(-1))
|
|
504
|
+
|
|
505
|
+
def times_w(self, A: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
506
|
+
"""Return ``(A @ W).ravel()`` for ``A`` (V, K)."""
|
|
507
|
+
return self._get((self._put(A) @ self._W).reshape(-1))
|
|
508
|
+
|
|
509
|
+
def times_wt(self, u: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
510
|
+
"""Return ``u.reshape(V, T) @ W.T`` (V, K) for a raveled (V*T,) vector."""
|
|
511
|
+
U = self._put(u).reshape(self._X.shape[0], self._W.shape[1])
|
|
512
|
+
return self._get(U @ self._W.T)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _available_devices(torch: Any) -> list[str]:
|
|
516
|
+
found = []
|
|
517
|
+
if torch.cuda.is_available():
|
|
518
|
+
found.append("cuda")
|
|
519
|
+
if torch.backends.mps.is_available():
|
|
520
|
+
found.append("mps")
|
|
521
|
+
return found
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def select_engine(backend: str, V: int, T: int, K: int) -> Engine:
|
|
525
|
+
"""Choose an engine for ``backend`` and a (V, T, K)-sized problem.
|
|
526
|
+
|
|
527
|
+
``'auto'`` uses a GPU torch engine only when torch is already installed, a
|
|
528
|
+
CUDA or MPS device exists, and ``V*T*K >= GPU_MIN_WORK``.
|
|
529
|
+
"""
|
|
530
|
+
indexed_cuda = (
|
|
531
|
+
isinstance(backend, str)
|
|
532
|
+
and backend.startswith("cuda:")
|
|
533
|
+
and backend[5:].isascii()
|
|
534
|
+
and backend[5:].isdigit()
|
|
535
|
+
)
|
|
536
|
+
if backend not in BACKENDS and not indexed_cuda:
|
|
537
|
+
raise ValueError(
|
|
538
|
+
f"backend must be one of {BACKENDS} or cuda:N, got {backend!r}"
|
|
539
|
+
)
|
|
540
|
+
if backend in ("numpy", "cpu"):
|
|
541
|
+
return NumpyEngine()
|
|
542
|
+
if backend == "auto":
|
|
543
|
+
if V * T * K < GPU_MIN_WORK or importlib.util.find_spec("torch") is None:
|
|
544
|
+
return NumpyEngine()
|
|
545
|
+
import torch
|
|
546
|
+
|
|
547
|
+
gpus = _available_devices(torch)
|
|
548
|
+
return TorchEngine(gpus[0]) if gpus else NumpyEngine()
|
|
549
|
+
from htfa._lazy import ensure_torch
|
|
550
|
+
|
|
551
|
+
torch = ensure_torch()
|
|
552
|
+
gpus = _available_devices(torch)
|
|
553
|
+
if indexed_cuda:
|
|
554
|
+
index = int(backend[5:])
|
|
555
|
+
if not torch.cuda.is_available() or index >= torch.cuda.device_count():
|
|
556
|
+
raise RuntimeError(f"backend {backend!r} requested but no such CUDA device")
|
|
557
|
+
return TorchEngine(f"cuda:{index}")
|
|
558
|
+
if backend == "torch":
|
|
559
|
+
return TorchEngine(gpus[0] if gpus else "cpu")
|
|
560
|
+
if backend not in gpus:
|
|
561
|
+
raise RuntimeError(f"backend {backend!r} requested but no {backend} device")
|
|
562
|
+
return TorchEngine(backend)
|