Repository navigation
Conversation
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.
…es when requested
…mprove numerical stability
|
I'll do my best to review this today, thought it's a big diff so may take me a day or two :) thanks! |
Benchmark Results (Julia v1)Time benchmarks
Memory benchmarks
|
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
Remove evidence of hacks that didn't work
|
i will review this by EOD |
wtf is this lol |
| @skip_test test_SLDS_posterior_basic() | ||
| @skip_test test_SLDS_posterior_shapes() | ||
| @skip_test test_SLDS_posterior_deterministic_and_modes() | ||
| @skip_test test_SLDS_posterior_K1() | ||
| @skip_test test_SLDS_posterior_recovers_distinct_regimes() |
There was a problem hiding this comment.
probably wanna unskip these?
| z, x, y = rand(rng, slds, fill(tsteps, ntrials)) | ||
|
|
||
| # Single-trial matrix ⇒ bare K × T matrix; wrapping in a vector ⇒ 1-element vector. | ||
| γ_mat = infer_γ(slds, y[1]) |
There was a problem hiding this comment.
many instances of this stale function handle
| the smoothed posterior mean), so the returned responsibilities are reproducible. | ||
|
|
||
| ```@docs | ||
| infer_γ |
| end | ||
|
|
||
| # Core SLDS trial sampling logic | ||
| # Core SLDS trial sampling logic. `ux_trial` / `uy_trial` are the canonicalized |
There was a problem hiding this comment.
seems liek this last predicate was meant to be deleted?
| `ws.opt.grad_buf` and returns it. `ux` (dynamics input, feeds `-Q⁻¹` / | ||
| `A'Q⁻¹` residuals via `Bₖ u`) and `uy` (observation input, feeds the emission | ||
| gradient via `Dₖ v`) are per-trial matrices; `nothing` or zero-row skips them. |
There was a problem hiding this comment.
I'm assuming claude added these types of statements. Probably can mention how inputs are done once and don't need to mention again unless the function is specific to them or has some behavior meant to truly notice
| """ | ||
| posterior(slds, y; max_iter=100, tol=1e-6, check_convergence=true, progress=false) | ||
|
|
||
| Infer the discrete-state responsibilities `γₜ(k) = q(zₜ = k) ≈ p(zₜ = k ∣ y₁:T)` | ||
| of a **fitted** `SLDS`, holding all model parameters fixed. | ||
|
|
||
| This is a post-fit *inference* routine: it estimates the discrete posterior for a | ||
| model whose parameters are already learned, and does **not** update them (there is | ||
| no M-step). | ||
|
|
||
| It runs the structured-variational E-step, alternating between: | ||
|
|
||
| 1. **discrete smoothing** — a forward-backward pass over the switching chain that | ||
| refreshes `q(z)` from the current per-regime log-likelihoods, and | ||
| 2. **continuous smoothing** — the Laplace/Kalman smoother that refreshes `q(x)` | ||
| under the updated responsibilities `γ`, | ||
|
|
||
| until either the responsibilities converge or for a fixed number of iterations. | ||
|
|
||
| # Arguments | ||
| - `y`: observations — a `(obs_dim, T)` matrix (single trial), a | ||
| `(obs_dim, T, ntrials)` array, or a `Vector` of per-trial `(obs_dim, T_i)` | ||
| matrices (ragged trial lengths allowed). | ||
|
|
||
| # Keywords | ||
| - `max_iter::Int=100`: maximum number of E-step (forward-backward + smoother) | ||
| iterations. | ||
| - `tol::Real=1e-6`: convergence tolerance on `max|Δγ|`, the largest absolute change | ||
| in any responsibility between successive iterations (used only when | ||
| `check_convergence=true`). | ||
| - `check_convergence::Bool=true`: the mode flag. `true` iterates *until | ||
| convergence* (`max|Δγ| < tol`), capped at `max_iter` iterations; `false` runs | ||
| *exactly* `max_iter` iterations. | ||
| - `progress::Bool=false`: show a progress bar. | ||
|
|
||
| # Returns | ||
| The responsibilities `γ`: | ||
| - for a single-trial matrix `y`, a `K × T` matrix; and | ||
| - otherwise (3-D array or vector-of-matrices input), a `Vector` of per-trial | ||
| `K × T_i` matrices, one per trial. | ||
|
|
||
| Each column is a probability vector over the `K` discrete states (sums to 1). | ||
| """ |
| function posterior( | ||
| slds::SLDS{T,S,O}, | ||
| data::Data{T}; | ||
| return_γ::Bool=true, |
There was a problem hiding this comment.
if someone is calling posterior--is there really a circumstance in which they dont want gamma? I mean to an extent what sets this apart from smooth is really just the gammas
|
|
||
| # Returns | ||
| The responsibilities `γ`: | ||
| - for a single-trial matrix `y`, a `K × T` matrix; and |
There was a problem hiding this comment.
i don't think this is accurate
| return_x::Bool=false, | ||
| max_iter::Int=100, | ||
| tol::Real=1e-6, | ||
| check_convergence::Bool=true, |
There was a problem hiding this comment.
this also seems a bit unneccesary. I mean we probably should just check convergence and if we don't ust throw a warnign and return given the max_iters
| return_elbo::Bool=true, | ||
| return_x::Bool=false, |
There was a problem hiding this comment.
I think there is a bit of semantic dubiousness going on. we noe effecticely have two ways to get elbo right? so why should this function privilege the "good elbo" ? I wonder if this function need to be integrated more into the core code somewhat like in ssm -- e.g., the same function does the posterior, but depending on the calls, we wi8ther iterate until convergence or do it once etc.
|
I think overall the functions are well written mopdulo some correctness issues. I do think the semantics need to be re-evaluated |
|
Ok, so maybe And then The only hiccup is that you might only want to run the back-and-forth estimator once -- because it might take many iterations to converge -- so nice to have it spit out the posterior and the elbo from the same fit. Maybe some caching would help here. |
yeah that should work. In theory the
do you mean gamma and x? also i don't mind too much if return the elbo as part of a named tuple in |
|
Ok, I'll take a look next week! Meant smooth should now additionally return gamma (and elbo, good idea). |
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
|
ok, I took another pass on this. one important decision is whether to resample q(x) each iteration, or whether to keep using the mean from the previous iteration. Here is the description from the new It keeps the biased version (use previous draw) in However, it defaults to using the unbiased version in |
…t it Brings the SLDS posterior work from the CCN2026 branch (PR depasquale-lab#161) onto this branch, replacing the `posterior` function this branch grew independently. The two implementations did the same job by the same coordinate ascent, but `posterior` scored the discrete layer against a *sample* from q(x) — the vLEM Monte-Carlo E-step — so its `γ` carried Monte-Carlo noise and needed an `rng` and a fixed iteration count. `smooth` scores it at the smoothed posterior mean instead: deterministic, reproducible, and iterated to a `γ` fixed point. - `smooth(slds, y; smoothing_iters, tol, return_cov, progress, depends_on)` returns one `NamedTuple` `(; x, γ, elbo, p)`, following the shape convention of `smooth(lds, y)` — matrix in, arrays out; vector or 3-D array in, per-trial vectors out. Covariances are opt-in (`return_cov`) because they are the large piece. `depends_on` keeps the stitching/grouped path available, and grouped datasets are evaluated cell by cell as before. - `elbo(slds, y)` is now that call's `elbo` field rather than a one-shot Monte-Carlo E-step, so it is deterministic and takes no `rng`. - `loglikelihood(slds, y)` returns the ELBO instead of throwing. The exact marginal is still intractable (a sum over K^T regime sequences); the docstring says so. - `fit!(slds, y; smoothing_iters=n)` runs `n` alternations per E-step. The default of 1 is the standard vLEM update, so existing fits are unchanged. - The alternation itself is now one `_vem_alternate!` shared by `fit!`'s E-step and `smooth`, with `x_samples === nothing` selecting the deterministic coupling. `estep!` and `_estep_grouped!` are thin wrappers over it, and the fill/smooth passes are factored into `_slds_fill_logL!` / `_slds_smooth_all!` so the grouped and ungrouped paths stop being written twice. Tests: the eight `smooth`/`smoothing_iters` tests from CCN2026, plus the two `posterior` tests rewritten against `smooth`. `test_SLDS_smooth_recovers_regimes` now separates its regimes with emission noise small enough for the smoothed mean to carry the dynamics — the old configuration (R = I against Q = 0.01·I) is not identifiable, and the assertion it carried did not hold on this branch either. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
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.
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.
|
I''ll have review / updates on thsi today |
`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.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## dev #161 +/- ##
===========================================
+ Coverage 82.68% 96.26% +13.57%
===========================================
Files 17 19 +2
Lines 4210 3585 -625
===========================================
- Hits 3481 3451 -30
+ Misses 729 134 -595 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
seems we have a flaky broken test? |
|
@harrisonritz want to review the changes i made? |
harrisonritz
left a comment
There was a problem hiding this comment.
Observations type is a great idea, let's keep it.
You trimmed a lot of the mstep docstring, just want to make sure thats documented elsewhere.
| const Observations{T} = Union{ | ||
| AbstractMatrix{T},AbstractArray{T,3},AbstractVector{<:AbstractMatrix{T}} | ||
| } |
There was a problem hiding this comment.
this is a great idea!
Its a little extraneous to the PR, but its small enough that lets just keep it
| `data` and `suf` are built once by [`fit!`](@ref) and reused every iteration: | ||
| `Data` revalidates the observations and inputs on construction, and `suf` is | ||
| overwritten per regime by the weighted aggregator, so neither belongs inside | ||
| the EM loop. | ||
|
|
||
| - Updates discrete parameters (`slds.A`, `slds.πₖ`) via `StatsAPI.fit!` on the discrete | ||
| layer (uses HMMs.jl's `ξ[t2]` scratch trick). | ||
| - Updates each LDS component using γ-weighted sufficient statistics aggregated | ||
| by `_aggregate_td_suff_stats_weighted!`. For Gaussian sub-LDSs this is the | ||
| full suf-based M-step (regression + IW MAP). For Poisson sub-LDSs the state- | ||
| side updates flow through the same suf path; the emission [C d] is updated | ||
| via the existing LBFGS routine (Poisson is non-conjugate and cannot be | ||
| folded into the regression). | ||
|
|
||
| When inputs are present the weighted aggregator folds `Bₖ u` / `Dₖ v` into the | ||
| regression targets, so `Bₖ` and `Dₖ` are re-estimated alongside `Aₖ` / `Cₖ`. | ||
| Update the transition probabilities and each regime's parameters from | ||
| γ-weighted sufficient statistics. Poisson emissions use their LBFGS update. | ||
| """ | ||
| function mstep!( |
There was a problem hiding this comment.
is all this info documented elsewhere? Isn't the website generated from this docstring?
There was a problem hiding this comment.
ehh nvm you're probably right, this isn't all needed
wait so |
i'm a bit confused by this. using the mean as a plug in estimator would be biased whereas a sample would not be? |
|
this is my last remaining concern related to this PR^ |
|
@harrisonritz any further thoughts? |
|
looks good! |
Iterates discrete/continuous smoothing until convergence, then exports elbo, responsibilities, and states. Takes a while to run to completion, so ideally for post-fit eval.
want a better interface to choose what is exported -- maybe an
exportdict?export smoothed cov, but make it optional (big variable)
remove kluge regularization of discrete parameters
maybe we create a function to share with the estep? Eg could have option to run multiple smoothing iterations during estep (iirc you said 2-3 iter can give much (?) better updates). Less surface for estep revisions