Skip to content

various fixes and improvements to profiling - #917

Open
palday wants to merge 36 commits into
mainfrom
pa/profile-audit
Open

palday wants to merge 36 commits into
mainfrom
pa/profile-audit

Conversation

@palday

@palday palday commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Each commit captures a different issue, so it can make sense to review this commit by commit.

  • add entry in NEWS.md
  • after opening this PR, add a reference and run docs/NEWS-update.jl to update the cross-references.
  • I've bumped the version appropriately

The nightly test failures also occur with the code on main. I'll investigate those in a different PR (#918).

`FeProfile` and `profileβj!` indexed the pivoted columns of `Xymat` with
the unpivoted `coef(m)` and `stderror(m)`. For rank-deficient models whose
pivot is not the identity, this offset the response by the wrong
coefficient. It also used the NaN standard error of the aliased column as
the step size, so the ζ loop in `profileβj!` never terminated.

Use `fixef(m)` and `stderror(m)[pivot(m)[j]]` instead, and use `fixef`
rather than `prm.β` in `betaprofile!`.
`profileσs!` computed the lower end of the grid as
`log(max(first(xtrms), 0.01 * lub))`, where `lub` is already on the log
scale. When the upper bound is below 1 and a variance component can reach
zero, this gives `log(0) = -Inf`, and the spline fit fails. Use
`0.01 * last(xtrms)` so the grid scales with the response.
A negative `objective - fmin` in the σ and θ profiles caused a bare
`DomainError` from `sqrt`. Add `_ζ`, which treats negative differences
within `sqrt(eps) * max(1, |fmin|)` as zero and otherwise throws an
`ArgumentError` saying the fit may not have converged. Use it in
`refitσ!`, `_facsz` and the downward loop of `profileθj!`. `_facsz` also
throws if the objective does not change, rather than returning an
infinite step factor.
The upward loop of `profileθj!` called `profileobj!` a second time to
compute ζ instead of reusing the first result. Use `_ζ` on the first
result, which also brings the handling of negative differences in line
with the downward loop.
The fixed-effects coefficients are integrated out of the REML criterion,
so no REML profile over β exists. `profileβj!` compared the ML objective
of the reduced model against the REML objective of the full model, which
gave a discontinuous and meaningless ζ.

`profile` now skips the β profiles for REML fits and warns that the model
should be refit by ML to profile them. The σ and θ profiles are unchanged.
@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.37500% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.17%. Comparing base (12ab678) to head (a30d080).

Files with missing lines Patch % Lines
src/profile/vcpr.jl 98.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #917      +/-   ##
==========================================
+ Coverage   94.90%   95.17%   +0.26%     
==========================================
  Files          38       38              
  Lines        3967     4019      +52     
