Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions mne/decoding/_ged.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,39 @@ def _smart_ged(S, R, restr_mat=None, R_func=None):
to the original space. The g-eigenvectors matrix is of shape (n_chs, r).
If callable R_func is provided the GED will be performed on (S, R_func(S,R))
"""
# Array API Standard support for hardware acceleration (TPU/GPU)
if hasattr(S, "__array_namespace__"):
xp = S.__array_namespace__()
else:
import numpy as xp

if restr_mat is None:
evals, evecs = scipy.linalg.eigh(S, R)
return evals, evecs
if xp.__name__ == "numpy":
evals, evecs = scipy.linalg.eigh(S, R)
return evals, evecs
else:
# Hardware-accelerated Cholesky path since eigh(A,B) is not in Array API
L = xp.linalg.cholesky(R)
L_inv = xp.linalg.inv(L)
C = L_inv @ S @ L_inv.T
evals, evecs_C = xp.linalg.eigh(C)
evecs = L_inv.T @ evecs_C
return evals, evecs

S_restr = restr_mat @ S @ restr_mat.T
R_restr = restr_mat @ R @ restr_mat.T
if R_func is not None:
R_restr = R_func([S_restr, R_restr])
evals, evecs_restr = scipy.linalg.eigh(S_restr, R_restr)

if xp.__name__ == "numpy":
evals, evecs_restr = scipy.linalg.eigh(S_restr, R_restr)
else:
L = xp.linalg.cholesky(R_restr)
L_inv = xp.linalg.inv(L)
C = L_inv @ S_restr @ L_inv.T
evals, evecs_C = xp.linalg.eigh(C)
evecs_restr = L_inv.T @ evecs_C

evecs = restr_mat.T @ evecs_restr

return evals, evecs
Expand Down
9 changes: 8 additions & 1 deletion mne/decoding/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,14 @@ def fit(self, X, y=None):
)
self._validate_ged_params()
covs, C_ref, info, rank, kwargs = self.cov_callable(X, y)
covs = np.stack(covs)

# Array API Standard support to preserve hardware acceleration tensors
if len(covs) > 0 and hasattr(covs[0], "__array_namespace__"):
xp = covs[0].__array_namespace__()
covs = xp.stack(covs)
else:
covs = np.stack(covs)

self._validate_covariances(covs)
if C_ref is not None:
self._validate_covariances([C_ref])
Expand Down