Skip to content

BUG: Avoid underflow in the log-sum-exp of the Hamilton filter - #11001

Merged
bashtage merged 3 commits into
statsmodels:mainfrom
bashtage:wip-ms-hamilton-filter-underflow
Nov 23, 2026
Merged

bashtage merged 3 commits into
statsmodels:mainfrom
bashtage:wip-ms-hamilton-filter-underflow

Conversation

@bashtage

Copy link
Copy Markdown
Member

The compiled Hamilton filter (hamilton_filter.pyx.in) computes each
log f(y_t | Y
{t-1}) as a log-sum-exp of the weighted log-likelihoods
with the maximum trick, but started the running maximum at 0 instead of
at the first term. When every term was below about -745, as for an
observation far from all regime means, exp underflowed to 0: the
period's log-likelihood was -inf, the filtered probabilities inf and
the total log-likelihood nan. For a two-regime MarkovRegression of the
first 20 fedfunds observations with observation 10 set to 200,
llf_obs[10] was -inf instead of -4088.312.

The maximum now starts at the first term, so the shift is the largest
term. The order-0 prediction step gets the same change for consistency;
its terms cannot fall that low (the log transition probabilities are
bounded below by log(1e-20)), so its results only change by rounding.
Results that were finite before change at the rounding level only;
log-likelihoods that were -inf or nan are now finite.

Tests: a MarkovRegression and an order-0 model given its conditional
log-likelihoods, with an observation about 200 standard deviations from
both regime means, against the Hamilton filter written out with a
shifted log-sum-exp (llf_obs, llf and the filtered probabilities), and
smoothed probabilities in [0, 1] that sum to one.

  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message. See
    NumPy's guide.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude Code (Claude Opus 5.5).
    Used for: finding the bug in a contract audit, writing the fix and its tests, and checking them (tests failing on main, mutation check).
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

🤖 Generated with Claude Code

The compiled Hamilton filter (_hamilton_filter.pyx.in) computes each
log f(y_t | Y_{t-1}) as a log-sum-exp of the weighted log-likelihoods
with the maximum trick, but started the running maximum at 0 instead of
at the first term. When every term was below about -745, as for an
observation far from all regime means, exp underflowed to 0: the
period's log-likelihood was -inf, the filtered probabilities inf and
the total log-likelihood nan. For a two-regime MarkovRegression of the
first 20 fedfunds observations with observation 10 set to 200,
llf_obs[10] was -inf instead of -4088.312.

The maximum now starts at the first term, so the shift is the largest
term. The order-0 prediction step gets the same change for consistency;
its terms cannot fall that low (the log transition probabilities are
bounded below by log(1e-20)), so its results only change by rounding.
Results that were finite before change at the rounding level only;
log-likelihoods that were -inf or nan are now finite.

Tests: a MarkovRegression and an order-0 model given its conditional
log-likelihoods, with an observation about 200 standard deviations from
both regime means, against the Hamilton filter written out with a
shifted log-sum-exp (llf_obs, llf and the filtered probabilities), and
smoothed probabilities in [0, 1] that sum to one.
@bashtage
bashtage marked this pull request as ready for review November 23, 2026 17:07
@bashtage
bashtage merged commit 375e7a6 into statsmodels:main Nov 23, 2026
9 of 10 checks passed
bashtage added a commit that referenced this pull request Nov 23, 2026
A line coverage measurement of the compiled statespace code (Linux, Cython
line tracing) found float64 template lines that nothing can reach: methods
without a caller, statements that cannot run, the code under three Cython
API flags that nothing in Python sets, and LAPACK error branches that no
input reaches. This removes the first two kinds and marks the other two
"pragma: no cover". All edits are in the .pyx.in templates (and the .pxd
declarations, _stl.pyx).

Changes
- Removed, because nothing calls them:
  - the cdef methods _forecasting, _inversion, _updating,
    _calculate_loglikelihood and _prediction of KalmanFilter (their calls
    in __next__ were commented out), with their declarations in
    _kalman_filter.pxd;
  - the Cython Statespace.initialize_stationary (the Python
    Representation.initialize_stationary goes through Initialization);
  - the module-level cpdef wrappers sldl, dldl, cldl and zldl in _tools,
    with their declarations in _tools.pxd (the cdef _ldl stays).
- Removed statements that cannot run:
  - in KalmanFilter.__next__, the re-raise when the filter was already
    univariate: the univariate inversion is a no-op that cannot raise;
  - in KalmanFilter.check_convergence, the return for t = 0 with filtered
    timing: the enclosing test requires t >= nobs_diffuse + 1;
  - in Statespace.transform_generalized_collapse, the check
    k_endog < k_states: the collapse only runs with more observed series
    than states (and KalmanFilter.set_filter_method raises first);
  - in arma_innovations_algo_fast, a continue: for n >= m the loop already
    starts at k = n + 1 - q;
  - in _is_pos_int of STL, a try/except around a comparison that only runs
    for integers.
- "# pragma: no cover" on the traced lines:
  - under the subset_design, companion_transition and identity_transition
    flags (hooks of the Cython API that nothing in Python sets), including
    companion_predicted_state and companion_predicted_state_cov, which
    only run under companion_transition;
  - of the LAPACK error branches that cannot be reached: illegal-argument
    codes of ?potrf, ?getrf, ?trtrs, ?potrs, ?getrs and ?pbtrf, a singular
    factor reported by ?trtrs after a successful ?potrf or for a unit
    diagonal, and the ?potrf of the inverse of a positive definite matrix;
    and of two defensive ones, a failure of ?gees in the Lyapunov solver
    and of ?pbtrf for the joint CFA posterior;
  - of the callbacks that ?gees requires but never calls with sort='N'.
  Cython.Coverage excludes only the line that carries the pragma, not the
  block below it, so every traced line has its own (including the
  continuation line of a multi-line raise, where the % formatting is
  traced).
- The Cython validate_matrix_shape printed the actual number of columns
  twice and had no space before "got".

Not changed
- Results. The statespace, innovations, STL and ARIMA tests pass, and 116
  outputs of representative models (loglikelihoods, filtered and smoothed
  states and covariances, forecasts and their covariances, KFS simulation
  smoother draws, the CFA posterior mean and draw, ARMA innovations, STL
  components) are bitwise identical to those of the base build, covering
  the conventional, univariate, exact diffuse, collapsed, Chandrasekhar
  and concentrated filters, filtered timing, the Cholesky and LU
  inversions and the conventional, univariate, alternative and classical
  smoothers.
- The nobs checks of the Cython validate_matrix_shape and
  validate_vector_shape: Statespace.__init__ passes nobs, so they are
  reachable through the Cython API (the Python layer validates first).
- The max shift of the order-0 logsumexp in the Hamilton filter, which
  #11001 changes.

Tests
- No new tests (refactoring). Linux coverage build (WSL, Python 3.12,
  Cython 3.3.1, Cython.Coverage), with the statespace, innovations, STL
  and ARIMA tests (4049 passed, before and after): the 19 measured .pyx
  files have 16971 traced lines with 8659 missed before, and 16400 with
  8126 missed after. All 328 generated lines that carry the pragma (82
  template lines, 4 dtypes each) are excluded, none of them is reported
  as missed, and no other line is excluded. For float64, the only covered
  lines that disappear are removed ones.
- Windows: the same tests pass, and the outputs listed above are bitwise
  identical to those of the base build.
@bashtage
bashtage deleted the wip-ms-hamilton-filter-underflow branch November 24, 2026 18:27
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