← Back to Pull requests

PERF: avoid pearson correlation L3 cache regression #68

Open
xirafa opened this pull request with 74 lines diff across 4 files
View on GitHub
xirafa xirafa commented on Jul 29, 2026 09:10 UTC
Author

Mirror of pandas-dev/pandas#66409. Runs the pandas test suite through dagz.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

Summary by CodeRabbit

Bug Fixes
Improved Pearson correlation calculations for greater numerical stability and accurate results, including correct handling of zero-variance data.
Correlation results are constrained to the valid range of -1.0 to 1.0.

Documentation
* Updated the Series.autocorr example to show the exact result for a lag of 2.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Diff: 74 lines (+2 / -72) across 4 files Reviewer: coderabbitai[bot] Review duration: 187515m
All Vouch review confidence checks passed
Residual risk 0.11 = Change Risk (0.45) × (1 − Review Confidence (0.77)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.45 · 74 lines diff across 4 files
0.45
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.63 · 1 substantive comment(s)
0.63
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
76%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.258
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
1 comments
pandas/core/nanops.py
"_🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash python - <<'PY' import numpy as np def candidate(values): a = np.asarray(values, dtype=np.float64) a = a - a.mean() var_a = np.dot(a, a) if var_a == 0: return np.nan cov_ab = np.dot(a, a) r_abs = np.sqrt((cov_ab / var_a) * (cov_ab / var_a)) return np.clip(r_abs, -1.0, 1.0) for values in ([1e200, 2e200, 3e200], [1e-200, 2e-200, 3e-200]): result = candidate(values) print(values[0], result) assert not np.isfinite(result), result PY ``` Repository: autodag-dev/pandas Length of output: 359 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail echo "== locate file and relevant symbols ==" git ls-files | rg '(^|/)nanops\.py$' wc -l pandas/core/nanops.py echo echo "== target lines ==" sed -n '1640,1725p' pandas/core/nanops.py | nl -ba -v1640 echo echo "== surrounding/correl functions ==" rg -n "_pearson_corr|pearson|corr|nanops|_variance" pandas/core/nanops.py | head -200 ``` Repository: autodag-dev/pandas Length of output: 305 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail echo "== target lines ==" sed -n '1687,1699p' pandas/core/nanops.py echo echo "== surrounding block 1600-1730 ==" sed -n '1600,1730p' pandas/core/nanops.py echo echo "== imports/options around nanops ==" sed -n '1,80p' pandas/core/nanops.py echo echo "== search max abs scaling / pearson helpers ==" rg -n "max(abs|max_abs|pearson|_pearson|_nancorr|_nanvar|nanvar|nanstd|isna|isnull)" pandas/core/nanops.py | head -250 ``` Repository: autodag-dev/pandas Length of output: 5131 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail echo "== current _pearson implementation ==" sed -n '1730,1780p' pandas/core/nanops.py echo echo "== search current/previous _pearson_corr occurrences ==" rg -n "def _pearson_corr|pearson_corr|max\(|abs\(" pandas/core/nanops.py echo echo "== deterministic finite-dot overflow/underflow behavior ==" python3 - <<'PY' import numpy as np def direct_dot(values): a = np.asarray(values, dtype=np.float64) a = a - a.mean() return np.dot(a, a) for values in ([1e200, 2e200, 3e200], [1e-200, 2e-200, 3e-200], [1, 2, 3]): try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") v = direct_dot(values) print(values[0], "direct_dot=", v, "isfinite=", np.isfinite(v), "iszero=", v == 0, "warnings=", [str(m.message) for m in w]) except Exception as e: print(values[0], type(e), str(e)) PY ``` Repository: autodag-dev/pandas Length of output: 3094 --- 🌐 Web query: `numpy floating point dot product overflow underflow runtime warning inf nan` 💡 Result: In NumPy, the behavior of np.dot regarding floating-point errors (overflow, underflow, invalid operations) is historically inconsistent with other NumPy ufuncs like np.multiply or np.matmul [1][2]. While most arithmetic operations in NumPy check for and report floating-point exceptions (resulting in RuntimeWarning or raising a FloatingPointError if configured), np.dot often bypasses these checks [1][3]. Key observations regarding np.dot and floating-point/integer issues include: Floating-Point Exceptions: Unlike np.multiply, np.dot frequently fails to trigger RuntimeWarning or raise a FloatingPointError when operations result in inf or nan values [1][3]. This is a known limitation that stems from the way np.dot offloads computations to optimized BLAS libraries, which do not always integrate with NumPy's internal error-reporting mechanisms [2][4][5]. Error Handling Configuration: You can configure NumPy's global error reporting using np.seterr or the np.errstate context manager [6][7][8]. However, because of the aforementioned implementation details, these settings (e.g., seterr(over='raise')) may effectively catch errors during standard arithmetic operations but remain ignored by np.dot [1][3]. Integer Overflow: NumPy generally does not perform overflow checks for integer operations, and np.dot is no exception [9][7]. Unlike floating-point types, integer overflows in NumPy typically result in silent wraparound rather than inf or nan values, and np.seterr settings have limited impact on these cases [2][9][7]. Recommended Alternatives: If consistent error handling is required, users are often advised to use np.matmul or the @ operator, which are more strictly integrated with NumPy's error-handling infrastructure [1][3]. For critical numerical stability, verify inputs for inf or nan values using np.isinf or np.isnan before performing high-dimensional dot products, as precision differences—particularly when using BLAS backends like MKL—can lead to varying results based on array shape and system architecture [5][10]. Current Development: Ongoing efforts in the NumPy project aim to improve the consistency of error checking in np.dot by adding internal checks, though some cases (such as certain multiplications involving nan or inf, and integer overflows) remain challenging to resolve due to performance considerations and the underlying BLAS reliance [2]. Citations: - 1: https://stackoverflow.com/questions/64401148/numpy-doesnt-throw-floatingpointerror-for-dot-product - 2: https://github.com/numpy/numpy/issues/28442/linked_closing_reference?reference_location=REPO_ISSUES_INDEX - 3: https://github.com/numpy/numpy/issues/14788 - 4: https://numpy.org/doc/stable/reference/generated/numpy.dot.html - 5: https://github.com/numpy/numpy/issues/15591 - 6: https://numpy.org/doc/stable/reference/routines.err.html - 7: https://numpy.org/doc/stable/reference/generated/numpy.seterr.html - 8: https://numpy.org/doc/stable/reference/generated/numpy.errstate.html - 9: https://github.com/numpy/numpy/issues/4126 - 10: https://github.com/numpy/numpy/issues/11655 --- </details> **Preserve a scaled fallback for extreme finite inputs.** The direct dot products in `_pearson_corr` can overflow/underflow before normalization, so `Series([1e200, 2e200, 3e200]).corr(...)` and the analogous `1e-200` input can return `NaN` instead of `1.0`. The zero-variance checks also misclassify underflowed variance as constant; keep the fast path, but fall back to scaling whenever intermediate variance/covariance values are non-finite or variance is zero before `a` and `b` are both centered to zero. <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pandas/core/nanops.py` around lines 1687 - 1699, Update _pearson_corr to retain the current dot-product fast path but add a scaled fallback when var_a or var_b is non-finite or zero, or when cov_ab is non-finite. Scale a and b before recomputing variance and covariance so extreme finite inputs do not overflow or underflow, while preserving the zero-variance result when centered data is genuinely constant. ``` </details> <!-- fingerprinting:phantom:poseidon:terra --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6fb4578959e6f869efa2c6dd --> <!-- This is an auto-generated comment by CodeRabbit -->"
logic_concern weight: 0.8
Assignees
xirafa xirafa
Labels
risk: low confidence: 76.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 45.2% (MEDIUM) · Higher = larger blast radius
45.2%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 76.6% · Lower = rushed or shallow review
76.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 10.6% · Safe to merge
10.6%