Repository navigation
feature / grouped EM for the Gaussian LDS - #168
Open
harrisonritz wants to merge 9 commits into
Open
harrisonritz wants to merge 9 commits into
harrisonritz wants to merge 9 commits into
Conversation
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-2
branch
from
August 13, 2026 23:04
6b9b221 to
0e80aa0
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-3
branch
2 times, most recently
from
August 13, 2026 23:26
b21a602 to
8be149a
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-2
branch
from
August 13, 2026 23:33
e1212f7 to
d8cc83f
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-3
branch
from
August 13, 2026 23:33
8be149a to
91f13b5
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-2
branch
from
August 14, 2026 11:15
d8cc83f to
1f33318
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-3
branch
from
August 14, 2026 11:15
91f13b5 to
f4a73c3
Compare
Second half of condition-dependent parameters (#165) for the Gaussian model family: `fit!`, `smooth`, `elbo`, `loglikelihood` and `rand` now honour a model's `depends_on` instead of rejecting it. Design. A cell is a maximal set of trials sharing every parameter — the common refinement of all the label vectors. Trials in a cell are governed by a single LinearDynamicalSystem, so the E-step runs on each cell's sub-`Data` completely unchanged; only the M-step and the ELBO become group-aware. This keeps the equal-length shared-covariance fast path alive *within* each group (parameters differ between cells, so their covariances genuinely differ), and the O(D^2*T) workspace storage is allocated once and reused across cells, so a grouped fit's memory tracks an ungrouped one's rather than scaling with the number of sessions. The small per-cell aggregator constants are cached instead, and swapped in before each cell's aggregation. New `grouped_em.jl` holds the parts that are shared with the Poisson LDS and the SLDS: pooling per-cell sufficient statistics per parameter version, the grouped state-side and Gaussian-emission M-steps, and the grouped prior log-density. Pooling is written against a flat list of units, so the same code serves a cell of an LDS and a (regime, cell) pair of an SLDS. The covariance updates accumulate their residual scatter cell by cell, each with its own regression matrix, so a grouping of (say) C finer than that of R comes out right; the MN/IW prior terms are counted once per distinct parameter version. A version backed by a single cell reuses that cell's statistics verbatim, which keeps singleton groups numerically identical to the ungrouped fit. Each entry point also accepts a `depends_on` keyword overriding the model's stored labels for that call, so a held-out set with a different trial count can be scored without mutating the model. `SmoothWorkspace` becomes mutable in its `batched` field only, so a grouped fit can swap in the BLAS-3 buffers sized for the cell it is about to smooth while sharing the expensive block-tridiagonal and shared-covariance storage. The Poisson LDS and the SLDS keep the interim guard until their own follow-ups. Tests. The load-bearing check is that a fully grouped fit — every parameter depending on the session label — reproduces independent per-session fits to floating point, in both the ELBO trace and every fitted parameter; and that a degenerate grouping with one label reproduces the ungrouped fit. On top of that: ragged trial lengths, ELBO monotonicity, per-group noise recovery, grouped `smooth`/`loglikelihood`, held-out scoring through the override, integer labels with priors, and the single-trial `rand` error. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-2
branch
from
August 14, 2026 11:35
1f33318 to
57a9eb8
Compare
harrisonritz
force-pushed
the
claude/split-pr-165-incremental-t8k2s5-3
branch
from
August 14, 2026 11:35
f4a73c3 to
a3f54f4
Compare
`state_params` / `obs_params` are now assigned in both arms of the grouping
branch, which boxes those bindings; the `tforeach` closure below captures
them, and OhMyThreads rejects a boxed capture outright:
rand(rng, lds, fill(20, 8))
ERROR: Attempted to capture and modify outer local variables
Reproduced on 4 threads before this change and clean after. CI runs
single-threaded, where `ntasks == 1`, so the suite never reached it — but any
caller sampling multiple trials with `-t auto` does.
Rebinding both in a `let` before the closure removes the boxes, the same idiom
`fit_SLDS.jl`'s parallel E-step already uses.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
Runs JuliaFormatter v1.0.62 (the version test/Project.toml pins, blue style with always_use_return) over the tree, so the "Code Formatting" test passes. Mostly `for c in 1:(grp.ncells)` needing parens around the range bound. Whitespace only, no logic changes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## claude/split-pr-165-incremental-t8k2s5-2 #168 +/- ##
============================================================================
+ Coverage 96.00% 96.71% +0.71%
============================================================================
Files 19 20 +1
Lines 3651 4018 +367
============================================================================
+ Hits 3505 3886 +381
+ Misses 146 132 -14 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Patch coverage here was 92.21%; the gaps were four distinct behaviours rather than incidental lines, so each gets a test that asserts what it is for. `_pool_obs!` summed observation sufficient statistics across the cells sharing one `[C d D]` slot and was never reached: every grouped test varies `:C`, which gives each cell its own emission and takes the `length(units) == 1` early return. Grouping `:R` alone is the case that needs it — one pooled emission fit from both cells' trials — and the test pins that the two cells share `C` and `d` by reference while keeping their own `R`. The matrix-normal priors contribute per *pair* of slots (`[A b B]` with `Q`, `[C d D]` with `R`, `x0` with `P0`), which is a different code path from the inverse-Wishart terms `test_grouped_integer_labels_and_priors` already covers. The new test sets all three and checks the penalised ELBO lands below the unpenalised one on the same data, so the terms are demonstrably in the objective rather than merely evaluated. `smooth` on a grouped model with a single trial passed as a plain matrix returned one `x`/`P` pair through a dispatch nothing exercised; the test checks it against the vector form of the same trial. The EM loop's early return — `finish!` the meter, truncate `elbos` to the iterations actually run — needed a fit that converges before `max_iter`, and `progress=true` needed any caller at all. One test covers both, and asserts the returned vector really is shorter and really did stop on the tolerance. Ancillary parameter dependencies 108 -> 131 assertions. Patch coverage of the files this PR touches: 347/347 added executable lines. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
harrisonritz
marked this pull request as ready for review
August 23, 2026 16:32
# Conflicts: # test/LinearDynamicalSystems/ParameterDependencies.jl # test/runtests.jl
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
# Conflicts: # src/lds/parameter_groups.jl
Motivation paragraphs out, technical reason kept. The GLS docstrings keep the score equation and the vectorized system, which the code does not show, and drop the prose around them. 67 comment lines out, 35 back. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
3 of 5 — splitting #165 into reviewable pieces. Stacked on #167 (which is stacked on #166); the diff here is only this PR's changes. Base retargets as the parents merge.
fit!,smooth,elbo,loglikelihoodandrandnow honour a Gaussian LDS'sdepends_oninstead of rejecting it. The Poisson LDS and the SLDS keep the interim guard until PRs 4 and 5.Design
A cell is a maximal set of trials sharing every parameter — the common refinement of all the label vectors. Trials in a cell are governed by a single
LinearDynamicalSystem, so the E-step runs on each cell's sub-Datacompletely unchanged; only the M-step and the ELBO become group-aware.Two consequences worth checking in review:
O(D²·T)workspace storage (block-tridiagonal + shared-covariance cache) is allocated once and reused across cells, so a grouped fit's memory tracks an ungrouped one's rather than scaling with the number of sessions. A cell's smoothed covariances are consumed by its own aggregation before the next cell overwrites them. What must survive between iterations is the small per-cell aggregator constants (Σyy', the bias/input blocks) — those have notstepsdimension, so they are cached per cell and copied back in before each cell's aggregation.SmoothWorkspacebecomesmutablein itsbatchedfield only (every other field isconst), so each cell's BLAS-3 mean-pass buffers can be swapped in while the expensive storage stays shared.grouped_em.jlHolds what PRs 4 and 5 also need. Everything is written against a flat list of units — a unit is one thing that produced a
SufficientStatistics: a cell for an LDS, or a (regime, cell) pair for an SLDS. Parameters shared by several units are the same array object, so writing through any one of them updates all.*_yy, which also avoids a Cholesky of a possibly rank-deficient pooledobs_yyfor a small group. A version backed by a single unit reuses that unit's statistics verbatim, which is what keeps singleton groups numerically identical to the ungrouped fit.Cfiner than that ofRcomes out right.Wm Λ Wm'is folded into the IW scale.Held-out scoring
Every entry point takes a
depends_onkeyword overriding the model's stored labels for that call, so a test set with a different trial count can be scored without mutating the model:Tests
The load-bearing check is
test_fully_grouped_matches_independent_fits: with every parameter depending on the session label, the sessions share nothing, so a grouped fit over the pooled data must equal two independent fits — same summed ELBO trace and same fitted parameters, to floating point. Its mirror image istest_single_group_matches_ungrouped: adepends_onwhose labels are all identical adds no parameters and must reproduce the ungrouped fit exactly. Everything else downstream shares that machinery.Also: ragged trial lengths (which take the per-trial smoother fallback rather than the fast path), ELBO monotonicity, per-group noise recovery, grouped
smoothreturning per-cell-shared covariances, held-out scoring through the override, integer labels combined with priors, and the single-trialranderror.Note on
randSampling lives in
simulate.jland is shared by the Gaussian and Poisson emissions, so a Poisson LDS can already be sampled withdepends_onafter this PR even though it cannot yet be fitted. That is intentional — it makes the synthetic multi-session dataset for PR 4's tests available — and PR 4 removes the remaining Poisson guards.Follow-ups in this series
Generated by Claude Code