Repository navigation
Fold posterior into smooth/loglikelihood, add smoothing_iters - #175
Merged
Merged
Conversation
`dev` carries the SLDS input addition as #158; CCN2026 already carries the same change as #160. The two patches are functionally identical and differ only in JuliaFormatter line wrapping, so all three conflicts in src/lds/fit_SLDS.jl resolve to CCN2026's side: - the header API summary, where CCN2026 adds the `posterior` entry point - two Poisson sampling hunks in `_sample_continuous_given_discrete!`, which differ only in `rand.(...)` wrapping The merged tree is byte-identical to CCN2026 before the merge; this records the ancestry so PR #161 is mergeable against `dev` again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
Ryan's review of #161 asked for `posterior`'s machinery to move into `smooth`, and for a single ELBO rather than two implementations where the more accurate one is not the one named `elbo`. Extract the shared kernel: - `_vem_warmstart!` — the uniform-γ warm-start pass that `fit!`, `elbo`, and `posterior` each carried a copy of. - `_vem_alternate!` — one discrete↔continuous alternation (fill `dl.logL`, forward-backward, re-smooth), run `smoothing_iters` times. `x_samples` selects the coupling: a joint draw from q(x) for the Monte-Carlo E-step, the smoothed mean for deterministic post-fit inference. `tol == 0` runs a fixed number of alternations; `tol > 0` stops on `max|Δγ| < tol` and warns if the cap is hit, replacing the `check_convergence` flag. Public API: - `smooth(slds, y)` infers q(x), γ, and the ELBO in one pass and returns `(; x, γ, elbo, p)`. γ and the ELBO are always returned; the smoothed covariances are opt-in via `return_cov` since they are large. Shapes follow `smooth(lds, y)`: matrix in, per-trial arrays out. - `elbo` delegates to it, so there is now one ELBO implementation reachable one way. It is deterministic, so the `rng` keyword is gone. - `loglikelihood(slds, y)` returns that ELBO instead of throwing, documented as a lower bound rather than the (intractable) marginal. - `smooth(slds, y, w)` with explicit responsibilities is unchanged. - `posterior` is removed, along with its export. `fit!` and `estep!` gain `smoothing_iters`, defaulting to 1. The loop and RNG draw order are unchanged, so `smoothing_iters=1` reproduces the previous E-step exactly; larger values run more alternations per M-step, each redrawing from q(x) so the estimator stays unbiased. Also addresses the review's line-by-line notes: the truncated comment above `_sample_slds_trial!`, and the `ux`/`uy` docstring boilerplate repeated on internal functions where the file header already states the convention. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
test/runtests.jl called `@skip_test`, a macro defined nowhere in the repo or in libs/SSDTest, so the suite did not parse. Remove it and run the inference tests. Tests: - Rename the `test_SLDS_posterior_*` group to `test_SLDS_smooth_infer_*` and port the 9 stale `infer_γ` call sites onto `smooth`, which is what the function was renamed to two commits into #161. - `check_convergence=false` becomes `tol=0`. - Cover the new surface: `return_cov` shapes and PSD covariances, `p === nothing` by default, positional destructuring, and that `elbo` and `loglikelihood` both return exactly `smooth(...).elbo`. - `loglikelihood(slds, y)` no longer throws; assert it equals the ELBO, and that the K=1 no-prior case is tight against the Kalman-filter marginal. - `test_SLDS_public_elbo` drops the "matches fit!'s first trace entry under a shared rng" assertion, which no longer applies now that `elbo` is deterministic. `elbo!` is still covered directly by `test_SLDS_estep_elbo_components`. - New `test_SLDS_fit_smoothing_iters` checks the property that matters for the refactor: `estep!(...; smoothing_iters=2)` lands bit-identically where two successive `smoothing_iters=1` calls do, from the same state and rng. Docs: - docs/src/SLDS.md referenced `infer_γ` in prose and in an `@docs` block. That binding no longer exists, so the docs build could not have resolved it. Rewrite the section around `smooth` and note that `loglikelihood` and `elbo` return the same bound. - The block is `canonical = false` because a bare `smooth` in LinearDynamicalSystems.md already claims every method of it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
The Code Formatting test was the only failure on this PR — 1477 passed, 1 failed, identically on Julia 1.10 (lts) and 1.13-rc (pre). It is not caused by this branch's changes: it arrived in 3fb7c92 on CCN2026, which deleted this `return`. PR #161 only ever ran the benchmark workflow, so the test suite never reported it. `.JuliaFormatter.toml` sets `always_use_return = true`, which JuliaFormatter applies to do blocks as well as function and macro definitions. Every other do block in the formatter-checked tree ends in `return ...` or a block; this was the only bare trailing call, so the formatter wanted it back. The deletion was motivated by a semantic concern ("surely it has to loop over all trials before returning"), but the two versions are equivalent. The do block is an anonymous function passed to `tforeach`; `return` there exits that closure for a single `i`, not the enclosing `sufficient_statistics!`, and does not break the loop. `tforeach` still invokes the closure for every trial. Added a comment saying so, since the `return` reads as suspicious without it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
Verified against the pinned JuliaFormatter 1.0.62 (blue style, margin 92): `format(repo; overwrite=false)` now returns true, which is exactly the assertion in test/runtests.jl's Code Formatting testset. Three whitespace-only deviations, no semantic change: - The two Poisson `rand.` hunks in `_sample_continuous_given_discrete!`. These are the merge conflict from merging `dev`: both sides were functionally identical and I kept CCN2026's wrapping, but the formatter wants `dev`'s (`y_trial[:, 1] =` then an indented `rand.(`). CCN2026's side was the stale one, so these were already unformatted before this branch. - `view(fs.p_smooth,:,:,t)` in `elbo!` was missing the spaces after its commas (also pre-existing, from #161). - `collect(1:st.total_T)` in the new smoothing_iters test, which blue style parenthesizes as `1:(st.total_T)`. This one is mine. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## CCN2026 #175 +/- ##
==========================================
Coverage ? 96.10%
==========================================
Files ? 18
Lines ? 3335
Branches ? 0
==========================================
Hits ? 3205
Misses ? 130
Partials ? 0 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
rsenne
added a commit
that referenced
this pull request
Aug 24, 2026
`dev` had two commits we lacked: the null models (#126), which are genuinely new, and the SLDS input addition (#158). CCN2026 already carries #158's content via a *different* commit (eca88b6, merged as #160), so the same patch existed twice under two SHAs — that duplicate is what made the PR conflict. Resolution: - src/lds/fit_SLDS.jl, src/utils/validation.jl, test/LinearDynamicalSystems/SLDS.jl -> ours. Verified first that dev's delta in these three files comes only from #158 (the null-models commit does not touch them), and that every function dev adds is already present on our side: the 9 input-handling test functions and helpers, `Random.rand`/`smooth` methods, and the ux_dim/uy_dim checks in validate_SLDS. Ours is a strict superset, being the same content plus #175 and the work on top. - src/StateSpaceDynamics.jl, test/runtests.jl -> both sides. Git auto-merged these correctly, keeping dev's null-model import/include/exports alongside our export line and SLDS test entries. - src/stats/null_models.jl, test/NullModels/NullModels.jl and the CHANGELOG / docs/api / show.jl edits -> dev's, unchanged. One fix on top of the auto-merge: it produced a duplicate "Control inputs (ux/uy)" testset in runtests.jl, because git could not tell dev's #158 block was the same one we already had from #160. Removed the copy. Checked that no other testset or test call was duplicated by the merge — the repeated names that remain (test_EM, test_smooth, ...) are the pre-existing per-model pattern and are identical to the pre-merge file. Verified on the merged tree: SLDS suites 559 passed / 0 failed / 1 broken (the pre-existing @test_broken on ELBO monotonicity), null models 142/142, and JuliaFormatter 1.0.62 clean across src/ and test/. The format check was run against `git archive` of the merged index rather than the working tree, because core.autocrlf=true makes the local checkout report src/stats/sufficient_statistics.jl as unformatted on line endings alone; the LF blob CI sees is clean, and that file is untouched by this merge. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
rsenne
added a commit
that referenced
this pull request
Aug 24, 2026
`dev` had two commits we lacked: the null models (#126), which are genuinely new, and the SLDS input addition (#158). CCN2026 already carries #158's content via a *different* commit (eca88b6, merged as #160), so the same patch existed twice under two SHAs — that duplicate is what made the PR conflict. Resolution: - src/lds/fit_SLDS.jl, src/utils/validation.jl, test/LinearDynamicalSystems/SLDS.jl -> ours. Verified first that dev's delta in these three files comes only from #158 (the null-models commit does not touch them), and that every function dev adds is already present on our side: the 9 input-handling test functions and helpers, `Random.rand`/`smooth` methods, and the ux_dim/uy_dim checks in validate_SLDS. Ours is a strict superset, being the same content plus #175 and the work on top. - src/StateSpaceDynamics.jl, test/runtests.jl -> both sides. Git auto-merged these correctly, keeping dev's null-model import/include/exports alongside our export line and SLDS test entries. - src/stats/null_models.jl, test/NullModels/NullModels.jl and the CHANGELOG / docs/api / show.jl edits -> dev's, unchanged. One fix on top of the auto-merge: it produced a duplicate "Control inputs (ux/uy)" testset in runtests.jl, because git could not tell dev's #158 block was the same one we already had from #160. Removed the copy. Checked that no other testset or test call was duplicated by the merge — the repeated names that remain (test_EM, test_smooth, ...) are the pre-existing per-model pattern and are identical to the pre-merge file. Verified on the merged tree: SLDS suites 559 passed / 0 failed / 1 broken (the pre-existing @test_broken on ELBO monotonicity), null models 142/142, and JuliaFormatter 1.0.62 clean across src/ and test/. The format check was run against `git archive` of the merged index rather than the working tree, because core.autocrlf=true makes the local checkout report src/stats/sufficient_statistics.jl as unformatted on line endings alone; the LF blob CI sees is clean, and that file is untouched by this merge.
rsenne
added a commit
that referenced
this pull request
Aug 25, 2026
…d smoothed states (#161) * add jitter to diagional of init_yy * add jitter to all symmetric dyn * add ugly priors to A/pi * Add infer_γ: post-fit SLDS discrete-responsibility inference (#159) Add a public `infer_γ` (exported) in `fit_SLDS.jl` that infers the discrete-state responsibilities γₜ(k) = q(zₜ = k) of a fitted SLDS with parameters held fixed (no M-step). It runs the structured-variational E-step, alternating the forward-backward pass over the switching chain q(z) with the Laplace/Kalman smoother over the continuous states q(x) — the classic coordinate-ascent E-step of Ghahramani & Hinton — either until the responsibilities converge (max|Δγ| < tol, capped by max_iter) or for a fixed number of iterations (check_convergence flag). The two smoothers are coupled deterministically: the discrete-layer log-likelihoods are plugged in at the smoothed posterior mean rather than a Monte-Carlo draw, so unlike fit!'s learning-time E-step the iteration is reproducible and γ settles to a fixed point, making the convergence check well behaved. Returns γ matching the input shape family: a K×T matrix for single-trial matrix input, otherwise a Vector of per-trial K×T_i matrices (ragged lengths allowed). Includes tests (shapes, determinism, both stopping modes, K=1 degenerate case, and discrete-state recovery on well-separated regimes) and a docs section. * SLDS input addition (#158) (#160) Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com> * add inputs to infer_\gamma * Rename infer_γ to posterior and update related tests * Refactor posterior function to return per-trial responsibility matrices when requested * Refactor post-fit inference documentation for clarity and conciseness * Add small constant to diagonal of sufficient statistics matrices to improve numerical stability * Remove small constant addition to diagonal of sufficient statistics matrices * Remove hacky prior * Update sufficient_statistics.jl There's no way that return was correct, surely it has to loop over all trials before returning. must have been a mistake, talk about stochastic update * Update sufficient_statistics.jl Remove evidence of hacks that didn't work * Fold `posterior` into `smooth`/`loglikelihood`, add `smoothing_iters` (#175) * Fix review findings in the SLDS smooth/ELBO path Correctness and hygiene fixes from the review of the `posterior` -> `smooth` refactor. No intended behaviour change beyond the two noted below. - Remove the `+1e-12` floors inside `log(πₖ)` and `log(A)` in `elbo!`. They were unnecessary: γ₁(k) > 0 implies πₖ[k] > 0 and ξ_t[i,j] > 0 implies A[i,j] > 0, which is the same argument the adjacent H[q(z)] block already relies on. Guard on the weight instead. This shifts the ELBO by ~1e-12 per term. - Validate `w` in the public `smooth(slds, y, w)`. A `w` with extra rows was silently ignored and unnormalised columns silently rescaled the posterior, because the weighted kernels index `w[k, t]` without inspecting its shape. - Drop `@inbounds` from the max|Δγ| reduction (project standard; the bounds checks are free next to the smooth that precedes it) and the dead `iter > 1` guard, which could never fire given `γ_prev` starts at Inf. - `mstep!` takes `Data` and `SufficientStatistics` instead of rebuilding both every EM iteration; `fit!` constructs them once. Also aligns the SLDS with the convention that backends take `Data`. - `_update_shared_initial_state!` fits regime 1 in place rather than deepcopying a whole LDS per M-step. Both updates already no-op on their `fit_bool`, so an unfitted x0/P0 is still left untouched everywhere. - Type the M-step `weights` concretely; an abstract eltype made every access inside the aggregator a dynamic dispatch. Hoist the pool-of-one wrapper. - `all(iszero, x)` instead of `all(x .== 0)` (was materialising a BitMatrix per smooth! call), and drop a no-op `Symmetrize!` self-assignment. - Correct two docstrings: `_vem_alternate!` never warns (its caller does), and the covariance shape is latent_dim x latent_dim x T. Tests: add Poisson coverage for the new `smooth`/`elbo` path (the 1/2 tr(H S) term is exact for Gaussian but a Laplace approximation for Poisson, so the existing Gaussian-only tests could not detect a Poisson-specific problem), `w`-validation coverage, and an ELBO test over the deterministic alternation. That last test records a real open issue. The deterministic path is coordinate ascent, so its ELBO should be non-decreasing in `smoothing_iters`; instead it converges to the fixed point from above, so `smoothing_iters=2` reports a higher bound than `smoothing_iters=100`. Ruled out: floating-point noise (the decay is geometric and too regular), the inner Newton tolerance (identical deficit at 1e-6, 1e-9, 1e-12 and 0), and a missing per-regime 1/2 tr(H_k S) term in the q(z) update (adding it makes the drift worse). The gap is ~1e-6 relative and does not stop convergence, so the test pins the behaviour that does hold and marks strict monotonicity @test_broken. * Add `num_samples` to the SLDS Monte-Carlo E-step The discrete update scores each regime against a draw from q(x) rather than the posterior mean, so it carries Monte-Carlo noise. Until now there was no way to reduce that noise: `smoothing_iters` runs more alternations but averages nothing, since only the final alternation's γ reaches the M-step. `num_samples` is the knob ssm exposes for this (`_fit_laplace_em`, default 1). The discrete update now averages `log p_k` over that many independent draws, estimating E_q(x)[log p_k] with 1/num_samples the variance of a single draw. Implementation: the per-trial sample buffer goes from `D x T` to `D x T x num_samples`. `smooth!` fills all of them from the one factorisation it already has, since `block_tridiagonal_sample!` only reads the block-LDL factors. The scoring step writes the first draw into `dl.logL` and accumulates the rest through `ll_tmp`, which carries nothing live at that point. The deterministic and sampled scoring paths are split into separate branches rather than sharing an `x_src` variable, because the resulting Matrix/SubArray union at that call site would make every kernel call a dynamic dispatch. Measured on a 2-regime model, spread of γ across 200 rng seeds: S sd(γ) vs S=1 sqrt(S) 1 0.16131 1.00x 1.00 2 0.12163 1.33x 1.41 4 0.08996 1.79x 2.00 8 0.06477 2.49x 2.83 16 0.04618 3.49x 4.00 32 0.03242 4.98x 5.66 Consistently ~88% of the ideal sqrt(S); the shortfall is the exp-and-normalise in forward-backward, which is not linear in logL. Cost is `num_samples` extra log-likelihood passes per alternation, while the smoother still runs once. `num_samples=1` is the default and is a verified no-op: against a clean checkout of the parent commit, the `fit!` ELBO trace is identical to all 17 digits at both `smoothing_iters=1` and `=3` (same RNG draws, same arithmetic). Also corrects the `fit!` docstring, which claimed redrawing each alternation keeps "the estimator unbiased" in a way that reads as a noise benefit. Redrawing does keep the loop from sharpening γ against one fixed noise realisation, but it does not reduce variance. Documents the ordering invariant too: the draws consumed by an E-step were taken before the intervening M-step, which ssm also does (it stores the posterior and samples lazily where this stores the realised draw), and the lag vanishes as EM converges. * Text refresh, add ability to use multiple discrete samples * Add observatiuons alias * add trace correction --------- Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>
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.
Addresses @rsenne's review on #161, plus the
smoothing_itersidea from that thread. TargetsCCN2026so it can be read on its own before it lands in #161.1. Merge
devintoCCN2026#161 was
mergeable_state: dirty.devis one commit ahead of the merge base (#158, the SLDS input addition), andCCN2026already carries the same change as #160. The two patches are functionally identical — they differ only in JuliaFormatter line wrapping — so the merge is pure ancestry, with no behavioural change.(I first resolved the two Poisson
rand.conflicts toCCN2026's side; JuliaFormatter later showeddev's wrapping was the canonical one, so a follow-up commit switches them. See Verification.)2. One alternation kernel
estep!andposterior's inner loop were the same three steps — filldl.logL, forward-backward, re-smooth — differing only in whetherlogLwas scored against a joint sample or the smoothed mean. Both now go through:_vem_warmstart!— the uniform-γ warm-start pass thatfit!,elbo, andposterioreach had a copy of._vem_alternate!— one alternation, runsmoothing_iterstimes.x_samples !== nothingselects the Monte-Carlo coupling,nothingthe deterministic one.tol == 0runs a fixed count;tol > 0stops onmax|Δγ| < toland warns if the cap is hit — replacingcheck_convergence, which you flagged as unnecessary.3. Public API
γ and the ELBO are always returned — you were right that nobody calls this without wanting γ. The smoothed covariances stay opt-in since they're large. Shapes follow
smooth(lds, y): matrix in, per-trial arrays out; positional destructuring still givesx, γ = smooth(slds, y).elbonow delegates tosmooth, so there is one ELBO implementation reachable one way, and it's the converged deterministic one. It lost itsrngkeyword as a result.loglikelihood(slds, y)returns that same bound instead of throwing, documented as a lower bound rather than the (intractable) marginal. If you want the posteriors and the ELBO, callsmoothonce and read itselbofield rather than paying for the alternation twice.smooth(slds, y, w)with explicit responsibilities is unchanged.posterioris removed.4.
smoothing_itersfit!andestep!takesmoothing_iters, defaulting to 1. The loop and RNG draw order are unchanged, so the default reproduces the previous E-step exactly; larger values run more alternations per M-step, each redrawing from q(x) so the estimator stays unbiased.5. Review comments and two latent breakages
Each line comment is addressed: the truncated comment above
_sample_slds_trial!, theux/uydocstring boilerplate repeated where the file header already states the convention once, the inaccurate return-shape docs,check_convergence, andreturn_γ.Two things on
CCN2026were broken rather than merely stale, both of which your comments pointed at:test/runtests.jldid not parse.@skip_testis defined nowhere in the repo or inlibs/SSDTest.infer_γ.docs/src/SLDS.mdreferenced it in prose and in an@docsblock after the rename toposterior.Tests are ported onto
smooth(9 staleinfer_γcall sites),check_convergence=falsebecomestol=0, and the new surface is covered.test_SLDS_public_elbodrops its "matchesfit!'s first trace entry under a shared rng" assertion, which no longer applies now thatelbois deterministic;elbo!is still covered directly bytest_SLDS_estep_elbo_components. The newtest_SLDS_fit_smoothing_iterschecks the property that actually matters for the refactor:estep!(...; smoothing_iters=2)lands bit-identically where two successivesmoothing_iters=1calls do.Verification
CI is fully green —
build,test (1),test (lts),test (pre), and codecov. The substantive tests passed from the first run onward (645 SLDS tests, Aqua with no ambiguities, JET, the docs examples, the docs build); every failure along the way was the singleCode Formattingassertion.That check turned out to be failing for three whitespace-only reasons, two of which predate this branch —
CCN2026had been unformatted for a while, unnoticed because #161 only ever ran thebenchmarkworkflow:sufficient_statistics.jl'stforeachclosure lost itsreturnin 3fb7c92, whichalways_use_return = truerequires. Restored. Worth noting the deletion's stated rationale doesn't hold: inside adoblockreturnexits that closure for onei, not the enclosing function, sotforeachruns every trial either way — the two spellings are equivalent.view(fs.p_smooth,:,:,t)inelbo!was missing the spaces after its commas (from Addposteriorfunction to estimate MLE/MAP elbo, responsibility, and smoothed states #161).collect(1:st.total_T)in the newsmoothing_iterstest, which blue style parenthesizes. That one's mine.Formatting is now verified locally against the pinned JuliaFormatter 1.0.62:
format(repo; overwrite=false)returnstrue, which is exactly the assertion inruntests.jl.Codecov reports 97.59% patch coverage with 2 uncovered lines in
fit_SLDS.jl; I left those alone rather than pad coverage, but happy to add a test for the non-convergence@warnpath if you'd like it covered, since that's the behaviour that replacedcheck_convergence.🤖 Generated with Claude Code
https://claude.ai/code/session_01HVJi2UB1AcCkUqmRNV6ufW
Generated by Claude Code