==========================================
+ Hits         3765     3825      +60     
+ Misses        202      194       -8     
Flag Coverage Δ
current 94.86% <99.36%> (+0.27%) ⬆️
minimum 95.07% <99.37%> (+0.26%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

The swap of `lower` and `upper` in `confint(::MixedModelProfile)` was
added in #785 for REML fits. The flipped limits came from the invalid
REML fixed-effects profiles, which are no longer computed. Without the
swap, no limits are flipped across dyestuff, dyestuff2, sleepstudy,
penicillin, pastes and kb07 under ML and REML.
`FeProfile` built the reduced model without weights, but reused the
weighted `wtz` of the random-effects terms alongside unweighted X and y.
The β profiles of weighted models were therefore wrong. Pass the weights
to the reduced model, and reset the shared `wtz` of the shallow `ReMat`
copies so that reweighting does not overwrite the original model's
storage.
`betaprofile!` filled the ζ, β, σ, σs and θ columns but not the ρ
columns, so every β-profile row kept the correlations from the previous
row written to the scratch vector, which was the estimate row. Compute
them with `ρvals!` and restore λ afterwards, as `mkrow!` does.
`σvals!` and `σvals` for `Diagonal` λ did not take absolute values, unlike
the methods for scalar and `LowerTriangular` λ. The unconstrained
optimization in `profilevc` can end at a negative diagonal element, which
produced negative σ values in the profile table and a non-monotone ζ.
`profileσs!` then did not build the reverse spline, so `confint` silently
omitted the variance components of models such as
`zerocorr(1 + days | subj)`.
`ρvals!` normalized the rows of λ in place. A row of zeros, as occurs
when a θ profile reaches a lower bound of zero, gave NaN, which cannot be
stored in the upper triangle of a `LowerTriangular` matrix and caused an
`ArgumentError`. Compute each correlation from the row norms instead, and
use zero when a row is all zeros, as in `rownormalize`. λ is no longer
modified, so the `setθ!` calls that restored it are removed.
The PRIMA `optimize!` methods for LMMs and GLMMs passed `optsum.final`
as the starting point, so they ignored `optsum.initial` whenever the two
differed. Copy `initial` into `final` before optimizing, as the NLopt
backend does.
With `warm_start=true`, `unfit!` copies the current parameter estimates
into `optsum.initial`, so `refit!` starts from them rather than from the
default initial values. `optsum.final` is reset to the defaults either
way. `_set_init!` takes the `OptSummary` field to initialize.
Each refit in `refitσ!`, `_facsz` and `betaprofile!` now starts from the
estimates at the previous point on the profile instead of the default
initial values. The pass above the estimate is started from θ̂ rather
than from the last point below it. In the sleepstudy, penicillin and kb07
examples this cuts the optimizer evaluations in these profiles by
35-46% and changes the confidence limits by less than 1e-5.
`betaprofile!` computed ζ with an unguarded `sqrt`, so an objective below
the reference value gave a bare `DomainError`. Use `_ζ`, as the σ and θ
profiles do, so that differences within the tolerance are treated as zero
and larger ones throw an informative `ArgumentError`.
In `profileθj!`, the other θ are optimized with θ[j] held fixed. Flipping
the sign of a column of λ is then no longer a symmetry of the objective,
so the conditional optimizer could make a diagonal element negative and
move to the mirror image of the model at -θ[j]. After `rectify!`, the
profile table recorded that mirror point, the θ[j] column was not
monotone, and the spline fit failed (e.g. kb07 with PRIMA). Use the
absolute value of the diagonal elements in the conditional objective.
`_σρs` for `Diagonal` λ scaled the diagonal without taking absolute
values, so `σρs` reported negative standard deviations when λ had a
negative diagonal element. Take absolute values, as `σvals` does.
Drop the unused `nzlb` keyword and commented-out `lowerbd` code from
`profileσs!`, and stop destructuring the unused `λ`, `σ` and `β`
properties there, each of which is computed on access. Remove the
duplicate computation of `σ` in `profileσ`, and give `FeProfile.j` the
concrete type `Int`.
`profilevc` overwrites `optsum.final` in place, so `profileσs!` started
each variance component from the last grid point of the previous one and
left the model at the last grid point. Save θ̂ beforehand, start each
component from it and restore it at the end. The number of objective
evaluations is essentially unchanged; the main effect is that
`profileσs!` no longer leaves the model away from its estimates.
`profile` refits the model while profiling σ, which overwrote `feval`,
`finitial`, `initial_step` and `returnvalue` of the model's `OptSummary`,
so `m.optsum` described the last σ-fixed refit rather than the original
fit. Save a deep copy of `m.optsum` before profiling and restore every
field afterwards, instead of restoring only selected fields.
The step updates in `profileθj!` divided by the change in ζ, so a flat
profile gave an infinite step and a change in the wrong direction (from
an inexact conditional optimization) gave a very large one. The new
`_nextstep` keeps the step when ζ does not change in the expected
direction and limits growth to a factor of 16. The first upward step
falls back to 1/32 when the slope cannot be estimated, and an estimate
within the first step of its lower bound now gets a point on the bound.

Profiles that still cannot be interpolated, because they are flat or not
monotone, now skip the affected spline with a warning instead of
aborting `profile`. This allows the oxide model with
`(1 + Source | Lot & Wafer)` to be profiled.
`profileσs!` added the point where a variance component is zero by
borrowing a row with that component at zero from the other profiles. It
failed with "Collection is empty" when no suitable row existed (e.g. for
the second variance component of a correlated term), and when it
succeeded the borrowed row was not the profile value at zero. For
sleepstudy with `(1 + days | subj)` this gave a lower 95% limit of 0 for
the standard deviation of the random slopes instead of about 3.8.

Compute the point at zero directly by holding the corresponding row of λ
at zero and optimizing the other θ. It is added when the profile has not
reached `-threshold` at the lower end of the grid, so `threshold` is now
passed to `profileσs!`.
The grid for each variance component spanned the smallest and largest
values of that component seen in the other profiles, so the profile did
not always reach ±threshold, and there could be a large gap between the
lowest grid point and zero. For sleepstudy with `(1 + days | subj)`, the
lower 95% limit for the standard deviation of the random slopes was
interpolated across such a gap and came out as 3.780 instead of 3.801.

Extend the grid in both directions with its own spacing on the log scale
until the profile reaches ±threshold. Going down, stop when the profile
becomes flat or at 1% of the estimate, leaving the rest to the exact
point at zero.
@palday
palday marked this pull request as ready for review October 1, 2026 17:32
palday and others added 2 commits October 1, 2026 12:35
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
The test that profiling reports a fit that has not converged used the
maximal kb07 model, whose singular fit stops at platform-dependent
values. Use exact data for which θ̂ = 0 instead, with the estimate
moved to 0.01 to mimic a fit that stopped early.
The objectives of the conditional optimizations in the θ and
variance-component profiles did not catch a `PosDefException` when the
optimizer moved into a region without enough shrinkage, so profiling
aborted (e.g. for the oxide model with `(1 + Source | Lot & Wafer)` under
some numerical conditions). Return `optsum.finitial` instead, as the
objective used for fitting does, and restore the original `finitial`
before profiling θ, since the warm-started refits in the σ profile
overwrite it.
@palday
palday requested a review from dmbates October 1, 2026 19:10
@dmbates

dmbates commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Do you know what is happening with the test failure on nightly?

@palday

palday commented Oct 1, 2026

Copy link
Copy Markdown
Member Author

Do you know what is happening with the test failure on nightly?

Not yet, but I'm working on it right now 😉

palday and others added 9 commits October 2, 2026 13:32
- profileσs!: skip forward/reverse splines that cannot be interpolated
  (e.g. ties at ζ = 0) with a warning, as profileθj! already does,
  instead of throwing a ZeroPivotException
- profileobj!/profilevc (NLopt and PRIMA): re-evaluate the objective at
  the minimizer so the model is not left at the last evaluation, which
  may be a failed factorization
- profileθj!: limit the initial upward step when the slope at the
  estimate is near zero

Fixes flaky oxide profile test on Julia nightly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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.

2 participants