Skip to content

BUG: Reject singular or non-positive-definite sigma in system GLS - #885

Merged
bashtage merged 5 commits into
bashtage:mainfrom
finite-sample:fix/sur-singular-sigma
Dec 3, 2026
Merged

bashtage merged 5 commits into
bashtage:mainfrom
finite-sample:fix/sur-singular-sigma

Conversation

@soodoku

@soodoku soodoku commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Check that the residual covariance matrix sigma is numerically positive definite before inverting it in _SystemModelBase._gls_estimate, using eigenvalues after scaling each equation to unit variance.
  • Validate user-supplied sigma in _SystemModelBase.__init__ for finiteness and symmetry. Full GLS requires positive definite covariance. Diagonal GLS checks the diagonal it actually inverts, so a singular input with positive variances remains usable. System GMM accepts positive semidefinite covariance when the instrument-weighted moment matrix is invertible.
  • Guard linearmodels.system._utility.inv_matrix_sqrt against non-positive-definite inputs (raising np.linalg.LinAlgError, matching linearmodels.shared.linalg.inv_sqrth), preventing silent RuntimeWarning: divide by zero and NaN propagation.

Why

When a system has more equations than observations ($M > T$) or linearly dependent residuals (e.g., identical equations or zero-variance residuals), the sample residual covariance $\hat{\Sigma} = \frac{1}{T}\hat{\varepsilon}^\top\hat{\varepsilon}$ is mathematically singular, yet IEEE-754 roundoff leaves a tiny positive smallest eigenvalue ($\sim 10^{-17}$). Calling numpy.linalg.inv(sigma) without a rank/eigenvalue check silently inverts floating-point noise (condition number $\sim 10^{17}$) and returns arbitrary GLS parameter estimates and standard errors with no warning or error.

Example before this fix:

import numpy as np, pandas as pd
from linearmodels.system import SUR

rng = np.random.default_rng(0)
eqs = {
    f"e{i}": {
        "dependent": pd.Series(rng.normal(size=4)),
        "exog": pd.DataFrame({"x": rng.normal(size=4)}),
    }
    for i in range(5)
}
res = SUR(eqs).fit(method="gls")  # silently succeeds with cond(sigma) = 1.19e+17

With this fix:

  • SUR(eqs).fit(method="gls") raises np.linalg.LinAlgError explaining that sigma is singular (and noting method='ols', full_cov=False, or a user-supplied positive definite sigma as alternatives).
  • method="ols", full_cov=False (when diagonal entries are positive), and a valid user-supplied sigma continue to work unchanged.

Verification

  • pytest linearmodels/tests/system/: 2821 passed, including diagonal GLS with a singular supplied covariance, variances in different units, and system GMM with a rank-one covariance and orthogonal instruments.
  • ruff check and ruff format --check pass cleanly on all modified files.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 29, 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-12-03T06:08:51.970738Z f1f789c New commits
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 677f5c58cd

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread linearmodels/system/model.py Outdated
Comment on lines +945 to +946
vals = np.linalg.eigvalsh((sigma + sigma.T) / 2)
if not (vals[-1] > 0 and vals[0] > k * np.finfo(float).eps * vals[-1]):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve diagonal GLS for equations on different scales

When equations have residual variances such as 1 and 1e16, this test rejects even an exactly diagonal, positive-definite covariance: the smallest eigenvalue is 1, while the cutoff is about 4.44. Consequently, fit(method='gls', full_cov=False) now fails solely because the equations use different measurement units, although the independent diagonal inversions are numerically safe. Test singularity on a diagonally normalized covariance, and keep the inverse-square-root and user-sigma guards consistent, so rescaling an equation does not invalidate an otherwise estimable system.

Useful? React with 👍 / 👎.

"sigma must be a square matrix with dimensions "
"equal to the number of equations"
)
self._sigma = self._validate_sigma(sigma, len(self._equations))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve semidefinite covariance support in system GMM

For IVSystemGMM(..., weight_type='unadjusted'), sigma itself need not be invertible: HomoskedasticWeightMatrix.weight_matrix constructs Z' (sigma ⊗ I) Z, which is what _blocked_gmm inverts. For example, sigma=np.ones((2, 2)) with orthogonal one-column instrument sets produces a positive-definite diagonal moment weight matrix; result finalization also supports this case because _system_r2 inverts only sigma's diagonal and skips its singular inverse square root. Since GMM calls this shared constructor, the new validation rejects these previously estimable models before fitting. Restrict strict positive-definiteness to GLS, allowing positive-semidefinite sigma for GMM and checking its actual moment weight matrix instead.

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (04f080d) to head (f1f789c).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #885   +/-   ##
=======================================
  Coverage   99.69%   99.69%           
