Skip to content

Fix NaN in hmm_hidden_state_prob for long sequences (#2677) - #3440

Open
atarutin wants to merge 1 commit into
stan-dev:developfrom
atarutin:bugfix/issue-2677-hmm-hidden-state-prob-underflow
Open

atarutin wants to merge 1 commit into
stan-dev:developfrom
atarutin:bugfix/issue-2677-hmm-hidden-state-prob-underflow

Conversation

@atarutin

@atarutin atarutin commented Oct 9, 2026 •

Copy link
Copy Markdown

Fixes #2677.

This was assisted by Claude.

Summary

hmm_hidden_state_prob returns NaN in two situations, both described in #2677:

  1. Long sequences. The forward pass rescaled only alphas.col(0). Every later column is the product of omegas and the previous column, so it shrinks like the joint density p(y_1, ..., y_n). Once that falls below the smallest double (a log density of about -745), the column is exactly 0, and the normalization alphas.col(n) /= alphas.col(n).sum() computes 0/0. In the reproducer in the issue comment (2 states, Gaussian observations) the first NaN appears at t = 472, for every T beyond that.
  2. Log densities of large magnitude. omegas = exp(log_omegas) underflows to 0 for entries below about -745 and overflows to inf above about 709. This is what @charlesm93 found in 2022 with log_omegas at 1000 or -1000.

The fix:

  • The forward loop now divides each column by its maximum, as the backward pass in this function already does and as the forward passes of hmm_latent_rng and hmm_marginal already do. The hidden state probabilities are invariant to a positive factor on each column of alphas, so unlike hmm_marginal the scale does not need to be kept.
  • Each column of log_omegas is shifted by its maximum before it is exponentiated. This is also exact: a constant factor on a column of omegas multiplies the same column of both the forward and the backward quantities and cancels in the per-column normalization.

The backward pass is unchanged. The cost stays at O(K^2) per step, with no transcendental functions in the loop. A recursion fully on the log scale (with log_sum_exp) would also work, but it needs K^2 exp/log calls per step, and the rescaled form matches the existing HMM functions.

@charlesm93 started bugfix/issue-2677-hmm_hidden_state in 2022. It has one commit, e7a5efa, which adds the test hidden_state_prob1 (log_omegas = 1000, Gamma sending every state to state 1) and no fix. The branch is 3,572 commits behind develop, so this PR is opened from a fresh branch, and that test is included here with its original name and assertions.

Tests

Three new tests in test/unit/math/prim/prob/hmm_hidden_state_prob_test.cpp, plus a reference implementation in the test file: hmm_hidden_state_prob_log_space, which runs forward-backward entirely on the log scale with log_sum_exp.

  • hmm_test_nonstandard.hidden_state_long_sequence: simulates a 2-state Gaussian HMM with 5000 observations (Gamma = [[0.95, 0.05], [0.10, 0.90]], means +1/-1, sd 1, boost::random::mt19937 seeded at 2677). It checks that hmm_marginal is below -2000 (here -7900.6), so the old forward pass must underflow. It then asserts that every output is finite, that every column sums to 1 within 1e-12 (measured: 2.2e-16), and that the output matches the log scale reference within 1e-10 (measured: 7.4e-13).
  • hmm_test.hidden_state_very_negative_log_omegas: subtracts 1000 + 10 n from column n of the fixture's log_omegas, so every entry is below -1000. It asserts that the output is finite, equals the output for the unshifted log_omegas within 1e-12 (measured: 2.5e-14), and matches the log scale reference within 1e-10 (measured: 7.5e-13). The reference tolerance is looser because a log scale computation loses about machine epsilon times the magnitude of the log densities.
  • hmm_test_nonstandard.hidden_state_prob1: taken from @charlesm93's branch (log_omegas = 1000, overflow).

On unmodified develop (43bc568) the three new tests fail and the three existing ones pass:

[  FAILED  ] hmm_test.hidden_state_very_negative_log_omegas      (prob = -nan)
[  FAILED  ] hmm_test_nonstandard.hidden_state_prob1             (prob = -nan)
[  FAILED  ] hmm_test_nonstandard.hidden_state_long_sequence
  Expected equality of these values:
    first_non_finite
      Which is: 475
    -1
  first non-finite column
 3 FAILED TESTS

With the patch:

  • ./runTests.py test/unit/math/prim/prob: all 155 test files pass (635 tests), including hmm_hidden_state_prob_test, hmm_marginal_test and hmm_latent_rng_test.
  • make stan/math/prim/prob/hmm_hidden_state_prob.hpp-test passes.
  • cpplint (the make cpplint invocation, run on the two changed files) reports no errors.
  • clang-format --dry-run --Werror is clean on both files with clang-format 10.0.0 from stanorg/ci:v1.

Compiler: g++ 14.2.0 (Debian), -std=c++17, Linux x86_64.

The function is prim only (it returns Eigen::MatrixXd of value_of inputs), so there are no rev/fwd/mix tests to update.

Side Effects

Inputs that used to give NaN now give finite probabilities. For inputs that already gave finite results, the output changes only by rounding (the existing tests pass unchanged, and the shifted and unshifted fixture agree to 2.5e-14). A column of log_omegas that is entirely -inf still gives NaN, as before.

hmm_latent_rng also computes omegas = exp(log_omegas) directly, so it shares the per-entry underflow and overflow. Its forward pass is already rescaled at every step. I left it out of this PR to keep it to #2677 and can open a follow-up.

Release notes

hmm_hidden_state_prob no longer returns NaN for long sequences or for log densities of large magnitude.

Checklist

  • Copyright holder: Aleksandr Tarutin

    The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
    - Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
    - Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

  • the basic tests are passing

    • unit tests pass (to run, use: ./runTests.py test/unit): test/unit/math/prim/prob run in full, not all of test/unit
    • header checks pass, (make test-headers): run for the changed header only
    • dependencies checks pass, (make test-math-dependencies): not run
    • docs build, (make doxygen): not run
    • code passes the built in C++ standards checks (make cpplint): run on the changed files
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

🤖 Generated with Claude Code

The forward pass rescaled only its first column, so on a long sequence
the forward probabilities underflowed to 0 and the final normalization
computed 0/0. Rescale every forward step, as hmm_latent_rng and
hmm_marginal already do. The hidden state probabilities are invariant to
a positive factor on each column, so the scale does not need to be kept.

log_omegas was also exponentiated directly, so log densities below about
-745 underflowed to 0 and large ones overflowed to inf. Subtract the
maximum of each column before exponentiating; the hidden state
probabilities are invariant to that shift as well.

The test hidden_state_prob1 is taken from Charles Margossian's branch
bugfix/issue-2677-hmm_hidden_state (e7a5efa).

@atarutin atarutin left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Looks reasonable.

@atarutin
atarutin marked this pull request as ready for review October 9, 2026 21:39
@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 0.98 -2.4% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 1.01 0.7% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.85 0.86 0.99 -0.61% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.98 -2.37% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.02 1.49% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.07 8.03 1.0 0.43% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.74 3.72 1.0 0.35% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.41 33.31 0.97 -2.76% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 1.0 0.07% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.93 6.93 1.0 0.01% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 137.32 135.94 1.01 1.01% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.2 1.01 0.87% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.6 0.61 1.0 -0.4% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.71 25.84 0.99 -0.51% slower
performance.compilation 401.03 383.09 1.05 4.47% faster
Mean result: 1.0005338929591159

Jenkins Console Log
Jenkins Build Stages
Commit hash: 44a50912ff3f2e71023ea29a6f91adf7c6b1cf87

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           52 bits physical, 57 bits virtual
CPU(s):                                  192
On-line CPU(s) list:                     0-191
Thread(s) per core:                      2
Core(s) per socket:                      48
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              25
Model:                                   17
Model name:                              AMD EPYC 9474F 48-Core Processor
Stepping:                                1
Frequency boost:                         enabled
CPU MHz:                                 1496.778
CPU max MHz:                             4114.4229
CPU min MHz:                             1500.0000
BogoMIPS:                                7189.39
Virtualization:                          AMD-V
L1d cache:                               3 MiB
L1i cache:                               3 MiB
L2 cache:                                96 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-47,96-143
NUMA node1 CPU(s):                       48-95,144-191
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Mitigation; Clear CPU buffers
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

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.

hmm_hidden_state returns NaN

2 participants