Skip to content

ENH: avoid full-matrix CSD computation in Fourier/multitaper paths #13717

Closed

Description

@PragnyaKhandelwal

Description

CSD computation in mne/time_frequency/csd.py currently computes a full channel × channel matrix in _csd_fourier / _csd_multitaper and then compresses it to upper-triangle vector form. This is unnecessarily expensive in memory and compute for larger channel counts.

Steps to reproduce

Use csd_array_fourier or csd_array_multitaper with many channels (e.g., 128+) and profile runtime/memory.

Expected results

CSD computation should directly compute upper-triangle channel pairs (the final stored representation), avoiding full matrix materialization.

Actual results

Before fix, code computes full channel × channel CSD and then compresses, causing extra memory/time overhead.

Activity

  1. scott-huberty commented on Mar 3, 2026

    @scott-huberty
    Contributor

    This is unnecessarily expensive in memory and compute for larger channel counts.

    Hi @PragnyaKhandelwal can you please share some self-contained code for the steps to reproduce section? In other words, a MWE that computes _csd_fourier on an example file, then share the results when running on this branch and when running on main, to demonstrate the problem on main and the speed-up and memory improvement gained in this branch?

  2. PragnyaKhandelwal commented on Mar 3, 2026

    @PragnyaKhandelwal
    ContributorAuthor

    Thanks @scott-huberty — sharing a self-contained MWE and branch comparison results.

    I ran this on:

    • main
    • fix-csd-upper-triangle-computation

    MWE (self-contained)

    import time
    import tracemalloc
    import numpy as np
    import mne
    from mne.time_frequency import csd_array_fourier, csd_array_multitaper
    
    def bench(func, X, sfreq, n_runs=2, **kwargs):
        times, peaks = [], []
        out_shape = None
        for _ in range(n_runs):
            tracemalloc.start()
            t0 = time.perf_counter()
            csd = func(X, sfreq=sfreq, **kwargs)
            dt = time.perf_counter() - t0
            _, peak = tracemalloc.get_traced_memory()
            tracemalloc.stop()
            times.append(dt)
            peaks.append(peak / (1024 ** 2))
            out_shape = csd._data.shape
        return np.mean(times), np.std(times), np.mean(peaks), np.std(peaks), out_shape
    
    rng = np.random.default_rng(0)
    sfreq = 200.0
    n_epochs, n_times = 20, 1200
    common = dict(fmin=8, fmax=30, t0=0.0, tmin=0.0, tmax=4.8, n_jobs=1)
    
    for n_channels in (128, 192):
        X = rng.standard_normal((n_epochs, n_channels, n_times))
        f = bench(csd_array_fourier, X, sfreq, n_runs=2, **common)
        m = bench(csd_array_multitaper, X, sfreq, n_runs=2, adaptive=False, **common)
        print(f"n_channels={n_channels}")
        print("  fourier:    %.3f ± %.3f s, peak %.3f ± %.3f MB, shape=%s" % f)
        print("  multitaper: %.3f ± %.3f s, peak %.3f ± %.3f MB, shape=%s" % m)
    
    print("mne version:", mne.__version__)
    print("mne path:", mne.__file__)

    Measured results
    Config:

    • mne==1.1.0.dev1458+gc8132bea6

    • n_epochs=20, n_times=1200, sfreq=200

    • fmin=8, fmax=30, tmin=0, tmax=4.8

    • n_jobs=1, runs=2

    n_channels=128

    - main

    1. Fourier: 7.324 ± 0.107 s, peak 133.823 MB

    2. Multitaper: 14.078 ± 1.790 s, peak 768.916 MB

    - fix-csd-upper-triangle-computation

    1. Fourier: 2.233 ± 0.188 s, peak 94.783 MB

    2. Multitaper: 10.593 ± 0.094 s, peak 495.738 MB

    - Delta (fix vs main):

    1. Fourier: ~69.5% faster, ~29.2% lower peak traced memory

    2. Multitaper: ~24.8% faster, ~35.5% lower peak traced memory

    n_channels=192

    - main

    1. Fourier: 6.485 ± 0.347 s, peak 299.591 MB

    2. Multitaper: 28.237 ± 0.801 s, peak 1729.644 MB

    - fix-csd-upper-triangle-computation

    1. Fourier: 3.974 ± 0.053 s, peak 211.344 MB

    2. Multitaper: 18.526 ± 2.031 s, peak 1111.348 MB

    - Delta (fix vs main):

    1. Fourier: ~38.7% faster, ~29.5% lower peak traced memory

    2. Multitaper: ~34.4% faster, ~35.7% lower peak traced memory

  3. scott-huberty commented on Mar 3, 2026

    @scott-huberty
    Contributor

    Those results look pretty convincing! Though I am a little surprised that the 128-channel Fourier results are slower than the 192-channel Fourier results.

    And I assume the motivation for this issue stems from this FIXME comment in the code?

    csds = _csd_from_mt(x_mt, y_mt, weights, weights_y)
    # FIXME: don't compute full matrix in the first place
    csds = np.array(
    [_sym_mat_to_vector(csds[:, :, i]) for i in range(csds.shape[-1])]
    ).T

    If so, then I'd say go ahead and open a PR so that we can iterate from there.

  4. PragnyaKhandelwal commented on Mar 4, 2026

    @PragnyaKhandelwal
    ContributorAuthor

    Thanks Scott — yep, exactly. This came directly from that FIXME in mne/time_frequency/csd.py where we build the full CSD matrix first and then convert it to upper-triangular vector form.

    I’ll go ahead and open the PR from fix-csd-upper-triangle-computation and link this issue so we can continue discussion there.

    Also good catch on the 128 vs 192 Fourier timing oddity — I think that’s likely run-to-run noise/cache effects with a small number of runs. I can include an additional rerun with more repetitions in the PR comments to make that comparison more stable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions