Skip to content

Sum average reference in float64 before casting to the input dtype - #606

Merged
suraj-ranganath merged 5 commits into
developfrom
cursor/fix-float32-average-reference-e0e5
Nov 18, 2026
Merged

suraj-ranganath merged 5 commits into
developfrom
cursor/fix-float32-average-reference-e0e5

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

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

Open in Web Open in Cursor 

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]>

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

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

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Code review in progress

  • Pre-review gate
  • Read diff and instructions
  • Review passes (AGENTS.md, conventions, correctness, EEGLAB parity)
  • Post review

View job run

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 19:27
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 19:27
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 18s —— View job


Code review

  • Overall assessment: The core change is correct and simpler. The float32 BLAS matmul and its errstate workaround are replaced by a float64 elementwise block - block.mean(axis=0) and a single cast back to the input dtype. That removes the dependence on BLAS kernel and thread count. I checked reref.py (all branches: average, explicit ref, exclude, refloc, Huber), the new exact-rounding oracle, the stage-parity and fuzz-harness test changes, and the docs/help updates.
  • Highest-risk area: Pipeline outcomes after reref. The deleted comment said bit-exact float32 reref mattered for ICA convergence on borderline subjects. This PR moves EEGPrep up to 0.156 µV away from EEGLAB on ds003061.
  • Merge recommendation: Needs the MATLAB reference run before merge. The code itself looks fine.

Blocking

None.

Important

  • MATLAB reference evidence is missing for a core-function change (src/eegprep/functions/sigprocfunc/reref.py). AGENTS.md §Testing requires one run of eeglab-reference.yml (or a local --eeglab-backend=matlab run) on the final branch before merge. The PR body says it was not run.
    • This matters more than usual here. The old code was bit-exact to EEGLAB on SkylakeX. The new code sits up to 0.15625 µV away. The removed comment warned that a ~0.06 µV reref difference "cascades through nonlinear downstream steps (ICA convergence) for borderline subjects".
    • The per-stage tests are safe: they feed the same p300_reref into both sides. The end-to-end summary in tests/parity_expected/ds003061_pipeline.json (13 subjects, exact keys such as channels_removed) is not. It could change.
    • Fix: trigger the EEGLAB reference workflow on this branch, plus the ds003061 pipeline parity. Add the commits, counts, and runtime to the PR body. If any subject's summary changes, explain it as part of the documented deviation rather than regenerating the expected file without comment.

Nits

  • reref.py:81,85: dtype=np.float64 is redundant. Line 53 already promotes work to at least float64, and the explicit dtype only downcasts longdouble input. Details are in the inline comment.
  • resources/help/pop_reref.md and reref.md: the end-user help now carries benchmark detail ("OpenBLAS Haswell", thread count, RMS to 12 digits), copied word for word in both files. A single sentence would suffice in Help, e.g. "Average reference on float32 data is computed in float64 and stored as float32; results can differ from EEGLAB's single-precision product by up to ~0.16 µV on large-amplitude recordings. See the EEGLAB migration guide." Leave the measurements in eeglab_migration.rst. The changelog could be trimmed the same way.

Test gaps

None. test_float32_average_reference_matches_exact_rounding checks against an integer-arithmetic oracle, not against the implementation's own arithmetic. It covers continuous, epoched, exclude, and refloc paths. Its adversarial input really does break a naive float32 mean. The updated fuzz-harness test now asserts that float32 stays inside the approved pop_reref tolerance and keeps its dtype.

EEGLAB parity notes

  • This is an intentional deviation from EEGLAB's refmatrix * data in single precision. It is documented in eeglab_migration.rst and locked by tests, which follows the policy that a documented, tested deviation is not a parity bug.
  • The stage test no longer bounds EEGPrep against EEGLAB directly. It bounds EEGPrep against the correctly rounded float32 result and requires EEGPrep to be at least as close as EEGLAB. That is a sound oracle, and REREF_ATOL is unchanged.

I could not run the tests in this environment (permission to run uv run pytest was denied), so this review is a static read of the code.

Comment on lines +81 to +85
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.)

cursoragent and others added 2 commits November 11, 2026 19:29
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]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 12, 2026 05:26
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 12, 2026 05:26
@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 13s —— View job


Code review

  • Overall assessment: The reref.py change is correct, and the earlier dtype=np.float64 nit is fixed in 3e1efd9. This re-review covers the new Picard commit (c1d07b6), the reref branches (average, explicit ref, exclude, refloc), the exact-rounding oracle, and the stage-parity and fuzz-harness test changes.
  • Highest-risk area: The cleaned-data Picard parity test probably does not send the matched iteration cap to MATLAB.
  • Merge recommendation: Needs changes. Fix the option name and add the MATLAB reference evidence.

Blocking

None.

Important

  • Picard option name on the MATLAB side (tests/test_ds003061_stage_parity.py:570-572)
    • Problem: MatlabWrapper passes kwargs through as name/value pairs unchanged. MATLAB therefore receives 'max_iter', 2048, but picard.m names this option 'maxiter' (see EEGLAB's own picard presets in pop_runica.py:26-28).
    • Why it matters: MATLAB either errors on the unknown parameter or ignores the cap. If it ignores it, the test no longer compares the two sides under matched settings, which is the premise of this change.
    • Fix: use maxiter=PICARD_MAX_ITER for the MATLAB call and keep max_iter for the Python eeg_picard. I could not check this against the picard plugin source, which is not vendored, so please confirm against the pinned plugin.
  • MATLAB reference evidence is still missing for a core-function change (src/eegprep/functions/sigprocfunc/reref.py)
    • Rule: AGENTS.md §Testing requires one eeglab-reference.yml run (or a local --eeglab-backend=matlab run) on the final branch before merge. The PR body still says it was not run.
    • Why it matters: the removed code was bit-exact to EEGLAB on SkylakeX. The deleted comment tied a ~0.06 µV reref difference to ICA convergence changes on borderline subjects. tests/parity_expected/ds003061_pipeline.json has exact keys (e.g. channels_removed) that could shift.
    • Fix: run the reference workflow and the ds003061 pipeline parity, then add the commits, counts and runtime to the PR body. Explain any summary change as part of the documented deviation.

Nits

  • resources/help/pop_reref.md and reref.md repeat the same benchmark paragraph (OpenBLAS Haswell, thread count, RMS to 12 digits) in end-user Help.
    • Fix: one sentence is enough in Help. The measurements belong in eeglab_migration.rst.

Test gaps

None. exact_float32_average_reference is an independent integer-arithmetic oracle, not a rebuild of the implementation. It covers continuous, epoched, exclude and refloc paths, and its adversarial input does break a naive float32 mean.

EEGLAB parity notes

  • The average reference now deliberately differs from EEGLAB's single-precision refmatrix * data (reref.m). This is documented in eeglab_migration.rst and locked by tests, so it is not a parity bug.
  • The stage test now bounds EEGPrep against the correctly rounded float32 result at the unchanged REREF_ATOL, and requires EEGPrep to be at least as close as EEGLAB. That is a sound oracle.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: MatlabWrapper turns kwargs into name/value pairs word for word (

kwargs_list = []
for key, value in kwargs.items():
kwargs_list.append(f'{key}')
kwargs_list.append(value)
new_args.extend(kwargs_list)
), so MATLAB gets 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 (
("runamica15", "AMICA (slowest; best)", "'maxiter', 2000"),
("picard", "Infomax picard.m", "'maxiter', 500, 'mode', 'standard'"),
("picard", "FastICA picard.m (fastest)", "'maxiter', 500"),
). 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:

Suggested change
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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.

cursoragent and others added 2 commits November 18, 2026 07:04
…-average-reference-e0e5

Co-authored-by: Suraj Ranganath <[email protected]>

# Conflicts:
#	docs/source/changelog.rst
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 07:06
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 07:06

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

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

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 44s —— View job


Code review

  • Overall assessment: The code is correct. This pass re-checked reref.py, the exact-rounding oracle, the stage-parity and fuzz-harness tests, and the help text at 85eb1c5. All the earlier code findings are resolved:
    • The redundant dtype=np.float64 is gone (3e1efd9).
    • The Help text is now one sentence (85eb1c5).
    • The max_iter / maxiter question is settled. The test requires MATLAB eeg_picard to call picard_python_port, and that function reads opt.max_iter. Python eeg_picard accepts tol and max_iter as well (eeg_picard.py:61-62).
  • Highest-risk area: How the reref change affects the end-to-end ds003061 pipeline. Single stages are covered.
  • Merge recommendation: The code is ready, but merge waits on the MATLAB reference evidence below and on human approval.

Blocking

None.

Important

  • The MATLAB reference run is still missing for a core-function change (src/eegprep/functions/sigprocfunc/reref.py). AGENTS.md §Testing says: "Before merging a PR that changes core function implementations … trigger .github/workflows/eeglab-reference.yml … or run the suite locally once on the final branch". The commits, counts and runtime must go in the PR body.
    • The PR body now reports a MATLAB run of the Picard stage test, but it also says "The MATLAB reference suite was not run here."
    • The old code matched EEGLAB bit for bit on SkylakeX. The new code can be up to 0.156 µV away. The stage tests feed the same p300_reref into both sides, so they cannot show what that gap does downstream. tests/parity_expected/ds003061_pipeline.json has exact keys (for example channels_removed) that could change for borderline subjects.
    • Fix: run eeglab-reference.yml on this branch (or the local --eeglab-backend=matlab command with the pinned roots) and the ds003061 pipeline parity. Put the result in the PR body. If any subject's summary changes, explain it as part of the documented float64-sum deviation; don't silently regenerate the expected file.

Nits

None.

Test gaps

None.

  • exact_float32_average_reference is an independent integer/long-double oracle, not a rebuild of the implementation. It covers the continuous, epoched, exclude and refloc paths, and the adversarial input really does break a naive float32 mean.
  • The fuzz-harness test now asserts that float32 keeps its dtype and stays inside the approved pop_reref tolerance.
  • The tolerances are unchanged (REREF_ATOL, PICARD_AMARI_MAX, tests/fuzz/tolerances.toml).

EEGLAB parity notes

  • The average reference now deliberately differs from EEGLAB's single-precision refmatrix * data (reref.m).
  • That difference is documented in eeglab_migration.rst and the Help resources, and locked by test_float32_average_reference_matches_exact_rounding. Under the repo's policy it is not a parity bug.
  • The stage test now bounds EEGPrep against the correctly rounded float32 result and requires it to be at least as close as EEGLAB. That is a sound oracle.

I did not run any tests. This review is a static read of the diff at 85eb1c5.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Float32 average reference fails the 64-channel EEGLAB comparison by 0.109375 uV

2 participants