Skip to content

fix(efficient_did): PT-All moment set, Eq 3.10 score centring, Hausman variance, exact label arithmetic, roundoff SE guard - #924

Open
igerber wants to merge 24 commits into
mainfrom
fix/efficient-did-correctness
Open

igerber wants to merge 24 commits into
mainfrom
fix/efficient-did-correctness

Conversation

@igerber

@igerber igerber commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Summary

Pre-existing EfficientDiD defects, found while reviewing the EfficientDiD tutorial in #920. Each reproduces on main. The first three were the planned scope; the rest surfaced while fixing and testing them.

Estimator math (closer to the paper)

  • One never-treated moment under PT-All. The estimator stacked a never-treated moment (inf, t_pre) per baseline. Without covariates these are all the same long difference-in-differences against the first period, and Eq 3.12 applied to them omits the cross-covariance between their two never-treated terms, so Omega* and the PT-All weights were wrong wherever a never-treated pair entered. enumerate_valid_triples now emits the single pair (inf, period_1), for which Eq 3.12 is exact (Eq 3.11's "noncollinear" stacking). The four Omega* builders are unchanged.
  • Covariate-path scores centred as in Eq 3.10. Scores were centred on the scalar ATT instead of (G_g / pi_g) ATT(g, t), adding ATT^2 (1 - pi_g) / pi_g to the variance, so covariate-path standard errors grew with the size of the effect.
  • Cohorts with no pre-treatment period. Under PT-All a cohort with g - anticipation <= period_1 was fitted silently against a baseline that was not one. It is now dropped with a UserWarning, as PT-Post already did.

Hausman pretest

  • Variance from paired influence-function differences (the alternative estimator of the paper's footnote 21). Eq A.2's difference of covariances equals it only when PT-All is exactly efficient in the sample; the default ridge, cluster= and aggregation over cells break that. The estimate is positive semidefinite by construction, so the negative-eigenvalue warning is gone.
  • Same cells on both sides. When periods have gaps PT-Post can drop a cohort PT-All keeps; the pretest now aggregates only cells both fits estimate, warns naming the cohorts left out, and is inconclusive (NaN, with a warning) when one side can estimate nothing or the contrast has no sampling variation.

Numerical robustness (not from the paper)

  • Exact label arithmetic. Unsigned labels wrapped in g - anticipation and t - g; integer labels above 2**53 were copied to float64 and merged cohorts; large or fractional float differences rounded onto the wrong horizon; a baseline computed in two rounded steps could match a period it was not equal to. Every label difference and cross-column comparison now goes through diff_diff.utils.exact_label / label_minus / event_time_bucket / matching_period (Python ints and Fraction). A float label column beyond its dtype's exact integer range raises, as do non-finite period labels and missing or negative cohort labels.
  • Roundoff-level standard errors. A statistic with no sampling variation had an SE near 1e-17 instead of 0, and a noiseless panel with a true effect of 0 could report p < 0.01. Every reported SE is now tested with the shared helper diff_diff.utils.se_is_roundoff (se * sqrt(n) <= 1e4 * eps * outcome scale): SE 0 analytically, NaN under the bootstrap, NaN inference in both, with a warning. The helper is written for adoption by the other influence-function estimators (TODO row); only EfficientDiD uses it here.
  • aggregate("total") counts the cells the overall ATT was built from, which a fit now records. For a result saved by an earlier release the selection is reconstructed only when the old label arithmetic was certainly exact (ordinary integer labels, or single-dtype floats without anticipation); otherwise it raises a ValueError asking for a refit.

Measured (seeded; benchmarks/python/edid_omega_conditioning.py unless noted)

Check main This PR
Hausman, null, three periods, 2,000 panels: mean H/df, 5% rejection 0.667, 1.7% 0.96, 4.3%
Hausman, null, period 1 within 1e-3 of period 0, 1,000 panels 0.20, 0.0% (difference-of-covariances form) 0.99, 4.6%
Hausman, null, 40 clusters of 6, cluster=, 500 panels 0.76, 2.8% (scratch probe, similar design) 1.15, 6.4%
HRS Table 6, worst deviation in published SE: ATT(g,t) / ES(e) / ES_avg 0.0257 / - / - 0.0019 / 0.0016 / 0.0004
Covariate SE over sampling SD at true ATT 0 / 2 / 10, 500 panels 0.96 / 1.24 / 4.05 0.96 / 0.96 / 0.96
Same panel with every label shifted by 2**53: ATT 1.31 (1.89 unshifted) identical to unshifted
Noiseless panel, true effect 0: p-value below 0.01 NaN, with a warning
300-unit, 10-period example: ATT / SE 1.9808 / 0.0366 1.9797 / 0.0362

Known limitation, documented, not fixed here. On staggered designs the multi-horizon Hausman pretest is conservative and does not converge to nominal size: 3.0% rejections at the 5% level with 80 units per group and 3.2% with 300 (seven periods, cohorts at 3 and 5). The difference-of-covariances form drifts the same way on those panels. REGISTRY Hausman Note and a TODO.md row (rank-revealing df) cover it.

Deferred to TODO.md. Adopting the roundoff guard and the exact label helpers in the other staggered estimators; dropping the degenerate self-pair at omega_ridge=0.

Oracle fixture

tests/fixtures/v4_aggregate_oracles.json pins EfficientDiD at rtol 1e-12. tests/_recapture_v4_edid_oracles.py rebuilds only the EfficientDiD arms; on the unmodified tree it reproduced every stored value on both backends (largest relative difference 5.7e-13) before any library change. After the fixes, point estimates in the fixture arms move by at most 0.61 stored SE and standard errors by under 11%, except the two replicate-weight arms (33-43%) and the covariate bootstrap arm (81%, from the centring fix). Every other estimator's entries are byte-identical.

Not in this PR

docs/tutorials/15_efficient_did.ipynb on main says "Period 1 is excluded ... using it as a baseline adds no information", which this change makes inaccurate. #920 replaces that notebook and is rebased straight after this merges; the notebook on main still executes.

Methodology references (required if estimator / math changes)

  • Method name(s): EfficientDiD (efficient DiD and event-study estimators; Hausman PT-All vs PT-Post pretest)
  • Paper / source link(s): Chen, Sant'Anna & Xie (2025), arXiv:2506.17729v1 - Eq 3.9-3.12, Theorem 4.1, Theorem A.1 and Eq A.2, footnote 21
  • Any intentional deviations from the source (and why): the Hausman variance uses the footnote-21 paired-difference estimator instead of the printed difference of covariances (equal asymptotically under efficiency; valid without it). The roundoff guard and the exact-label rules are library conventions. All are recorded as REGISTRY **Note:** entries, together with Notes for the PT-All moment set, the Eq 3.10 centring, cohorts without a pre-treatment period, and the omega_ridge Note re-measured on the corrected moment set.

Validation

  • Tests added/updated: tests/test_methodology_efficient_did.py (TestNeverTreatedMoment, TestHausmanStatistic, TestHausmanCalibration, TestCovariateScoreCentring), tests/test_efficient_did.py (TestValidTriples, TestNanInference, TestCohortWithoutPreTreatmentPeriod, TestLargeIntegerLabels, TestRoundoffScores), tests/test_utils.py (TestRoundoffStandardErrorHelpers, TestExactLabelArithmetic), tests/test_efficient_did_validation.py (HRS tolerance 0.05 -> 0.01 SE), tests/test_anticipation_policy.py, tests/test_aggregate_contract.py (re-baselined fixture), tests/_recapture_v4_edid_oracles.py (new).
  • With the old behaviour patched back in-process, the four core test files fail: 32 tests for the moment set, 21 for score centring, 26 with the roundoff guard off, 15 with native label arithmetic.
  • Every test file that references the estimator passes on both backends (5,778 on Rust, 5,256 on pure Python); the fixture --check is clean on both.
  • Backtest / simulation / notebook evidence (if applicable): benchmarks/python/edid_omega_conditioning.py (seeded; prints the figures quoted in the REGISTRY Notes); pytest --nbmake docs/tutorials/15_efficient_did.ipynb passes; Sphinx -W build clean.

Security / privacy

  • Confirm no secrets/PII in this PR: Yes

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): Yes

…f the 4.0 aggregate oracle fixture

Rebuilds only the EfficientDiD numeric leaves from the public fit() + aggregate()
API. --check on the unmodified tree reproduces every leaf at the contract
tolerances on both backends (largest relative shift 5.7e-13).
Every (inf, t_pre) moment of Eq 3.9 is the same long difference-in-differences,
and Eq 3.12 omits the cross-covariance between its two never-treated terms, so
stacking one per baseline gave a wrong Omega*, inefficient PT-All weights and a
miscalibrated Hausman pretest (statistic mean 0.667 under the null, 1.7%
rejections at the 5% level). enumerate_valid_triples now emits the single pair
(inf, period_1), for which Eq 3.12 is exact; the four Omega* builders are
unchanged. HRS Table 6 is reproduced to 0.002 published SE (was 0.026).
…s Eq 3.10 does

The covariate path subtracted the scalar ATT from each per-unit score. The two
centrings share a mean but differ by ATT (G_g/pi_g - 1) unit by unit, a term of
variance ATT^2 (1 - pi_g)/pi_g, so covariate-path standard errors grew with the
size of the effect (noiseless panel, ATT 2: SE 0.1414 where the no-covariate
fit and Callaway-Sant'Anna DR give 0). Point estimates are unchanged.
…PT-All; unsigned labels no longer wrap

A cohort with g - anticipation <= period_1 has no untreated baseline. PT-Post
already drops it with a warning; PT-All estimated it silently against a baseline
that was not one (cell estimates near 0 against a true 2). It is now dropped the
same way, so the Hausman pretest compares the same cohorts on both sides.

Unsigned period or cohort labels are converted to signed on entry: g - anticipation
and t - g wrapped around for them, bypassing the cohort guards.
…te oracle fixture

Numeric leaves only, from the public API, once per weight backend. Every other
estimator's subtree is byte-identical; the routine reproduced the original
capture on the pre-correction tree first.
…r the conditioning, stability, anchor and calibration figures

REGISTRY Notes for the single never-treated moment, the Eq 3.10 score centring
and the cohort drop; the ridge and Hausman Notes rewritten from re-measured
figures; METHODOLOGY_REVIEW correction entry; changelog fragment; TODO rows.
…o labels above 2**53 no longer merge cohorts

Float label columns with magnitudes of 2**53 or more raise. Also: the oracle
re-capture routine starts a fresh round per commit, the conditioning script
counts exactly singular matrices, and the HRS wording says within 0.002 SE.
…aired influence-function differences

Theorem A.1's difference of covariances is the variance of the contrast only
under exact efficiency, which the ridge, clustering and cross-cell aggregation
break in a finite sample. Registry Notes for the variance, the staggered
conservativeness and roundoff-level standard errors on noiseless data; TODO rows
for a rank-revealing df and a shared roundoff guard.
…est aggregates only cells both fits estimate

Narrow floats are widened and refused beyond their exact integer range. On
panels with period gaps PT-Post can drop a cohort PT-All keeps; the pretest
leaves it out of both sides and warns. The paired variance is the paper's
footnote-21 alternative; df is described as an effective rank. The oracle
re-capture routine gets explicit rounds.
…man pretest is inconclusive when one side estimates nothing

Integer periods of magnitude 2**53 or more beside a float cohort column are
converted to integers together (the mixed difference put a period one horizon
early); labels that cannot be made exact raise. Pandas nullable floats are
accepted. A re-capture round no longer inherits the previous round's record.
…nce, through a shared helper

utils.scores_are_roundoff / outcome_scale: scores no larger than 1e4 machine
epsilons times the outcome magnitude are residue. EfficientDiD replaces such a
cell's scores by exact zeros (SE 0, NaN t/p/CI; constant bootstrap; inconclusive
Hausman pretest), applies the same test to every aggregate after its
weight-influence term, and warns once per fit. Registry Note, changelog, and a
TODO row for adopting the helper in the other influence-function estimators.
…ed support; one exactness rule for labels

A bootstrap aggregate whose cell scores cancel gets a constant distribution;
scale and scores are taken over positive-weight units; zeroed scores go through
the usual variance routine, so an undefined replicate variance stays NaN. Labels
below 2**52 are exact in float64 whatever the dtype mix; above it both columns
become integers or the input is refused.
…rify label differences are exact; validate label values

The roundoff test moves from scores to the standard error about to be reported
(utils.se_is_roundoff), so it holds for cluster sums, replicate weights and
bootstrap draws alike. Label arithmetic is checked with an error-free
transformation instead of magnitude thresholds. Missing or negative cohort
labels and non-finite period labels raise.
…ausman roundoff scale from the fits; warnings from the published inference path

A rounded label difference matters only if it lands on an integer (event-time
bucket) or on a period label (baseline lookup), so decimal labels pass. The
Hausman residue check uses the outcome scale the fits recorded. A bootstrapped
fit reports its own residue.
… helpers

Relative times, baseline lookups and pre-treatment comparisons go through
utils.exact_label / label_minus / event_time_bucket / matching_period (ints and
Fractions), so they are exact for any dtype mix, magnitude or fractional part,
and independent of the order of subtraction. The float-arithmetic validator is
removed. A post-fit bootstrap replay warns only about the statistics it returns.
…uilt from

A fit records the cells of the overall ATT in the aggregation kit; a kit saved
by an earlier release reproduces that release's selection. Comparison pairs are
enumerated once per cohort. The label-invariance claim is limited to
relabellings that preserve exact label differences.

Full two-backend verification of this commit was still running when it was made.
… the stored ATT

For a kit with no record of the overall ATT's cells, cells within rounding of
the anticipation boundary are resolved by which selection reproduces the stored
ATT; an unrecoverable selection raises and asks for a refit. A fit selects the
overall ATT's cells once and passes them to the aggregation.

Full two-backend verification of this commit was still running when it was made.
…ed ATT

Recovery for kits with no record tries the exact selection, then per-cohort
cut-offs moved by one period, and accepts a set only if its weighted mean is
the stored ATT; otherwise aggregate('total') asks for a refit. No tolerance on
labels. Saved-result tests carry inference consistent with the stored ATT.
…l cell selection

For kits with no record, the post-anticipation cells are selected as native
arithmetic did under each of the two NumPy promotion rules; when the two differ
the stored ATT decides, and aggregate('total') asks for a refit when it cannot.
Replaces the neighbour search, its tolerance and its cohort cap.
…label arithmetic was certainly exact

For a kit with no record of the overall ATT's cells, the exact selection is
used when native label arithmetic cannot have differed from it (integral labels
of ordinary size, or no anticipation); otherwise aggregate('total') asks for a
refit. Replaces the reconstruction of historical NumPy arithmetic.
…rvive the narrowest float type present

A Python float compared with a float32 label is rounded to float32 under
NumPy 2, so no-anticipation results were not always exact. Labels of mixed
precision that do not all fit the narrowest one now ask for a refit.
…name mixed-precision labels; a public-API test for that case
@github-actions

Copy link
Copy Markdown

Overall assessment

⛔ Blocker — Two label-handling regressions can silently change reported estimates.

Executive summary

  • P0 — Converting extended-precision cohort labels to float64 can merge distinct cohorts before estimation.
  • P0 — An older saved fit can silently report a different group ATT after loading because post-fit aggregation changes which cells enter the estimate.
  • The single never-treated moment and covariate score centring align with the cited EfficientDiD equations. The Registry documents the paired Hausman variance and the conservative staggered-design calibration.

Methodology

  • P0 — Cohort normalization can change treatment status. On platforms where np.longdouble has more precision than float64, 1.0 and the next representable longdouble above it both become 1.0. The magnitude check accepts both. On a panel observed at periods 0, 1, 2, the later cohort is still untreated at period 1, but the fit merges it into the cohort treated at 1. This changes the target and comparison groups without a warning. Concrete fix: Check that conversion preserves every label before downcasting, or raise a ValueError for inputs that would lose precision. diff_diff/efficient_did.py:L231-L257, diff_diff/efficient_did.py:L748-L753
  • P3 — Documented inference choices. The single never-treated moment follows the noncollinear stack in Eq. 3.11 and makes the omitted never-treated cross-terms in Eq. 3.12 vanish. Both covariate paths use the Eq. 3.10 centring. The Registry records the paired influence-function variance as the footnote 21 option and documents the staggered pretest’s rank limitation. No action required. docs/methodology/REGISTRY.md:L1952-L1954, docs/methodology/REGISTRY.md:L2011 · Chen, Sant’Anna & Xie (2025)

Code Quality

  • P0 — Group aggregation silently changes the estimand of saved fits. With g=0.1, anticipation=1, and t=-0.9, legacy float arithmetic included the cell, while the new exact inequality excludes it. For a one-cohort saved fit with cell effects 0, 3, 3, aggregate("simple") still relays the original ATT of 2, while aggregate("group") now returns 3 with inference for the smaller cell set. Bootstrap replay makes the same change. Concrete fix: Resolve post-anticipation cell membership once for both analytical group aggregation and bootstrap replay. Apply the existing refit error when legacy membership cannot be established. diff_diff/efficient_did_results.py:L386-L466, diff_diff/efficient_did_aggregation.py:L724-L731, diff_diff/efficient_did_bootstrap.py:L548-L563

Performance

  • P2 — Computing the outcome scale can allocate multiple panel-sized arrays. Boolean indexing copies the positive-weight outcomes and then the finite outcomes. np.abs allocates another float array. This raises peak memory on every fit. Concrete fix: Use masked min/max reductions or scan the outcomes in bounded blocks. diff_diff/utils.py:L440-L453

Maintainability

No additional findings.

Tech Debt

  • P3 — Tracked in TODO.md. The unregularized placebo self-pair, staggered Hausman rank selection, and adoption of the shared guards in other estimators have backlog entries. No action required for this PR. TODO.md:L91-L94

Security

No findings in the diff.

Documentation/Tests

  • P3 — Qualify the just-identified example. A cohort adopting in the second period can still borrow pre-treatment baselines from later cohorts. The example also needs an observed PT-Post baseline for the two fits to coincide. Concrete fix: Specify a single-cohort, consecutive-period panel in the API example and the Registry. docs/api/efficient_did.rst:L12-L18, docs/methodology/REGISTRY.md:L1952
  • The changelog fragment is present. I checked Python syntax and the arithmetic examples. The environment lacked pytest and NumPy, and arXiv access was unavailable. The source comparison used the repository’s equation transcription and Methodology Registry.

Path to Approval

  1. Reject lossy label conversion or preserve the original precision. Add a test using np.longdouble(1) and its next representable value toward 2 on a platform with extended precision. Verify the fit preserves distinct treatment assignments or raises a clear validation error.
  2. Add an analytical and bootstrap pickle regression for the legacy g=0.1, t=-0.9, anticipation=1 panel. Verify aggregate("group") reproduces the legacy selection or asks for a refit before reporting an estimate.

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