Repository navigation
refactor / split covariance M-steps and ELBO loops into reusable halves - #166
harrisonritz wants to merge 3 commits into
Conversation
Benchmark Results (Julia v1)Time benchmarks
Memory benchmarks
|
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
151d870 to
d29e5b2
Compare
There was a problem hiding this comment.
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 fromelbo!). - Extracts the Poisson LDS observation-side Q-term per-trial loop into
_poisson_q_obs_total(called fromelbo!).
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.
ae02dff to
dec54f1
Compare
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
dec54f1 to
80c06d4
Compare
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
rsenne
left a comment
There was a problem hiding this comment.
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` |
There was a problem hiding this comment.
this should be tested as other PR's rely on it
There was a problem hiding this comment.
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.ν |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
_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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
|
|
||
| # E_q[log p(z_1)]. | ||
| for k in 1:K | ||
| trial_elbo += w[k, 1] * log(slds.πₖ[k] + T(1e-12)) |
There was a problem hiding this comment.
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:
| trial_elbo += w[k, 1] * log(slds.πₖ[k] + T(1e-12)) | |
| wk1 = w[k, 1] | |
| wk1 > 0 && (trial_elbo += wk1 * log(slds.πₖ[k])) |
| 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)) |
There was a problem hiding this comment.
| 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])) |
|
Thanks! Maybe comments are just for agents now... |
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
Restimated 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:
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_totalout of the Poissonelbo!_slds_trial_elboout of the SLDSelbo!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 countNas an argument rather than readingsuf.*_n, since a pooled fit'sNis a sum over models.Follow-ups in this series
depends_on: declare, validate, and read back per-group parametersGenerated by Claude Code