Skip to content

Add posterior function to estimate MLE/MAP elbo, responsibility, and smoothed states - #161

Merged
rsenne merged 22 commits into
devfrom
CCN2026
Aug 25, 2026
Merged

rsenne merged 22 commits into
devfrom
CCN2026

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

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 export dict?

  • 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

harrisonritz and others added 12 commits July 20, 2026 16:18
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.
Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>
@rsenne

rsenne commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

I'll do my best to review this today, thought it's a big diff so may take me a day or two :) thanks!

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results (Julia v1)

Time benchmarks
main 1083bc3... main / 1083bc3...
GaussianLDS/("smooth", "latent=2", "obs=10", "T=100") 0.221 ± 0.016 ms 0.241 ± 0.067 ms 0.916 ± 0.26
GaussianLDS/("smooth", "latent=2", "obs=10", "T=500") 1.02 ± 0.019 ms 0.988 ± 0.057 ms 1.03 ± 0.062
GaussianLDS/("smooth", "latent=2", "obs=20", "T=100") 0.225 ± 0.031 ms 0.219 ± 0.031 ms 1.03 ± 0.2
GaussianLDS/("smooth", "latent=2", "obs=20", "T=500") 1.06 ± 0.023 ms 1.02 ± 0.081 ms 1.04 ± 0.086
GaussianLDS/("smooth", "latent=2", "obs=5", "T=100") 0.222 ± 0.018 ms 0.217 ± 0.026 ms 1.02 ± 0.15
GaussianLDS/("smooth", "latent=2", "obs=5", "T=500") 1.03 ± 0.021 ms 0.973 ± 0.044 ms 1.06 ± 0.052
GaussianLDS/("smooth", "latent=4", "obs=10", "T=100") 0.408 ± 0.012 ms 0.407 ± 0.04 ms 1 ± 0.1
GaussianLDS/("smooth", "latent=4", "obs=10", "T=500") 1.88 ± 0.023 ms 1.86 ± 0.042 ms 1.01 ± 0.026
GaussianLDS/("smooth", "latent=4", "obs=20", "T=100") 0.412 ± 0.02 ms 0.42 ± 0.049 ms 0.98 ± 0.12
GaussianLDS/("smooth", "latent=4", "obs=20", "T=500") 1.93 ± 0.18 ms 1.89 ± 0.045 ms 1.02 ± 0.096
GaussianLDS/("smooth", "latent=4", "obs=5", "T=100") 0.398 ± 0.014 ms 0.397 ± 0.021 ms 1 ± 0.063
GaussianLDS/("smooth", "latent=4", "obs=5", "T=500") 1.88 ± 0.041 ms 1.85 ± 0.035 ms 1.02 ± 0.03
GaussianLDS/("smooth", "latent=8", "obs=10", "T=100") 0.923 ± 0.028 ms 0.887 ± 0.03 ms 1.04 ± 0.048
GaussianLDS/("smooth", "latent=8", "obs=10", "T=500") 6.85 ± 3.1 ms 7.18 ± 2.3 ms 0.953 ± 0.53
GaussianLDS/("smooth", "latent=8", "obs=20", "T=100") 0.949 ± 0.018 ms 0.916 ± 0.038 ms 1.04 ± 0.047
GaussianLDS/("smooth", "latent=8", "obs=20", "T=500") 5.79 ± 3.2 ms 6.67 ± 2.5 ms 0.868 ± 0.58
PoissonLDS/("smooth", "latent=2", "obs=10", "T=100") 1.17 ± 0.026 ms 0.948 ± 0.015 ms 1.23 ± 0.034
PoissonLDS/("smooth", "latent=2", "obs=10", "T=500") 5.87 ± 0.043 ms 4.76 ± 0.037 ms 1.23 ± 0.013
PoissonLDS/("smooth", "latent=2", "obs=5", "T=100") 1.24 ± 0.02 ms 0.998 ± 0.02 ms 1.24 ± 0.032
PoissonLDS/("smooth", "latent=2", "obs=5", "T=500") 6.79 ± 0.027 ms 5.36 ± 0.051 ms 1.27 ± 0.013
PoissonLDS/("smooth", "latent=4", "obs=10", "T=100") 1.98 ± 0.028 ms 1.67 ± 0.036 ms 1.18 ± 0.031
PoissonLDS/("smooth", "latent=4", "obs=10", "T=500") 10.9 ± 0.082 ms 9.17 ± 0.083 ms 1.19 ± 0.014
PoissonLDS/("smooth", "latent=4", "obs=5", "T=100") 1.57 ± 0.028 ms 1.32 ± 0.019 ms 1.2 ± 0.027
PoissonLDS/("smooth", "latent=4", "obs=5", "T=500") 10.1 ± 0.06 ms 8.35 ± 0.083 ms 1.21 ± 0.014
time_to_load 0.825 ± 0.014 s 0.844 ± 0.034 s 0.978 ± 0.043
Memory benchmarks
main 1083bc3... main / 1083bc3...
GaussianLDS/("smooth", "latent=2", "obs=10", "T=100") 2.08 k allocs: 0.265 MB 2.05 k allocs: 0.235 MB 1.13
GaussianLDS/("smooth", "latent=2", "obs=10", "T=500") 9.3 k allocs: 1.24 MB 9.27 k allocs: 1.09 MB 1.14
GaussianLDS/("smooth", "latent=2", "obs=20", "T=100") 2.09 k allocs: 0.298 MB 2.06 k allocs: 0.259 MB 1.15
GaussianLDS/("smooth", "latent=2", "obs=20", "T=500") 9.31 k allocs: 1.31 MB 9.28 k allocs: 1.11 MB 1.17
GaussianLDS/("smooth", "latent=2", "obs=5", "T=100") 2.08 k allocs: 0.254 MB 2.05 k allocs: 0.227 MB 1.12
GaussianLDS/("smooth", "latent=2", "obs=5", "T=500") 9.3 k allocs: 1.22 MB 9.27 k allocs: 1.08 MB 1.12
GaussianLDS/("smooth", "latent=4", "obs=10", "T=100") 2.09 k allocs: 0.716 MB 2.06 k allocs: 0.626 MB 1.14
GaussianLDS/("smooth", "latent=4", "obs=10", "T=500") 9.3 k allocs: 3.48 MB 9.27 k allocs: 3.03 MB 1.15
GaussianLDS/("smooth", "latent=4", "obs=20", "T=100") 2.1 k allocs: 0.75 MB 2.07 k allocs: 0.652 MB 1.15
GaussianLDS/("smooth", "latent=4", "obs=20", "T=500") 9.31 k allocs: 3.55 MB 9.28 k allocs: 3.06 MB 1.16
GaussianLDS/("smooth", "latent=4", "obs=5", "T=100") 2.09 k allocs: 0.704 MB 2.06 k allocs: 0.618 MB 1.14
GaussianLDS/("smooth", "latent=4", "obs=5", "T=500") 9.3 k allocs: 3.45 MB 9.27 k allocs: 3.02 MB 1.14
GaussianLDS/("smooth", "latent=8", "obs=10", "T=100") 2.09 k allocs: 2.48 MB 2.06 k allocs: 2.16 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=10", "T=500") 9.3 k allocs: 12.3 MB 9.27 k allocs: 10.7 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=20", "T=100") 2.1 k allocs: 2.52 MB 2.07 k allocs: 2.19 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=20", "T=500") 9.31 k allocs: 12.3 MB 9.28 k allocs: 10.7 MB 1.15
PoissonLDS/("smooth", "latent=2", "obs=10", "T=100") 3.32 k allocs: 0.283 MB 2.05 k allocs: 0.234 MB 1.21
PoissonLDS/("smooth", "latent=2", "obs=10", "T=500") 15.3 k allocs: 1.33 MB 9.27 k allocs: 1.09 MB 1.22
PoissonLDS/("smooth", "latent=2", "obs=5", "T=100") 3.53 k allocs: 0.276 MB 2.05 k allocs: 0.228 MB 1.21
PoissonLDS/("smooth", "latent=2", "obs=5", "T=500") 17.4 k allocs: 1.34 MB 9.27 k allocs: 1.09 MB 1.23
PoissonLDS/("smooth", "latent=4", "obs=10", "T=100") 3.54 k allocs: 0.738 MB 2.06 k allocs: 0.626 MB 1.18
PoissonLDS/("smooth", "latent=4", "obs=10", "T=500") 17.4 k allocs: 3.6 MB 9.27 k allocs: 3.03 MB 1.19
PoissonLDS/("smooth", "latent=4", "obs=5", "T=100") 3.33 k allocs: 0.723 MB 2.06 k allocs: 0.618 MB 1.17
PoissonLDS/("smooth", "latent=4", "obs=5", "T=500") 17.4 k allocs: 3.58 MB 9.27 k allocs: 3.03 MB 1.18
time_to_load 0.149 k allocs: 11.2 kB 0.149 k allocs: 11.2 kB 1

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
@rsenne
rsenne self-requested a review August 13, 2026 17:54
@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

