Repository navigation
SLDS posteriors via smooth, tied_params, and a green suite - #11
Merged
harrisonritz merged 4 commits intoAug 24, 2026
Merged
harrisonritz merged 4 commits into
harrisonritz merged 4 commits into
Conversation
…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
…ting Four pre-existing failures on this branch, none of them caused by the posterior work in the previous commit. Verified against `claude/poisson-slds-fa-hmm-vr5llo` itself: 1105 passing / 21 erroring there, with `Aqua`/`JET`/`JuliaFormatter` skipped. - **Multi-trial `rand(lds, tsteps_per_trial)` never ran.** `state_params` and `obs_params` were assigned from two branches of an `if` and then captured by the `tforeach` sampling closure, so Julia boxed them and OhMyThreads rejected the closure with `Attempted to capture and modify outer local variables`. They now come from `_per_trial_sample_params`, so each name is assigned once. This is what produced 19 of the 21 errors — every test that samples more than one trial from an LDS or PLDS. - **`fit!(slds, y; tie_emissions=true)` read an uninitialized workspace.** The unit-weight aggregator seeds its buffers from the data-only constant blocks (`Σ y y'`, `Σ y`, the observation count, the `uy` blocks), which only the LDS/PLDS `fit!` entry points fill; the SLDS never reaches them, because its own M-step goes through the weighted aggregator, which rebuilds the data-side sums each E-step and needs no constants. The tied-emission update called the unit-weight aggregator anyway, so `Szz_Ab` and `Szz_Cd` came out indefinite (eigenvalues around -8) and the Cholesky threw `PosDefException` — and where it did not throw, the tied emission was fitted from garbage. Both the plain and the grouped tied-emission paths now fill the constants first. - **JET.** `_slds_trial_elbo`'s `ll` scratch, analysed at the unspecialized signature, widened to a union with an `Any`-eltype branch that no `joint_loglikelihood!` method matches. Asserting the element type on the view drops the branch. - **JuliaFormatter.** Ran 1.0.62 over the package; it rewrote eight files, six of them untouched by this branch's own work. Also switched the SLDS docs example over to `smooth`. It was reaching into `initialize_FilterSmooth` / `SLDSDiscreteLayer` / `estep!` behind a warning that the package "does not yet expose a public posterior-decoding API for SLDS" — which is exactly what the previous commit added. Full suite now passes: 1775 tests, including Aqua, JuliaFormatter, JET, and all seven docs examples. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
posterior into smooth, and make elbo/loglikelihood report itposterior into smooth, and get the test suite green
## `tied_params`
`tie_emissions` could only tie `[C d D]` and `R`. It becomes `tied_params`,
which takes a `Symbol` or a collection of them and ties any parameter group:
fit!(slds, y; tied_params = (:C, :R)) # was tie_emissions=true
fit!(slds, y; tied_params = (:A, :Q)) # one set of dynamics, switching emissions
fit!(slds, y; tied_params = :Q) # shared process noise, switching A
Names follow `depends_on`/`fit_bool`: `[A b B]` is fit as one regression, so any
of `:A`/`:b`/`:B` names the whole group, likewise `:C`/`:d`/`:D` for `[C d D]`,
with `:Q` and `:R` groups of their own. `:x0`/`:P0` are accepted and dropped —
an SLDS ties its initial state across regimes unconditionally, so the keyword
carries the model's full vocabulary without implying a choice it doesn't
control. A name the model doesn't own throws, listing the ones it does.
`tie_emissions` is gone rather than deprecated: it never shipped, and lives only
on this branch.
## How a tied group is fitted
The M-step now expresses "tied across regimes" as a slot vector over the
regimes and hands it to the same `_grouped_update_*!` helpers `depends_on`
already uses — one slot for a tied group, one slot per regime otherwise. Both
SLDS M-steps (plain and grouped) collapse onto that one path, which is what let
`_update_tied_emission!` and `_update_tied_emission_grouped!` go away entirely.
The grouped path additionally drops its per-regime update loop: units are
already flat over (regime, cell), and a tie just removes the regime from the
slot, so a tied group stays a property of the cell — each session keeps its own
version, shared by every regime, which is what `tie_emissions` did.
Three cases, all exact:
- **Group tied with its noise** (`(:C, :R)`, `(:A, :Q)`) — the ordinary M-step
on pooled statistics. The shared term doesn't depend on the regime and
`Σₖ γₖ(t) = 1`, so the summed per-regime weighted objectives collapse to the
unit-weight one.
- **Noise tied alone** (`:Q`, `:R`) — each regime contributes its own residual
scatter, summed before the covariance is formed. Already how
`_grouped_update_Q!`/`_grouped_update_R!` work.
- **Regression tied alone** (`:C` without `:R`) — the covariance no longer
divides out of `∂/∂W`, the output rows couple, and the shared fit is a
generalized least-squares solve. New: `_tied_gls_regression`.
`_tied_gls_regression` is written against a flat list of units rather than
anything SLDS-specific, so other callers with the same shape can use it. It
reduces to `mn_map` exactly when the covariances agree — verified in a test —
so the pooled path is a special case, not a second estimator. It costs
`O((p·m)³)`; callers reach for it only when the noise genuinely is not shared,
and both the docstring and the manual say to tie the pair when you can.
## Fixed alongside
A grouped fit that pooled a regression over units with *different* noise
versions — `depends_on = (R = session,)` with one emission over all sessions —
was solving the pooled normal equations, which do not maximize the ELBO there.
Same gap, same fix: those cases now take the GLS path.
The documentation build failed on `set_group_seeds!`, which is exported and
documented but was in no `@docs` block, so Documenter raised `missing_docs` plus
the unresolved `@ref`s pointing at it. Added to the api.md group-accessor block;
`docs/make.jl` now completes.
## Tests
Canonicalization (aliases, dedup, `:x0`/`:P0`, bad names, `:R` on a Poisson
emission); each group ties exactly itself and nothing else; pairs and
everything-tied; the GLS paths produce a shared regression with per-regime
covariances; frozen groups are untouched; `:x0`/`:P0` change nothing. The
load-bearing one is ELBO monotonicity across every tie configuration — a tied
group is only fitted right if it still maximizes the same bound, and a pooled
fit where GLS is needed would show up there as a decrease.
Full suite: 1855 passing, including Aqua, JuliaFormatter, JET and the docs
examples.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
posterior into smooth, and get the test suite greensmooth, tied_params, and a green suite
harrisonritz
added a commit
to depasquale-lab/StateSpaceDynamics.jl
that referenced
this pull request
Aug 23, 2026
Pooling several units' sufficient statistics and solving the ordinary normal equations maximizes the objective only when those units also share the residual covariance: held fixed, it divides out of the score. When it does not, the output rows couple and the pooled solve is simply the wrong estimator — the fit walks downhill. `depends_on = (R = session,)` with one emission over every session is exactly that configuration, and it was reaching the pooled path. On two sessions whose noise differs by a factor of 100 the ELBO fell on 16 of 29 iterations, worst step -0.84. It now rises on every one, and converges higher (-474.3 against -486.8). `_tied_gls_regression` is the estimator, ported from harrisonritz#11 and kept as a primitive over a flat list of units rather than anything grouping-specific. `_shared_noise` picks between it and the pooled solve, so the cheap path still runs whenever the covariance genuinely is shared — which, with `depends_on` unset or with `(C = s, d = s, R = s)`, is every existing fit. The GLS solve reduces to exactly `mn_map`'s answer when the covariances agree, with and without a matrix-normal prior, so the two are one estimator rather than two; that reduction is tested directly. Both regressions get it: `[C d D]` against `R`, and `[A b B]` against `Q`. The write-back halves of the two M-steps become `_unpack_obs_V!` / `_unpack_dyn_W!` so the GLS path and the ordinary one share them. Costs `O((p*m)^3)`, against `O(m^3)` for the pooled solve, so it is only reached when the noise is not shared. Ancillary parameter dependencies 131 -> 168 assertions; patch coverage of the files this PR touches stays at 100%. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
A name used to stand in for the group it is fitted with: `:A` meant `[A b B]`
and `:C` meant `[C d D]`, in `depends_on` as well as `tied_params`. That reads
as a claim about one parameter while quietly acting on three, which is easy to
get wrong. Names now mean themselves everywhere.
## `depends_on` (breaking)
`depends_on = (C = session, R = session)` is now an error rather than shorthand
for grouping the whole emission regression. Name every member:
depends_on = (C = session, d = session, D = session, R = session)
A model with no observation input has no `D` to fit, so `(C, d)` is the whole
group there — which is why most of the test and doc call sites gain one key
rather than two. `:A`/`:b`/`:B` the same. The error names the members that are
missing and the regression they belong to.
`group_labels`, `group_parameter` and `set_group_seeds!` are unaffected: they
look a parameter up rather than declaring anything, so an individual name is
still exactly what they want.
## `tied_params`
`tied_params = :C` no longer widens to the emission. Naming part of a jointly
fitted regression is a *partial tie*, and where there is a way to fit one, it is
fitted rather than rejected:
fit!(slds, y; tied_params = (:C, :d, :D, :R)) # whole emission tied
fit!(slds, y; tied_params = :C) # C shared, d and D per regime
Sharing part of a regression is still linear, and it reduces to sharing all of
it. Stationarity in a regime's free block gives that block in closed form, with
the regime's own covariance cancelling; substituting it into the shared block's
condition leaves exactly the system `_tied_gls_regression` already solves, over
statistics with the free columns projected out — Frisch–Waugh–Lovell, one extra
`|free|`-square solve per regime. So the pooled fit, the whole-regression GLS
and the partial tie are one estimator seen at three levels of sharing.
A matrix-normal prior is split between the shared block and the free ones, which
is available exactly when its column precision `Λ` does not couple them. A
diagonal `Λ` always qualifies; one that does not throws rather than dropping the
cross term.
Two partial ties have no such reduction and throw, per the "informative error
unless GLS resolves it" rule:
- a **Poisson** `[C d D]`, fitted by LBFGS rather than from sufficient
statistics, so there is no shared-block solve to run; and
- a partial tie alongside **`depends_on`**, which already splits the regression
into one version per group of trials, so the tie would have to partition
columns and cells at once.
Both are fine with the whole regression tied.
## Tests
`_resolve_tied_params` returns literal names; each name ties exactly its own
parameter and nothing else; `depends_on` rejects a group named only in part
(both on the model and as a call-site override); the two partial ties that
cannot be fitted throw, and their whole-regression forms still work; a diagonal
prior splits and a coupling one throws.
ELBO monotonicity now covers the partial ties too — `:A` alone and `:C` alone
are where a wrong estimator would show up, and eleven configurations hold.
Full suite: 1871 passing, including Aqua, JuliaFormatter, JET and the docs
examples; `docs/make.jl` completes.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
harrisonritz
merged commit Aug 24, 2026
c6dc2d4
into
claude/poisson-slds-fa-hmm-vr5llo
4 checks passed
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.
Four commits.
af5a334— the SLDS posterior work fromCCN2026(Addposteriorfunction to estimate MLE/MAP elbo, responsibility, and smoothed states depasquale-lab/StateSpaceDynamics.jl#161).04f126c— the test failures that were already here.b78287d—tie_emissions→tied_params, and the docs build.3fcb50b— parameter names become literal; partial ties solved by GLS.1.
posterior→smoothBoth did the same job by the same coordinate ascent, differing in how the discrete layer is scored:
posterior(this branch)smooth(CCN2026)q(x)E_q[x]rngrngat allmax_itermax|Δγ| < tol, capped atsmoothing_iters(x_smooth, p_smooth, γ, elbos)(; x, γ, elbo, p),popt-insmooth(slds, y; smoothing_iters=100, tol=1e-6, return_cov=false, progress=false, depends_on=nothing)returns oneNamedTuple, followingsmooth(lds, y)'s shape convention.depends_onkeeps the stitching path available.elbo(slds, y)is that call'selbofield — deterministic, norng(breaking).loglikelihood(slds, y)returns the ELBO instead of throwing (breaking).fit!(slds, y; smoothing_iters=n); the default of 1 leaves existing fits bit-identical.posterioris removed.The alternation is one
_vem_alternate!shared byfit!'s E-step andsmooth, withx_samples === nothingselecting the deterministic coupling.One test needed more than a rename.
test_SLDS_smooth_recovers_regimesseparated its regimes only by dynamics atR = IagainstQ = 0.01·I— not identifiable, and not a regression either: the oldtest_SLDS_posterior_recovers_regimesstandalone onclaude/poisson-slds-fa-hmm-vr5llogives 0.571, under its own> 0.7bar. NowR = 0.01·IagainstQ = 0.05·I, asserting> 0.9(observed 1.0) plus an occupancy check.2. Getting the suite green
Four pre-existing failures. On
claude/poisson-slds-fa-hmm-vr5lloitself: 1105 passing / 21 erroring, with Aqua / JET / JuliaFormatter skipped.rand(lds, tsteps_per_trial)never ran.state_params/obs_paramswere assigned from two branches of anifand captured by thetforeachclosure, so Julia boxed them and OhMyThreads rejected it. 19 of the 21 errors.tie_emissions=truefitted the emission from an uninitialized workspace. The unit-weight aggregator seeds from data-only constant blocks only the LDS/PLDSfit!paths fill; readingundef,Szz_Ab/Szz_Cdcame out indefinite (eigenvalues ≈ -8). Crashing was the lucky outcome — where it didn't throw,[C d D]andRwere fitted from garbage._slds_trial_elbo'sllscratch widened to a union with anAny-eltype branch. JuliaFormatter: eight files, six untouched by this branch.docs/examples/SLDS.jlstopped reaching intoestep!behind a warning that there is no public posterior-decoding API — which commit 1 adds.3.
tied_paramstie_emissionscould only tie the emission. It becomestied_params, taking aSymbolor a collection, and ties any parameter.tie_emissionsis removed rather than deprecated, per your call.The M-step expresses "tied across regimes" as a slot vector over the regimes and hands it to the same
_grouped_update_*!helpersdepends_onalready uses. Both SLDS M-steps collapse onto that path, which let_update_tied_emission!and_update_tied_emission_grouped!go away; the grouped path also lost its per-regime loop.A grouped-fit bug the same primitive closes. A grouped fit pooling a regression over units with different noise versions —
depends_on = (R = session, …)with one emission across sessions — was solving the pooled normal equations, which do not maximize the ELBO there. Flagging it because it changesdepends_onbehavior beyond what you asked for; easy to revert.Docs build.
set_group_seeds!is exported and documented but was in no@docsblock, so Documenter raisedmissing_docsplus four unresolved@refs.4. Literal names, and partial ties
A name used to stand in for the group it is fitted with —
:Ameant[A b B],:Cmeant[C d D]— independs_onas well astied_params. Names now mean themselves everywhere.depends_on(breaking)The error names the missing members and the regression they belong to. A model with no observation input has no
Dto fit, so(C, d)is the whole group there — which is why most call sites gain one key rather than two.group_labels,group_parameterandset_group_seeds!are unaffected: they look a parameter up rather than declaring anything, so an individual name is still exactly what they want.Partial ties
tied_params = :Cno longer widens to the emission. Naming part of a jointly fitted regression is a partial tie, and where there is a way to fit one, it is fitted rather than rejected:Sharing part of a regression is still linear, and it reduces to sharing all of it. Stationarity in a regime's free block gives that block in closed form — the regime's own covariance cancels, since only its term involves it. Substituting it into the shared block's condition leaves exactly the system
_tied_gls_regressionalready solves, over statistics with the free columns projected out (Frisch–Waugh–Lovell), one extra|free|-square solve per regime:So the pooled fit, the whole-regression GLS and the partial tie are one estimator at three levels of sharing — verified: the partial solver returns
_tied_gls_regression's answer exactly when every column is tied, and that in turn returnsmn_map's exactly when the covariances agree.O(m³)O(m³)O((p·m)³)O((p·m′)³)An MN prior is split between the shared and free blocks when its column precision
Λdoes not couple them (a diagonalΛalways qualifies); one that does throws rather than dropping the cross term.Two partial ties have no reduction and throw, per your "informative error unless GLS resolves it":
[C d D], fitted by LBFGS rather than from sufficient statistics;depends_on, which already splits the regression per group of trials, so the tie would have to partition columns and cells at once.Both are fine with the whole regression tied.
Tests
Literal-name resolution; each name ties exactly its own parameter;
depends_onrejects a group named only in part, on the model and as a call-site override; the two unfittable partial ties throw and their whole-regression forms work; a diagonal prior splits and a coupling one throws.ELBO monotonicity now covers the partial ties —
:Aalone and:Calone are where a wrong estimator would surface, and eleven configurations hold.Test results
docs/make.jltest/runtests.jlin full, 10m00s, no failures and no errors.🤖 Generated with Claude Code
https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY