Skip to content

refactor / split covariance M-steps and ELBO loops into reusable halves - #166

Open
harrisonritz wants to merge 3 commits into
devfrom
claude/split-pr-165-incremental-t8k2s5
Open

harrisonritz wants to merge 3 commits into
devfrom
claude/split-pr-165-incremental-t8k2s5

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

1 of 5 — splitting #165 into reviewable pieces. Pure refactor: no behavior change, no new API, no new tests. The existing suite is the proof.

Why

#165 needs to fit one covariance from several models at once — e.g. a single R estimated from the pooled residual scatter of trials whose emission matrices differ. The current updates compute a residual scatter, add a prior term, and finalize in one function body, so there is no seam to pool at. This PR opens the seams and changes nothing else.

What

Each covariance update becomes an accumulate half and a finalize half, with the existing entry point calling both:

was becomes
update_initial_state_covariance! _accumulate_init_scatter! + _accumulate_x0_prior_scatter! + _finalize_P0!
update_Q! _accumulate_dyn_scatter! + _accumulate_ab_prior_scatter! + _finalize_Q!
update_R! _accumulate_obs_scatter! + _accumulate_cd_prior_scatter! + _finalize_R!

The accumulators += into the scatter matrix instead of overwriting it, and the entry points now zero the scratch buffer first, call the halves in the original order, and finalize — so the single-model arithmetic is unchanged operation for operation. The prior scatter is a separate call because a prior term belongs to a regression, and #165 can have several regressions sharing one covariance.

Packing the stacked regressions into a workspace buffer is factored out as _pack_dyn_W! ([A b B]) and _pack_obs_V! ([C d D]), shared by the residual-scatter, prior-scatter, and log-density paths.

Two per-trial loops move out of their enclosing ELBO functions with their bodies byte-identical:

  • _poisson_q_obs_total out of the Poisson elbo!
  • _slds_trial_elbo out of the SLDS elbo!

so that a trial can later be evaluated against a parameter set that differs from its neighbours'.

Review notes

  • _finalize_P0!/_finalize_Q!/_finalize_R! take the sample count N as an argument rather than reading suf.*_n, since a pooled fit's N is a sum over models.
  • The symmetrization stays where it was — after the prior term, before the MAP division — so IW posteriors are unaffected.
  • Nothing here is exported, and no call site outside these files changes.

Follow-ups in this series

  1. depends_on: declare, validate, and read back per-group parameters
  2. Grouped EM for the Gaussian LDS
  3. Grouped EM for the Poisson LDS
  4. Grouped EM for the SLDS

Generated by Claude Code

@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results (Julia v1)

Time benchmarks
main a293826... main / a293826...
GaussianLDS/("smooth", "latent=2", "obs=10", "T=100") 0.215 ± 0.01 ms 0.203 ± 0.0087 ms 1.06 ± 0.068
GaussianLDS/("smooth", "latent=2", "obs=10", "T=500") 1.01 ± 0.046 ms 0.963 ± 0.0058 ms 1.05 ± 0.048
GaussianLDS/("smooth", "latent=2", "obs=20", "T=100") 0.224 ± 0.017 ms 0.212 ± 0.01 ms 1.05 ± 0.094
GaussianLDS/("smooth", "latent=2", "obs=20", "T=500") 1.04 ± 0.018 ms 0.977 ± 0.029 ms 1.06 ± 0.036
GaussianLDS/("smooth", "latent=2", "obs=5", "T=100") 0.21 ± 0.024 ms 0.2 ± 0.01 ms 1.05 ± 0.13
GaussianLDS/("smooth", "latent=2", "obs=5", "T=500") 1.01 ± 0.058 ms 0.956 ± 0.0093 ms 1.05 ± 0.062
GaussianLDS/("smooth", "latent=4", "obs=10", "T=100") 0.413 ± 0.025 ms 0.38 ± 0.016 ms 1.09 ± 0.079
GaussianLDS/("smooth", "latent=4", "obs=10", "T=500") 1.88 ± 0.025 ms 1.77 ± 0.04 ms 1.06 ± 0.028
GaussianLDS/("smooth", "latent=4", "obs=20", "T=100") 0.421 ± 0.012 ms 0.405 ± 0.19 ms 1.04 ± 0.49
GaussianLDS/("smooth", "latent=4", "obs=20", "T=500") 1.93 ± 0.59 ms 1.87 ± 0.51 ms 1.03 ± 0.42
GaussianLDS/("smooth", "latent=4", "obs=5", "T=100") 0.408 ± 0.027 ms 0.382 ± 0.032 ms 1.07 ± 0.11
GaussianLDS/("smooth", "latent=4", "obs=5", "T=500") 1.87 ± 0.047 ms 1.76 ± 0.025 ms 1.06 ± 0.031
GaussianLDS/("smooth", "latent=8", "obs=10", "T=100") 0.931 ± 0.02 ms 0.873 ± 0.04 ms 1.07 ± 0.054
GaussianLDS/("smooth", "latent=8", "obs=10", "T=500") 7.02 ± 3.6 ms 7.35 ± 2.4 ms 0.955 ± 0.59
GaussianLDS/("smooth", "latent=8", "obs=20", "T=100") 0.945 ± 0.037 ms 0.886 ± 0.0072 ms 1.07 ± 0.043
GaussianLDS/("smooth", "latent=8", "obs=20", "T=500") 5.44 ± 3.6 ms 7.4 ± 1.4 ms 0.735 ± 0.51
PoissonLDS/("smooth", "latent=2", "obs=10", "T=100") 1.12 ± 0.015 ms 0.966 ± 0.015 ms 1.16 ± 0.024
PoissonLDS/("smooth", "latent=2", "obs=10", "T=500") 5.6 ± 0.035 ms 4.86 ± 0.052 ms 1.15 ± 0.014
PoissonLDS/("smooth", "latent=2", "obs=5", "T=100") 1.18 ± 0.023 ms 1.01 ± 0.021 ms 1.16 ± 0.033
PoissonLDS/("smooth", "latent=2", "obs=5", "T=500") 6.41 ± 0.06 ms 5.43 ± 0.029 ms 1.18 ± 0.013
PoissonLDS/("smooth", "latent=4", "obs=10", "T=100") 1.98 ± 0.022 ms 1.72 ± 0.055 ms 1.15 ± 0.039
PoissonLDS/("smooth", "latent=4", "obs=10", "T=500") 10.8 ± 0.077 ms 9.28 ± 0.059 ms 1.16 ± 0.011
PoissonLDS/("smooth", "latent=4", "obs=5", "T=100") 1.6 ± 0.044 ms 1.35 ± 0.02 ms 1.18 ± 0.037
PoissonLDS/("smooth", "latent=4", "obs=5", "T=500") 10.1 ± 0.092 ms 8.5 ± 0.098 ms 1.18 ± 0.017
time_to_load 0.798 ± 0.017 s 0.812 ± 0.0017 s 0.982 ± 0.021
Memory benchmarks
main a293826... main / a293826...
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