=======================================
  Files         203      203           
  Lines       38941    39033   +92     
  Branches     2503     2512    +9     
=======================================
+ Hits        38822    38914   +92     
  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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ccf6ba38b7

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread linearmodels/system/model.py Outdated
if np.max(np.abs(sigma_arr - sigma_arr.T)) > 1e-8 * scale:
raise ValueError("sigma must be symmetric.")
sigma_arr = 0.5 * sigma_arr + 0.5 * sigma_arr.T
if not covariance_is_definite(sigma_arr, allow_singular=allow_singular):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Defer strict sigma validation until full_cov is applied

When a user supplies a semidefinite covariance and requests diagonal GLS, for example SUR(eqs, sigma=np.ones((2, 2))).fit(method='gls', full_cov=False), construction now raises before the fitting mode is known. This previously worked because _gls_estimate discards the off-diagonal entries, making the effective covariance the identity. Accept semidefinite inputs at construction and enforce strict definiteness through the existing post-diagonalization _check_sigma_invertible call so that full_cov=False remains usable with singular supplied covariances whose diagonal entries are positive.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 55e231168b

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +262 to +263
vecs, roots, _ = np.linalg.svd(np.linalg.cholesky(s))
out = (vecs / roots) @ vecs.T

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve small roots when decomposing differently scaled covariances

For correlated equations on very different scales, the unscaled Cholesky-factor SVD can lose the smaller singular value. For example, np.array([[1., 2.**53], [2.**53, 2.**108]]) has correlation eigenvalues 0.5 and 1.5 and passes the definiteness check, but LAPACK's bidiagonalization can round the Cholesky factor's trailing pivot to zero. The subsequent division by roots then produces NaN/inf instead of the finite inverse square root obtainable from the previous eigendecomposition. Since GLS uses this routine for weighted residuals and McElroy R², a valid supplied covariance can now produce invalid results solely because of equation units. Use a scale-robust decomposition rather than an SVD of the unscaled factor.

