Skip to content

Batch cluster score sums and their cross-product - #878

Open
soodoku wants to merge 1 commit into
bashtage:mainfrom
finite-sample:perf/grouped-score-covariance
Open

soodoku wants to merge 1 commit into
bashtage:mainfrom
finite-sample:perf/grouped-score-covariance

Conversation

@soodoku

@soodoku soodoku commented Nov 21, 2026

Copy link
Copy Markdown

The clustered covariance is the sum of the outer products of the cluster score totals, divided by the number of observations. After sorting the labels once, this change uses NumPy's segmented addition (np.add.reduceat) to sum contiguous runs and a single matrix multiplication for all the outer products. The same group boundaries also supply the existing check for fewer than two groups. The regression test adds a singleton cluster to the independent summation check.

I timed the complete public PooledOLS(y, x).fit(cov_type="clustered", ...) call including model construction and the first evaluation of its lazy .cov property. I also measured the first .cov access separately. Median milliseconds from five alternating baseline/candidate blocks after warmup, Python 3.13.16, NumPy 2.5.5, pandas 3.1.1, arm64 macOS, one BLAS thread.

Entities × periods Regressors Clustering Model + fit + covariance, before → after Covariance, before → after
40 × 5 4 entity 9.27 → 6.83 0.26 → 0.12
1,500 × 4 4 entity 14.64 → 11.38 2.92 → 0.29
1,500 × 4 4 entity and time 23.32 → 12.43 13.46 → 0.98
8,000 × 4 8 entity 50.23 → 32.38 16.41 → 1.58
8,000 × 4 8 entity and time 118.10 → 35.99 83.41 → 5.50

I checked both versions against statsmodels OLS and its one- and two-way clustered sandwich estimators with corrections off. The largest absolute coefficient and covariance differences were 1.43e-14 and 6.08e-17. Floating-point summation order changes: both implementations can lose precision when within-cluster scores nearly cancel at the limit of float64.

Local full installed-package suite: 23,686 passed, 2,476 skipped, 47 xfailed, one failure. The same test fails at the same line on a separately built wheel from unmodified parent d7980a7: test_constant_dependent_variable_panel[RandomEffects-0.1] divides 0 by 0 in the random-effects variance decomposition, before evaluating any clustered covariance.

Minimal large fixture (time the entire body from model construction through first covariance access):

import numpy as np
import pandas as pd
from linearmodels.panel import PooledOLS
from threadpoolctl import threadpool_limits

rng = np.random.default_rng(8914)
idx = pd.MultiIndex.from_product([range(8000), range(4)])
x = pd.DataFrame(rng.normal(size=(len(idx), 8)), index=idx)
y = pd.Series(x.to_numpy() @ np.arange(8) + rng.normal(size=len(idx)), index=idx)
with threadpool_limits(1):
    fit = PooledOLS(y, x).fit(cov_type="clustered", cluster_entity=True,
                              cluster_time=True, debiased=False, group_debias=False)
    cov = fit.cov.to_numpy()

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T07:27:37.682711Z a2fee08 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (d7980a7) to head (a2fee08).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #878      +/-   ##
==========================================
- Coverage   99.69%   99.69%   -0.01%     
==========================================
  Files         202      202              
  Lines       38871    38866       -5     
  Branches     2501     2501              
==========================================
- Hits        38752    38747       -5     
  Misses         51       51              
  Partials       68       68              
Flag Coverage Δ
adder 99.68% <100.00%> (-0.01%) ⬇️
subtractor 99.68% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
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.

1 participant