Pure refactor ahead of condition-dependent parameters (#165): no behavior
change, no new API, no new tests. Each of the three covariance updates is
split into an accumulate half and a finalize half so a single covariance can
later be fitted from the pooled residual scatter of several models, each
contributing with its own regression matrix:

  update_initial_state_covariance!  ->  _accumulate_init_scatter!
                                        _accumulate_x0_prior_scatter!
                                        _finalize_P0!
  update_Q!                         ->  _accumulate_dyn_scatter!
                                        _accumulate_ab_prior_scatter!
                                        _finalize_Q!
  update_R!                         ->  _accumulate_obs_scatter!
                                        _accumulate_cd_prior_scatter!
                                        _finalize_R!

The accumulators add into the scatter matrix instead of overwriting it, and
the public entry points now zero the scratch, call the halves in the original
order, and finalize — so the single-model path is arithmetically unchanged.
Packing the stacked regressions `[A b B]` and `[C d D]` into a workspace
buffer becomes `_pack_dyn_W!` / `_pack_obs_V!`, which the prior-scatter and
log-density paths share.

Two per-trial loops are lifted out of their enclosing ELBO functions with
their bodies unchanged: `_poisson_q_obs_total` from the Poisson `elbo!` and
`_slds_trial_elbo` from the SLDS `elbo!`, so a trial can be evaluated against
a parameter set that differs from its neighbours'.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from 151d870 to d29e5b2 Compare August 13, 2026 23:04
@harrisonritz
harrisonritz requested a lite review from Copilot August 13, 2026 23:58

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.

Pull request overview

This PR is a refactor that splits several covariance M-step updates and two ELBO per-trial loops into reusable “accumulate” and “finalize” halves, enabling future pooled/grouped fits (per #165) without changing single-model behavior.

Changes:

  • Refactors Gaussian LDS covariance updates into reusable helpers: pack-regression, accumulate residual scatter, accumulate prior scatter, and finalize (MAP/MLE) steps.
  • Extracts the SLDS per-trial ELBO computation into _slds_trial_elbo (called from elbo!).
  • Extracts the Poisson LDS observation-side Q-term per-trial loop into _poisson_q_obs_total (called from elbo!).

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
src/lds/gaussian_observations.jl Splits update_R! into packing, residual/prior scatter accumulation, and finalize steps.
src/lds/continuous_latents.jl Splits update_initial_state_covariance! and update_Q! into accumulate/finalize halves and adds shared regression packing helpers.
src/lds/fit_SLDS.jl Extracts per-trial ELBO logic into _slds_trial_elbo and reuses it from elbo!.
src/lds/fit_PLDS.jl Extracts the Poisson observation Q-term per-trial loop into _poisson_q_obs_total and reuses it from elbo!.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch 2 times, most recently from ae02dff to dec54f1 Compare August 14, 2026 11:35
Splitting `_slds_trial_elbo` out of `elbo!` changed two things. The `slds`
argument was declared `SLDS{T}`, dropping the `S`/`O` parameters `elbo!`
carries; since `LDSs` is a `Vector{LinearDynamicalSystem{T,S,O}}`, leaving
them free makes `slds.LDSs[k]` looser than in the original. And the
per-regime `ll` view was hoisted above the `for k` loop.

JET reports the hoisted scratch as `SubArray{Any,...}` over an existential
`Vector{T} where T<:Real` parent, which matches no `joint_loglikelihood!`
method. The weighted `joint_loglikelihood!(ws, slds, x, y, w, ...)` in this
same file makes the identical call with the view built at the call site and
is not flagged, so restore that shape here too.

The loop body is now identical to the one the helper was extracted from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from dec54f1 to 80c06d4 Compare August 14, 2026 11:59
joint_loglikelihood!'s single-regime method (continuous_latents.jl) requires
S<:GaussianStateModel{T0} — state_loglikelihood! reads .A/.Q/.b/.x0/.P0
directly, so it can't be generic over AbstractStateModel. Every other file in
the codebase already declares S<:GaussianStateModel{T} for this reason (the
only concrete AbstractStateModel subtype there is); fit_SLDS.jl was the
outlier, declaring S<:AbstractStateModel (unbound, not even tied to T).

For _slds_trial_elbo specifically, that gap meant JET's abstract-domain
analysis couldn't prove slds.LDSs[k] satisfies joint_loglikelihood!'s bound,
so it reported "no matching method found" even though runtime dispatch always
resolves fine. Tightening the where-clause to S<:GaussianStateModel{T},
O<:AbstractObservationModel{T} matches the bound joint_loglikelihood! actually
requires and the convention used everywhere else. This doesn't change what the
function accepts at runtime — Julia dispatches on the argument's actual
(always-Gaussian) type regardless of a caller's looser static annotation —
only what JET can prove ahead of time.

That alone wasn't sufficient: `ll = view(slds_ws.ll_tmp, 1:Tsteps)` was
independently inferred as SubArray{Any,...} rather than SubArray{T,...} in
JET's abstract interpretation. Asserting the view's type fixes that; the
assertion is a no-op at runtime since it always holds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
@codecov

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.16%. Comparing base (ba1b0be) to head (a293826).
⚠️ Report is 38 commits behind head on dev.

Additional details and impacted files
@@             Coverage Diff             @@
##              dev     #166       +/-   ##
===========================================
+ Coverage   82.68%   96.16%   +13.48%     
===========================================
  Files          17       18        +1     
  Lines        4210     3342      -868     
===========================================
- Hits         3481     3214      -267     
+ Misses        729      128      -601     

☔ 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.

@harrisonritz
harrisonritz marked this pull request as ready for review August 23, 2026 16:32

@rsenne rsenne left a comment

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.

Overall, looks good. I will be reviewing these one at a time starting now! If there are any points where Claude is being verbose i just ask it gets trimmed. I didn't look at comments too much


Add this model's initial-state scatter `Σγ(x₁-x0)(x₁-x0)' + Σγ P₁` to `S0`.

`S0` is accumulated into rather than overwritten, so a caller fitting one `P0`

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 should be tested as other PR's rely on it

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.

add a small test that runs _accumulate_init_scatter! / _accumulate_dyn_scatter! / _accumulate_obs_scatter! for two models into one buffer and checks it equals the sum of the two single-model scatters?

S0 ./= T(N)
S0 ./= N
else
Ψ, ν = lds.state_model.P0_prior.Ψ, lds.state_model.P0_prior.ν

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.

pre-existing but: with P0_prior set this branch allocates 736 B per call (measured), while _finalize_Q! avoids that by asserting Ψ::Matrix{T}. Same one-line assert here would make the three finalizers consistent

fill!(S0, zero(T))
_accumulate_init_scatter!(S0, lds, suf)
_accumulate_x0_prior_scatter!(S0, lds)
Symmetrize!(S0)

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.

_finalize_Q! and _finalize_R! symmetrize internally, but _finalize_P0! leaves it to the caller. Can you move Symmetrize!(S0) to the top of _finalize_P0! (and mention it in its docstring)?

function update_Q!(
lds::LinearDynamicalSystem{T,S,O}, suf::SufficientStatistics{T}, sws::SmoothWorkspace{T}
"""
_pack_dyn_W!(W, lds)

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.

The PR description says _pack_dyn_W!/_pack_obs_V! are shared with the log-density path, but here they are only used by the M-step?

S_res .+= Wm * AB_prior.Λ * Wm'
end
AB_prior === nothing && return S_res
W = _pack_dyn_W!(sws.reg.AB, lds)

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.

Nit: this repacks into sws.reg.AB, so the helper overwrites that buffer as a side effect. Fine, but please say so in the docstring. Same for _accumulate_cd_prior_scatter! and sws.reg.CD.

Comment thread src/lds/fit_SLDS.jl

# E_q[log p(z_1)].
for k in 1:K
trial_elbo += w[k, 1] * log(slds.πₖ[k] + T(1e-12))

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.

Blocking, for the rebase: #161 on dev replaced this with a guarded term (zero-probability regimes can't carry mass at t=1, so the 1e-12 fudge is gone). The rebase conflict only shows up in elbo!; this helper merges cleanly with the old body, so taking your side of that hunk silently reverts #161. I diffed dev's inline body against this helper and these two terms (plus your ::AbstractVector{T} assert) are the only differences. Please port them here, along with #161's comment block:

Suggested change
trial_elbo += w[k, 1] * log(slds.πₖ[k] + T(1e-12))
wk1 = w[k, 1]
wk1 > 0 && (trial_elbo += wk1 * log(slds.πₖ[k]))

Comment thread src/lds/fit_SLDS.jl
for t in t1:(t2 - 1)
ξt = fb_storage.ξ[t]
for i in 1:K, j in 1:K
trial_elbo += ξt[i, j] * log(slds.A[i, j] + T(1e-12))

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.

see above

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.

Suggested change
trial_elbo += ξt[i, j] * log(slds.A[i, j] + T(1e-12))
ξij = ξt[i, j]
ξij > 0 && (trial_elbo += ξij * log(slds.A[i, j]))

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

Thanks!

Maybe comments are just for agents now...

This branch has not been deployed

No deployments
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.

4 participants