Useful? React with 👍 / 👎.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks, this fixes a real problem: a singular residual covariance, for example in a share system that keeps all of the share equations, or with more equations than observations, was inverted and gave arbitrary GLS estimates, often without a warning. GLS here agrees with a direct GLS on the stacked system to 6e-14, and the estimates and covariances of valid input are unchanged.

  1. Coverage. if np.any(variances < 0): return False in covariance_is_definite is reachable (SUR(eqs, sigma=[[-1, 0], [0, 1]])) but not tested, and if not np.isfinite(corr).all(): return False can't be reached through a public path: sigma is finite by then, and |corr| <= 1 for positive semidefinite input.

  2. The tolerance isn't tested: in both singular tests the smallest eigenvalue of the correlation matrix is already <= 0, so tol = 0 passes them. With seeds 2 and 4 of test_sur_singular_sigma_more_equations_than_obs it is a small positive number, so running that test over several seeds makes it depend on the tolerance.

    Both changes:

    --- a/linearmodels/system/_utility.py
    +++ b/linearmodels/system/_utility.py
    @@ -229,8 +229,6 @@ def covariance_is_definite(
             return False
         scales = np.sqrt(np.where(zero, 1.0, variances))
         corr = s / scales[:, None] / scales
    -    if not np.isfinite(corr).all():
    -        return False
         vals = np.linalg.eigvalsh(corr)
         tol = len(s) * np.finfo(float).eps * vals[-1]
         return bool(vals[0] >= -tol if allow_singular else vals[0] > tol)
    --- a/linearmodels/tests/system/test_sur.py
    +++ b/linearmodels/tests/system/test_sur.py
    @@ -1093,8 +1093,9 @@ def test_sur_contraint_with_value():
         assert_allclose(result.params, result_without_q.params)
    
    
    -def test_sur_singular_sigma_more_equations_than_obs():
    -    rng = np.random.default_rng(0)
    +@pytest.mark.parametrize("seed", range(6))
    +def test_sur_singular_sigma_more_equations_than_obs(seed):
    +    rng = np.random.default_rng(seed)
         nobs = 4
         eqs = {
             f"e{i}": {
    @@ -1146,6 +1147,7 @@ def test_sur_singular_sigma_collinear_equations():
             (np.array([[1.0, np.nan], [np.nan, 1.0]]), "missing or infinite"),
             (np.array([[1.0, 0.5], [0.0, 1.0]]), "symmetric"),
             (np.array([[1.0, 2.0], [2.0, 1.0]]), "positive semidefinite"),
    +        (np.array([[-1.0, 0.0], [0.0, 1.0]]), "positive semidefinite"),
         ],
     )
     def test_sur_invalid_user_sigma(bad_sigma, match):
  3. Docs. The sigma parameter of SUR, IV3SLS and IVSystemGMM (and of the from_formula methods) should say what is accepted:

    sigma : array_like, optional
        Prespecified residual covariance to use in GLS estimation, with shape
        (nequations, nequations). If not provided, FGLS is implemented based on an
        estimate of sigma. It must be finite, symmetric and positive semidefinite.
    
        .. versionchanged:: 7.2
    
           A ``ValueError`` is raised if sigma is not finite, symmetric and positive
           semidefinite.

    and fit needs a Raises entry:

    numpy.linalg.LinAlgError
        If ``method`` is "gls" and the residual covariance that GLS inverts (``sigma``,
        or its estimate, or only their diagonal if ``full_cov`` is False) is singular.
  4. Release notes, one bullet in each of three sections:

    .. "Bug fixes"
    - GLS estimation of ``SUR`` and ``IV3SLS`` raises a ``LinAlgError`` when the residual
      covariance that it inverts is singular, as it is when there are more equations than
      observations or when the residuals of some equations are linearly dependent, for
      example share equations that sum to one. The check uses the correlation matrix, so it
      does not depend on the units of the equations. 7.1 inverted the rounding error and
      returned arbitrary estimates, at most with a ``RuntimeWarning`` (:issue:`885`).
    
    .. "Backward-incompatible changes"
    - ``SUR``, ``IV3SLS`` and ``IVSystemGMM`` raise a ``ValueError`` if ``sigma`` contains
      missing or infinite values or is not symmetric and positive semidefinite. 7.1 accepted
      it, also when it was not used, as with ``method="ols"``, ``full_cov=False`` or a GMM
      weight type other than "unadjusted" (:issue:`885`).
    
    .. "Changes that alter results"
    - The McElroy R-squared of the system models is computed when the residual variances of
      the equations differ by a factor of about 1e15 or more, where 7.1 reported NaN. The
      weighted residuals of GLS and the McElroy R-squared are more accurate when the
      equations have very different scales, and change by rounding error otherwise
      (:issue:`885`).

On the last Codex comment: it is right that [[1, 2**53], [2**53, 2**108]] gives NaN, but those scales aren't realistic, and for realistic differences in scale the new inv_matrix_sqrt is more accurate than eigh was. No change needed.

Optional: test_sur_singular_sigma_more_equations_than_obs only checks that the OLS, diagonal-GLS and sigma=np.eye(5) estimates are finite. All three equal equation-by-equation OLS, so assert_allclose against the OLS estimates would be a real check.

- Drop the unreachable finiteness check on the correlation matrix and test
  the negative-variance branch through SUR(sigma=...).
- Run the more-equations-than-observations test over six seeds, so that it
  depends on the eigenvalue tolerance (tol = 0 fails two of them), and
  compare the OLS, diagonal-GLS and sigma=I estimates with each other
  instead of only checking that they are finite.
- Document what sigma must be in SUR, IV3SLS and IVSystemGMM, and the
  LinAlgError that GLS raises for a singular covariance.
- Add 7.2 notes under bug fixes, backward-incompatible changes and changes
  that alter results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@soodoku

soodoku commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — all four points are in f1f789c: your coverage/tolerance diff (with tol = 0, seeds 3 and 4 fail), the sigma docs for SUR, IV3SLS, IVSystemGMM and the from_formula methods, the LinAlgError entry on fit, and the three release notes. I also took the optional suggestion: the diagonal-GLS and sigma=I estimates are now checked against OLS with assert_allclose.

@bashtage
bashtage merged commit 88a91d6 into bashtage:main Dec 3, 2026
27 checks passed
@bashtage

bashtage commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Thanks.

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.

2 participants