i will review this by EOD

@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

kluge regularization

wtf is this lol

Comment thread test/runtests.jl Outdated
Comment on lines +114 to +118
@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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

probably wanna unskip these?

Comment thread test/LinearDynamicalSystems/SLDS.jl Outdated
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])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

many instances of this stale function handle

Comment thread docs/src/SLDS.md Outdated
the smoothed posterior mean), so the returned responsibilities are reproducible.

```@docs
infer_γ

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

needs to be updated

Comment thread src/lds/fit_SLDS.jl Outdated
end

# Core SLDS trial sampling logic
# Core SLDS trial sampling logic. `ux_trial` / `uy_trial` are the canonicalized

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

seems liek this last predicate was meant to be deleted?

Comment thread src/lds/fit_SLDS.jl Outdated
Comment on lines +402 to +404
`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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Comment thread src/lds/fit_SLDS.jl Outdated
Comment on lines +1382 to +1424
"""
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).
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

can we de-claude this?

Comment thread src/lds/fit_SLDS.jl Outdated
function posterior(
slds::SLDS{T,S,O},
data::Data{T};
return_γ::Bool=true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Comment thread src/lds/fit_SLDS.jl Outdated

# Returns
The responsibilities `γ`:
- for a single-trial matrix `y`, a `K × T` matrix; and

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

i don't think this is accurate

Comment thread src/lds/fit_SLDS.jl Outdated
return_x::Bool=false,
max_iter::Int=100,
tol::Real=1e-6,
check_convergence::Bool=true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Comment thread src/lds/fit_SLDS.jl Outdated
Comment on lines +1431 to +1432
return_elbo::Bool=true,
return_x::Bool=false,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@rsenne

rsenne commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

I think overall the functions are well written mopdulo some correctness issues. I do think the semantics need to be re-evaluated posterior is really just smoothing, so I think it might be more appropriate to get this machinery into smooth or a variant of it, and then make the public return both in a NamedTuple and then we can have the necessary kwargs to specify maxiters etc. thoughts?

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

Ok, so maybe smooth just needs to have an smoothing_iters argument (as well as fit!/estep!, for that matter).

And then smooth can just return gamma, and the loglikelihood can return the elbo.

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.

@rsenne

rsenne commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

smooth just needs to have an smoothing_iters

yeah that should work. In theory the smooth! variant can just default to 1 iteration to stay fiathul to OG vLEM algo

And then smooth can just return gamma

do you mean gamma and x? also i don't mind too much if return the elbo as part of a named tuple in smooth. my biggest concern is two places to compute the elbo and the one not called elbo is actually the more accurate one. we should probably also have some way in elbo to allow for the approximation to be better via more iters

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

Ok, I'll take a look next week!

Meant smooth should now additionally return gamma (and elbo, good idea).

harrisonritz pushed a commit that referenced this pull request Aug 22, 2026
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
harrisonritz pushed a commit that referenced this pull request Aug 22, 2026
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
@harrisonritz

Copy link
Copy Markdown
Collaborator Author

ok, I took another pass on this.
You can see a description of the revision in #175

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 _vem_alternate! function (modularized and used across fit! and smooth):

Run `smoothing_iters` discrete↔continuous alternations of the structured-variational
E-step. One alternation is:

1. fill `dl.logL` (`K × sum(T_i)`) with per-regime log-likelihoods of the current
   continuous trajectory,
2. refresh q(z) = γ by forward-backward over the switching chain (HMMs.jl threads
   across trials), and
3. refresh q(x) by re-running the Laplace/Newton smoother on each trial under the new
   γ, filling `tfs[*].x_smooth`, `tfs[*].p_smooth`, and `tfs[*].entropy`.

`x_samples` selects how step 1 reads the continuous trajectory, and is the only
difference between the two callers:

- `x_samples === nothing` — plug in the smoothed mean `E_q[x]`. Deterministic and
  reproducible; used by [`smooth`](@ref) for post-fit inference.
- `x_samples !== nothing` — plug in a joint draw from q(x), and draw the next one in
  step 3. This is the vLEM Monte-Carlo E-step used by [`fit!`](@ref); `x_samples` is
  read then overwritten within each alternation.

It keeps the biased version (use previous draw) in fit! so that it reproduces the original behaviour.

However, it defaults to using the unbiased version in smooth (x_samples === nothing), which might be slower to converge. Take a look at the implementation, something worth thinking about -- you have better intuitions about stochastic VEM than I do.

harrisonritz pushed a commit to harrisonritz/StateSpaceDynamics.jl that referenced this pull request Aug 22, 2026
…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
rsenne added 3 commits August 24, 2026 10:53
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.
@rsenne

rsenne commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator

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.
@rsenne
rsenne requested a lite review from Copilot August 24, 2026 17:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codecov

codecov Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.70130% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.26%. Comparing base (ba1b0be) to head (1083bc3).
⚠️ Report is 39 commits behind head on dev.

Files with missing lines Patch % Lines
src/lds/fit_SLDS.jl 98.69% 2 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rsenne

rsenne commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator

seems we have a flaky broken test?

@rsenne

rsenne commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator

@harrisonritz want to review the changes i made?

@harrisonritz harrisonritz left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread src/lds/types.jl
Comment on lines +34 to +36
const Observations{T} = Union{
AbstractMatrix{T},AbstractArray{T,3},AbstractVector{<:AbstractMatrix{T}}
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

this is a great idea!
Its a little extraneous to the PR, but its small enough that lets just keep it

Comment thread src/lds/fit_SLDS.jl Outdated
Comment on lines 1324 to 1341
`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!(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

is all this info documented elsewhere? Isn't the website generated from this docstring?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

ehh nvm you're probably right, this isn't all needed

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

seems we have a flaky broken test?

wait so lts is failing because it passes? thats weird

@rsenne

rsenne commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

However, it defaults to using the unbiased version in smooth

i'm a bit confused by this. using the mean as a plug in estimator would be biased whereas a sample would not be?

@rsenne

rsenne commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

this is my last remaining concern related to this PR^

@rsenne

rsenne commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

@harrisonritz any further thoughts?

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

looks good!

@rsenne
rsenne merged commit 1376310 into dev Aug 25, 2026
7 checks passed
@rsenne
rsenne deleted the CCN2026 branch August 25, 2026 16:19
@rsenne
rsenne restored the CCN2026 branch August 25, 2026 17:38
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.

3 participants