Repository navigation
Sum average reference in float64 before casting to the input dtype - #606
Conversation
A float32 matrix product depends on the BLAS kernel and thread count. On the 64-channel ds003061 recording that product matched MATLAB on SkylakeX and missed by 0.109375 uV on Haswell, while MATLAB's own single-precision result is 0.15625 uV from the correctly rounded float32 value. Co-authored-by: Suraj Ranganath <[email protected]>
There was a problem hiding this comment.
If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.
Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.
|
Claude finished @suraj-ranganath's task in 1m 18s —— View job Code review
BlockingNone. Important
Nits
Test gapsNone. EEGLAB parity notes
I could not run the tests in this environment (permission to run |
| mean_data = work[np.asarray(ref_indices), :].mean(axis=0, dtype=np.float64) | ||
| work[chansin_array, :] = work[chansin_array, :] - mean_data | ||
| else: | ||
| # Average reference via matrix multiplication, matching MATLAB's | ||
| # reref.m: refmatrix = eye(n) - ones(n)/n; data = refmatrix * data. | ||
| # MATLAB accumulates this product column-major; replicate that float32 | ||
| # accumulation order in NumPy (row-major) by transposing the operands | ||
| # (refmatrix is symmetric, so (data.T @ refmatrix).T == refmatrix @ data | ||
| # algebraically). The plain np.dot(refmatrix, data) form is ~0.06 uV off | ||
| # MATLAB in float32, which cascades through nonlinear downstream steps | ||
| # (ICA convergence) for borderline subjects; the transposed form is | ||
| # bit-exact to MATLAB on x86 BLAS. | ||
| n = len(chansin) | ||
| dt = original_dtype | ||
| refmatrix = np.eye(n, dtype=dt) - np.ones((n, n), dtype=dt) / dt.type(n) | ||
| block = np.ascontiguousarray(work[chansin_array, :].astype(dt).T) | ||
| # NumPy 2 can report spurious floating-point warnings for this finite | ||
| # float32 BLAS product. The result remains finite and is the deliberate | ||
| # MATLAB-order accumulation above, so contain only those matmul flags. | ||
| with np.errstate(divide="ignore", over="ignore", invalid="ignore"): | ||
| work[chansin_array, :] = (block @ refmatrix).T | ||
| block = work[chansin_array, :] | ||
| work[chansin_array, :] = block - block.mean(axis=0, dtype=np.float64) |
There was a problem hiding this comment.
Nit: work is already np.result_type(data_arr.dtype, np.float64) from line 53, so float32/float64 input is already summed in float64 here. Adding dtype=np.float64 makes no difference for those inputs. Its only effect is to lower precision for np.longdouble input, which used to be summed in long double. The fix is the float64 elementwise subtract on line 85, which replaces the float32 BLAS product. You can drop the explicit dtype and leave line 81 as it was:
| mean_data = work[np.asarray(ref_indices), :].mean(axis=0, dtype=np.float64) | |
| work[chansin_array, :] = work[chansin_array, :] - mean_data | |
| else: | |
| # Average reference via matrix multiplication, matching MATLAB's | |
| # reref.m: refmatrix = eye(n) - ones(n)/n; data = refmatrix * data. | |
| # MATLAB accumulates this product column-major; replicate that float32 | |
| # accumulation order in NumPy (row-major) by transposing the operands | |
| # (refmatrix is symmetric, so (data.T @ refmatrix).T == refmatrix @ data | |
| # algebraically). The plain np.dot(refmatrix, data) form is ~0.06 uV off | |
| # MATLAB in float32, which cascades through nonlinear downstream steps | |
| # (ICA convergence) for borderline subjects; the transposed form is | |
| # bit-exact to MATLAB on x86 BLAS. | |
| n = len(chansin) | |
| dt = original_dtype | |
| refmatrix = np.eye(n, dtype=dt) - np.ones((n, n), dtype=dt) / dt.type(n) | |
| block = np.ascontiguousarray(work[chansin_array, :].astype(dt).T) | |
| # NumPy 2 can report spurious floating-point warnings for this finite | |
| # float32 BLAS product. The result remains finite and is the deliberate | |
| # MATLAB-order accumulation above, so contain only those matmul flags. | |
| with np.errstate(divide="ignore", over="ignore", invalid="ignore"): | |
| work[chansin_array, :] = (block @ refmatrix).T | |
| block = work[chansin_array, :] | |
| work[chansin_array, :] = block - block.mean(axis=0, dtype=np.float64) | |
| mean_data = work[np.asarray(ref_indices), :].mean(axis=0) | |
| work[chansin_array, :] = work[chansin_array, :] - mean_data | |
| else: | |
| block = work[chansin_array, :] | |
| work[chansin_array, :] = block - block.mean(axis=0) |
(The docstring line "Average reference sums in float64" stays true because of line 53.)
The working array is already at least float64. Forcing the mean to float64 would reduce a long double input. Co-authored-by: Suraj Ranganath <[email protected]>
Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 1m 13s —— View job Code review
BlockingNone. Important
Nits
Test gapsNone. EEGLAB parity notes
I did not run any tests. This review is a static read of the code. |
| python_unmixing = _unmixing(p300_picard) | ||
| picard_options = {"tol": PICARD_TOL, "max_iter": PICARD_MAX_ITER} | ||
| python_eeg = eeg_picard(p300_clean, **picard_options) | ||
| matlab_eeg = _Side(matlab.engine).wrapper.eeg_picard(p300_clean, **picard_options) |
There was a problem hiding this comment.
Important: MatlabWrapper turns kwargs into name/value pairs word for word (
eegprep/src/eegprep/functions/adminfunc/eeglabcompat.py
Lines 266 to 270 in c1d07b6
eeg_picard(EEG, 'tol', 1e-10, 'max_iter', 2048). MATLAB picard.m names this option 'maxiter'. EEGLAB's own picard menu presets use 'maxiter', 500 (eegprep/src/eegprep/functions/popfunc/pop_runica.py
Lines 26 to 28 in c1d07b6
max_iter is the Python-side name only.
Why it matters: depending on how picard.m parses options, the MATLAB side either errors on an unknown parameter or ignores the iteration cap and runs at its own default. In the second case, the test no longer compares the two sides under matched settings, which is the premise of this change. Note that I could not check this against the picard plugin source, which is not vendored here. Please confirm against the pinned plugin, or by printing the iteration count on the MATLAB side.
Fix: pass the MATLAB-side name to the engine call:
| matlab_eeg = _Side(matlab.engine).wrapper.eeg_picard(p300_clean, **picard_options) | |
| matlab_eeg = _Side(matlab.engine).wrapper.eeg_picard(p300_clean, tol=PICARD_TOL, maxiter=PICARD_MAX_ITER) |
There was a problem hiding this comment.
🤖 This test refuses to run unless MATLAB eeg_picard calls picard_python_port (mind-inria/picard 617ce6ae669cfbd1dfedba6a5fce39a602b99ac3). That function documents and reads 'max_iter': it sets opt.max_iter = 512 and stops on opt.max_iter. Unknown names are stored with opt.(lower(name)) and are not rejected, so 'maxiter' would set opt.maxiter and leave the cap at 512. The 'maxiter', 500 strings in pop_runica are the older EEGLAB menu presets, which the Python wrapper remaps to max_iter. Passing max_iter is the name both sides of this comparison actually honor.
…-average-reference-e0e5 Co-authored-by: Suraj Ranganath <[email protected]> # Conflicts: # docs/source/changelog.rst
Co-authored-by: Suraj Ranganath <[email protected]>
There was a problem hiding this comment.
If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.
Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.
|
Claude finished @suraj-ranganath's task in 44s —— View job Code review
BlockingNone. Important
NitsNone. Test gapsNone.
EEGLAB parity notes
I did not run any tests. This review is a static read of the diff at 85eb1c5. |

Average reference now sums in float64 and casts once to the input dtype, so float32 stays float32 and the result does not depend on the BLAS kernel or thread count. On ds003061 sub-001 (64 channels, 194048 samples, peak 259369.28125 µV) the old float32 product matched MATLAB on SkylakeX and missed by 0.109375 µV on Haswell (RMS 0.00235126327796 µV). MATLAB's single-precision result is 0.15625 µV (RMS 0.004684294629 µV) from the correctly rounded float32 value, above every existing tolerance, so the stage test keeps REREF_ATOL at 1e-5 against that oracle and checks EEGPrep is at least as close as EEGLAB. The MATLAB reference suite was not run here (EEGLAB d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4, eeglab_tests fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9).
The cleaned-data Picard comparison now passes the same tol and max_iter into Python eeg_picard and MATLAB eeg_picard, still with identity initialization. PICARD_TOL is 1e-10 and PICARD_MAX_ITER is 2048. At the default tol of 1e-7 both sides converge, but this recording is weakly conditioned and they stop at slightly different points, so AMARI tracks that stopping point. Running both sides to 1e-12 with 4096 iterations brought AMARI to 2.78e-10. PICARD_AMARI_MAX stays 1e-5, the matched-correlation check stays, and production defaults are unchanged. The test timeout is 1800 seconds so the longer run is allowed.
MATLAB verification
On jamming on 2026-11-15 (MATLAB R2025b, EEGLAB d0963be9, eeglab_tests fec88f9f), sub-001 at tol=1e-10 and max_iter=2048 gave AMARI 5.85e-7 and corr_mean 1.000000 in about 7 minutes. At tol=1e-9 it gave AMARI 1.90e-6 and corr 1.000000 in about 2 minutes. No ceiling was changed.
Fixes #579