Repository navigation
Conversation
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
marked this pull request as ready for review
October 9, 2026 21:39
Contributor
Jenkins Console Log Machine informationDistributor 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #2677.
This was assisted by Claude.
Summary
hmm_hidden_state_probreturns NaN in two situations, both described in #2677:alphas.col(0). Every later column is the product ofomegasand the previous column, so it shrinks like the joint densityp(y_1, ..., y_n). Once that falls below the smallest double (a log density of about -745), the column is exactly 0, and the normalizationalphas.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.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 withlog_omegasat 1000 or -1000.The fix:
hmm_latent_rngandhmm_marginalalready do. The hidden state probabilities are invariant to a positive factor on each column ofalphas, so unlikehmm_marginalthe scale does not need to be kept.log_omegasis shifted by its maximum before it is exponentiated. This is also exact: a constant factor on a column ofomegasmultiplies 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^2exp/logcalls per step, and the rescaled form matches the existing HMM functions.@charlesm93 started
bugfix/issue-2677-hmm_hidden_statein 2022. It has one commit, e7a5efa, which adds the testhidden_state_prob1(log_omegas= 1000,Gammasending every state to state 1) and no fix. The branch is 3,572 commits behinddevelop, 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 withlog_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::mt19937seeded at 2677). It checks thathmm_marginalis 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: subtracts1000 + 10 nfrom column n of the fixture'slog_omegas, so every entry is below -1000. It asserts that the output is finite, equals the output for the unshiftedlog_omegaswithin 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:With the patch:
./runTests.py test/unit/math/prim/prob: all 155 test files pass (635 tests), includinghmm_hidden_state_prob_test,hmm_marginal_testandhmm_latent_rng_test.make stan/math/prim/prob/hmm_hidden_state_prob.hpp-testpasses.make cpplintinvocation, run on the two changed files) reports no errors.clang-format --dry-run --Werroris clean on both files with clang-format 10.0.0 fromstanorg/ci:v1.Compiler: g++ 14.2.0 (Debian),
-std=c++17, Linux x86_64.The function is prim only (it returns
Eigen::MatrixXdofvalue_ofinputs), 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_omegasthat is entirely-infstill gives NaN, as before.hmm_latent_rngalso computesomegas = 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_probno 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
./runTests.py test/unit):test/unit/math/prim/probrun in full, not all oftest/unitmake test-headers): run for the changed header onlymake test-math-dependencies): not runmake doxygen): not runmake cpplint): run on the changed filesthe code is written in idiomatic C++ and changes are documented in the doxygen
the new changes are tested
🤖 Generated with Claude Code