yde/ytrans Extension: Implementation
NotesThis document is knowledge memory for future development of
rms::orm’s Y-dependent-effects
(yde/ytrans, i.e. non-proportional-odds)
extension, written for a future session of Claude or Claude Code picking
up this work. It covers the numerical/code side — architecture,
what was tried and rejected, a bug history with enough detail to avoid
re-discovering the same failure modes, and what remains unsolved.
Companion reading: orm-yde-design.md (the
pre-implementation design document — read first; this document records
what actually happened against that plan, including where reality
diverged from it), orm-random-effects-implementation.md and
orm-random-effects-methodology.md (the
cluster()/mre work this extension builds on
and interacts with), and orm_accuracy.md §3 (the
cancellation-avoidance requirement this extension’s Fortran code must
satisfy).
Key files: orm.fit.r (Stage 1:
Z/ytrans validation,
qyde/myde/ qm computation,
ytrans='all' construction, dispatch into
ormfit()/ ormrfit()), orm.s
(yde formula handling,
zDesign/zassign/
zsformula/z storage on the fit object,
anova’s own $assign extension for joint
beta+tau Wald tests), orm.rfit.r (Stage 2: the
random-effects fitting workhorse extended for yde —
clusterModeFind, agqStep,
ormrfit, sparseInfoMatrix,
sparseMissingInfo), predict.lrm.s (new
function ormPredictYde()), Predict.s,
Xcontrast.r, summary.rms.s,
anova.rms.s, nomogram.s,
robcov.s, residuals.lrm.s,
bootcov.s, quickRefit.r (all extended to
recognize a yde-fitted orm object). Compiled
routines ormll.f90 (extended with
qm/Z1/Z2/tau/
hc/hac/hbc),
ormeta.f90 (extended with
qm/Z1/Z2/tau), and
init.c (registration counts: ormll 36→43 args,
ormeta 20→24 args) — treat any copy of these as
potentially stale, same caveat as the random-effects document;
always rebuild and re-check init.c’s own registration table
against the actual Fortran signatures before trusting argument counts
from memory.
orm()/orm.fit()
|-- Z/ytrans validation (qyde = ncol(Z); myde/qm computed once ylevels
| known; ytrans='all' substituted here if requested)
|
|-- Stage 1: ormfit() [non-clustered] -- extended, not replaced
| ormll.f90: qm>0 branch computes e1=Z1%*%tau, e2=Z2%*%tau,
| passes them to ormatoms SEPARATELY (never pre-summed into lp --
| see orm_accuracy.md 3.1 and Sec. 5 below), accumulates new
| hc (tau-tau), hac (alpha-tau), hbc (beta-tau) Hessian blocks
| alongside the existing ha/hb/hab. Gated behind qm>0 so a
| qm==0 fit runs the IDENTICAL ormatoms call as before (verified
| bit-identical).
|
'-- Stage 2 (this document's main focus): ormrfit() [clustered/mix_re]
|-- Zexp1/Zexp2 (n x qm): per-observation yde design at the
| "p1"/"p2" intercepts, built once per fit (mirrors
| ormfit()'s own construction)
|-- clusterModeFind(): qm/Z1/Z2/tau threaded into its internal
| ormeta call -- e1/e2 now come from Z1/Z2/tau directly
| inside ormeta.f90 (never from lp2-lp1), no h11/h12/h22
| split needed HERE since a random intercept shifts eta
| identically regardless of e1 != e2 (see Sec. 3)
|-- agqStep(): qm/Z1/Z2/tau threaded into BOTH its log-density
| loop (ormeta, for rho_w) and its score/Hessian loop
| (ormll, which already has the Stage-1 qm/Z1/Z2/tau
| extension) -- combines accum_hb/accum_hbc/accum_hc and
| accum_hab/accum_hac into one (p_star+qm)-wide block
| before returning, mirroring orm.fit.r's own rfort()
|-- onestep(): theta_full's layout gets ytau appended LAST
| (after whichever of log(sigma)/sigma1,sigma2 applies --
| see Sec. 4's bug for the asymmetry this requires)
|-- missing-information correction (Sec. 6): added to
| agqStep's own Newton-step Hessian, gated qm>0, confirmed
| necessary but NOT sufficient for cluster()+mix_re()+yde
| jointly -- see Sec. 7 for why that combination is
| documented as a known hard case instead of fixed
'-- sparseInfoMatrix()/sparseMissingInfo(): extended with
qm/Z1/Z2/tau, p_star widened by qm, xname reordered
(Sec. 4)
Downstream consumers (predict, Predict,
Xcontrast, summary, anova,
nomogram, bootcov, robcov) are
extended separately — see Sec. 2.
New function: ormPredictYde() (in
predict.lrm.s) — the MLE analog of
rmsb::bormPredictYde(). Dispatched from
predict.orm() whenever object$qyde>0 and
type %in% c('lp','x'); all other types/cases still go
through predict.lrm() unchanged (no modification to
lrm() itself, per explicit instruction). Builds
X and Z via
predictrms(...,type='x') and
predictrms(...,type='x',second=TRUE) respectively — reusing
predictrms()’s existing second=TRUE mechanism
(built originally for blrm()’s ppo, keyed off
fit$zDesign/zassign/zsformula by
exactly those names) rather than inventing a parallel Design()-matching
path. Computes Zexp via
outer(Z[i,], ytransmat[rowidx[i],]) and
lp = alpha[rowidx] + X%*%beta + Zexp%*%tau. Delta-method
SE/CI via infoMxop(object$info.matrix, i=idxset) on a
reduced index set (unique touched alpha rows + all beta+tau), avoiding
inverting the full, possibly huge, k x k matrix. Explicit (mostly
pass-through) formals fun, funint,
codes, posterior.summary, cint
exist ONLY to keep these names out of ..., which would
otherwise leak into predictrms()’s
model.frame() call and be misread as extra model-frame
variables (a real bug, see Sec. 5).
Changed functions (all additive/gated, no behavior
change when qyde==0):
orm.fit.r: Z/ytrans
validation; ytrans='all' construction (discrete Y,
k<=50, no censoring, produces a k-2 column 0/1 indicator, column
names = the Y levels it corresponds to); explicit guard
p==0 -> error (“a yde-only model is not supported” —
tried and reverted supporting this case, see Sec. 4); stores
ytransmat on the fit object (needed by
ormPredictYde() since re-calling ytrans() for
'all' on out-of-sample Y would silently give an all-zero
row).orm.s: stores
zDesign/zassign/zsformula/z
(raw Z matrix, guarded by x && qyde>0, mirroring
f$x) on the fit object; extends ass (the
$assign list) so a yde variable’s tau columns
are tested JOINTLY with its ordinary effect in Wald tests
(anova) — using zassign’s per-yde-variable
column positions and the column-major tau-flattening offset
outer(zpos, (0:(myde-1))*qyde, '+').Predict.s/Xcontrast.r:
isormyde <- isorm && qyde>0 detection,
routing type='x'/'lp' through
predict() (reaching ormPredictYde()) instead
of predictrms() directly.summary.rms.s: same detection; routes through
predict(object,d, type='x',ycut=ycut) instead of
predictrms(object,d,type='x') — fixes a real bug where a
user-specified ycut= was silently ignored for
yde-fitted orm objects (Sec. 5).anova.rms.s: test='LR' explicitly disabled
for qyde>0 with an informative error (a real,
silently-wrong bug was found and fixed by disabling rather than patching
— Sec. 5); Wald tests (the default) work via orm.s’s
$assign extension above.nomogram.s: explicit, informative error for
qyde>0 (a yde effect has no single
nomogram-representable contribution per predictor, same rationale as
blrm’s own ppo).robcov.s/residuals.lrm.s: require
mscore=TRUE at fit time for a yde-fitted
object (the X-only score-residual fallback, used when
mscore wasn’t requested, doesn’t know about
tau; the mscore=TRUE path already did, needing
only this guard, not new derivation).bootcov.s/quickRefit.r:
Z/ytrans threaded through the resampling loops
via do.call() (not direct fitter(...) calls —
seeds a regression for non-orm fitters otherwise, Sec.
5).ormll.f90’s own pre-existing header comments (written
before this extension, during the random-effects work) already
anticipated the mechanism almost exactly — see
orm-yde-design.md a.1 for the literal quotes.
ormatoms already had optional
e1/e2 arguments (default 0);
ormeta.f90’s header already stated the caller should pass
lp/e1/e2 separately rather than
pre-summed lp1/lp2. Stage 1’s job was to wire
this up, not invent it — confirmed true: the Hessian block derivation
(orm-yde-design.md a.3) and the numerical toy-example check
(gradient FD diff 1e-7, Hessian FD diff 8e-5 shrinking with step size,
alpha-alpha block exactly 0 off the tri-band with tau != 0) both came
out clean on the first principled derivation, no sign bugs surviving to
the Fortran implementation.
The non-negotiable accuracy requirement
(orm_accuracy.md §3.1, reiterated in
orm-yde-design.md a.1’): e1 = Z1 %*% tau and
e2 = Z2 %*% tau must reach ormatoms as
separate arrays, never pre-summed into lp on the R or
Fortran side. Measured cost of getting this wrong: ~1e-10 relative error
in the cell probability d if pre-summed, vs. ~1e-15 if kept
separate — a ~1e5x amplification, because lp + e1 rounds to
ulp(lp) regardless of how small and distinct
e1 actually is. Both ormll.f90 (Stage 1) and
ormeta.f90 (Stage 2, Sec. 3 below) honor this by
construction: e1/e2 are computed from
Z1/Z2/tau inside the
Fortran routine and passed to ormatoms as named arguments,
never added to lp/offset beforehand at the R
level.
Fortran signature changes (gated behind
qm>0/qm==0 so a no-yde fit
runs the byte-identical ormatoms call as before this
extension existed):
ormll.f90: qm, Z1, Z2, tau inserted after
beta; hc (qm x qm), hac (k x qm),
hbc (p x qm) inserted after hab. 36 -> 43
args.ormeta.f90 (Stage 2 only — needed once a random
intercept and yde coexist): qm, Z1, Z2, tau
inserted after nb. 20 -> 24 args. Internal dispatch:
qm>0 computes e1yde=matmul(Z1,tau),
e2yde=matmul(Z2,tau) and calls ormatoms with
those as e1/e2, bypassing the pre-existing
e2=lp2-lp1 path entirely (which would reintroduce the
cancellation problem orm_accuracy.md measures).
ormeta’s own g/h outputs (the
combined “common shift” quantities the random intercept’s own
mode-finding Newton step uses) remain exactly correct even with
yde active and no h11/h12/h22 split needed there —
confirmed by first-principles derivation: a random intercept
u shifts x1 and x2 identically
(d(x1)/du = d(x2)/du = 1) regardless of whether
e1 != e2, so only getting e1/e2
themselves right (for accuracy) is new; the mode-finding math itself
needs no rederivation.init.c: registration counts updated to match
(36->43, 20->24); verified directly
(grep -o "void \*" | wc -l) rather than trusted from
memory, since an out-of-sync registration count is a silent, dangerous
failure mode (wrong-argument-count crashes, or worse, silent
misalignment if counts happen to coincidentally match).ytransmat’s column-major flattening convention
(q varies fastest within each ytrans-column
block) is used consistently everywhere tau is indexed by a
combined (q,m) position — orm.s’s
anova extension, ormPredictYde()’s
Zexp construction, and agqStep’s
p_star+qm block all rely on this same convention; it
matches rmsb::borm()’s own
expandZ()/Zexp construction exactly (confirmed
deliberately, for cross-package naming/ordering consistency per
orm-yde-design.md a.2).
Extending ormeta.f90’s Fortran signature broke
every existing cluster() fit (no yde involved
at all). Symptom:
Incorrect number of arguments (20), expecting 24 for 'ormeta'
on a plain orm(y~x+cluster(cl)) fit, immediately after the
signature extension (Sec. 3) was added to the Fortran source. Cause: 4
R-level .Fortran(F_ormeta,...) call sites in
orm.rfit.r (clusterModeFind’s internal
eval_ormeta(), agqStep’s log-density loop,
sparseMissingInfo’s loop, and the step-halving
surrogate() closure) were not yet updated to pass the new
arguments. Same pattern hit agqStep’s one
ormll call site after ormll.f90’s own Stage-1
extension (36->43 args). Fix: all 5 call sites updated with
qm=0L, Z1=matrix(0e0,n,0), Z2=matrix(0e0,n,0), tau=numeric(0)
placeholders (reproducing prior behavior exactly), THEN, incrementally,
each wired to pass the real
qm/Zexp1/Zexp2/ytau
values as the actual Stage-2 integration proceeded. Verified via a
stash-based bit-identical comparison (max|coef diff| / max|sigma diff| /
max|deviance diff| / max|u diff| all exactly 0) at each checkpoint
before continuing.
ytau’s extraction from theta_full
used one index formula for both the mre-active and
mre-inactive cases — silently wrong for the
mre-inactive one. Symptom:
cluster()+yde (no mix_re) failed to converge —
“step size reduced below minstepsize … without improving the objective”
at the very first outer iteration, with tau’s own gradient
exploding to ~100x its starting value after just one Newton step, while
alpha/beta stayed well-behaved. Cause: theta_full’s layout
differs by case — mre active:
[alpha,beta,log(sigma1),sigma2,ytau] (ytau
after the two scale parameters, matching agqStep’s
own p_star which already includes them); mre
inactive: [alpha,beta,ytau,log(sigma)] (ytau
before log(sigma), which is appended externally by
sparseInfoMatrix() after everything agqStep
itself computes). A single formula,
theta_full[(k+p+p_wt+1):(k+p+p_wt+qm)], was used for both
cases — only correct for the mre-active one. For
mre inactive this silently grabbed
log(sigma)’s own slot and fed it to
ormeta/ormll as if it were tau.
Fix: branch explicitly on use_mre at each of the 3
extraction sites (onestep()’s two extractions of
ytau_t/ytau; sigmaObjective’s
call site already had the branch right). Caught and fixed by direct
reasoning about theta_full’s construction (not by further
trial-and-error) once the symptom’s pattern (tau specifically, not
alpha/beta) pointed at an indexing issue in exactly the code that
differs between the two branches — confirmed by immediate convergence
after the fix, no other changes needed for this specific case.
A yde-only model (p==0, all effects in
yde) was briefly supported, then explicitly
reverted. Not a bug per se — an explicit scope correction.
Frank’s direct instruction: “No need to implement the case where there
are no predictors in the main part of the model but yde is specified.”
Reverted orm.fit.r’s if(p>0||qyde>0)
back to if(p>0), added an explicit stop()
guard instead
("yde requires at least one predictor in the main model formula; a yde-only model is not supported"),
simplified the stats block’s conditional back to if(p==0)
from if(p==0 && qyde==0). Kept
model.df <- p+qm (still correct regardless of this
reversion).
predict()/Predict() silently wrong
for yde-fitted orm objects. Cause:
predictrms()/Design() had no knowledge of
yde’s separate Z design — a plain
predictrms(object,newdata,type='x') call simply never built
the tau-related columns, so predictions omitted the Y-dependent effect
entirely with no error or warning. Fix: the ormPredictYde()
architecture (Sec. 2), reusing predictrms()’s existing
second=TRUE mechanism rather than reinventing
Design()-matching logic. Verified against hand computation to 7 decimal
places.
fun=NULL/funint/codes/posterior.summary/cint
leaking into predictrms()’s own model.frame()
call. Symptom:
Error in eval(extras, data, env): object 'fun' not found.
Cause: model.frame.default’s own ...-based
“extras” mechanism treats any unrecognized named argument as an
extra variable to evaluate in the data environment — any caller passing
fun= through ... without
ormPredictYde() consuming it first got silently forwarded
into that model-frame evaluation. Fix: added these as explicit (mostly
pass-through, interface-compatibility) formals on
ormPredictYde(), so they stop at that function’s own
argument-matching rather than falling into its ... and
being forwarded further.
Predict() crashing on a yde-fitted
orm object with
$ operator is invalid for atomic vectors. Cause:
Predict.s’s own code unconditionally does
xx$lower/xx$upper when
conf.int>0 (the default), assuming the list-style return
blrm()/borm() already provide;
ormPredictYde() originally returned a plain numeric vector.
Fix: implemented full delta-method SE/CI support in
ormPredictYde() (Sec. 2), returning
list(linear.predictors=lp, se.fit=se, lower=..., upper=...)
when cint is requested — matching the Bayesian-model return
convention Predict.s already assumes.
anova(..., test='LR') silently wrong for a
yde-fitted orm object. The most
severe bug found in this entire project. Symptom: the reported
x2 (chi-square for the predictor’s own effect) and
TOTAL rows showed identical chi-square values
despite having different degrees of freedom — a result that cannot be
correct if the LR refit is doing anything at all. Cause:
X[,-idx,drop=FALSE] (dropping columns to fit the reduced
model) used idx containing global coefficient
positions (offset by k, the number of intercepts) — not
valid column indices into object$x, which only has
p columns (no intercepts). R’s negative-indexing silently
ignores out-of-range negative indices rather than erroring, so this
dropped nothing, refitting the identical full model and
reporting it as the “reduced” one. Fix: rather than attempt a deeper fix
to the LR-refit machinery (which would need qyde-aware
column remapping throughout), added an explicit, informative
stop() guard disabling test='LR' entirely for
qyde>0 objects, directing the user to the default
test='Chisq'/'F' (Wald) instead — which works
correctly via orm.s’s own $assign extension
(Sec. 2). A targeted guard was chosen over a deeper fix given the
severity (silently wrong, not just unimplemented) and the availability
of a correct alternative test.
bootcov() regressed for lrm fits
(not orm) after a first attempt at wiring Z=
through the resampling loop. Symptom: 100% fit failures in a
bootcov() call on a plain lrm fit (no
orm, no yde involved at all), confirmed via a
stash-based before/after comparison to be a genuine regression, not
pre-existing. Cause: bootcov.s has two resampling loops,
each calling
fitter(X[j,,drop=FALSE], Y[j,,drop=FALSE], ...) directly.
Adding Z=Z[j,,drop=FALSE] unconditionally to that
call meant a non-orm fitter’s own closure (which forwards
its ... straight into lrm.fit(), which has no
Z parameter) received Z= and errored “unused
argument (Z = NULL)” — silently swallowed by bootcov()’s
own tryCatch(...,error=function(...) list(fail=TRUE)), so
the only visible symptom was a 100% failure rate with no informative
message. Fix: switched both call sites to
do.call(fitter, c(fitargs, list(...))) with
fitargs$Z added only when
nfit=='orm' && length(Z), so non-orm
fitters never see a Z= argument at all.
Problem investigated:
cluster()+mix_re()+yde together (all three) failed to
converge, systematically across every seed tried (5/5), with
sigma2’s own gradient specifically exploding (60 ->
150+) across outer iterations while
alpha/beta/log(sigma1)/tau all stayed
well-behaved. cluster()+yde alone and
cluster()+mix_re() alone both converged cleanly
(bit-identical to baseline for the latter).
Root cause, confirmed not hypothesized:
agqStep()’s Newton-step Hessian
(hb/hab) is, and always has been, only the
conditional- expectation term of the true marginal Hessian —
E[d2(complete-data ell)/dtheta2 | y], accumulated by
summing ormll’s per-AGQ-node Hessian, AGQ-node-weighted by
rho_w. Louis (1982)’s identity says the true
marginal Hessian also needs a second term added:
Var[d(complete-data ell)/dtheta | y] (the AGQ-weighted
variance, not just the mean, of the per-cluster complete-data
score under the posterior over the random effect) — this term is
computed, but only once, at the very end, by
sparseMissingInfo()/sparseInfoMatrix(), for
the final reported information matrix/SEs. It was never fed back into
the iteration itself.
Measured directly (not just asserted) by comparing against a true
reference: re-running clusterModeFind() at perturbed
parameter values (not holding the cluster mode fixed, as the Newton step
implicitly does) and finite-differencing the resulting AGQ
log-likelihood gives the true marginal curvature. At a
representative point in a failing fit:
| quantity | agqStep’s naive Hessian |
true marginal (FD, mode re-found) |
|---|---|---|
d(loglik)/d(sigma2) |
137.3138 | 137.3137 |
d2(loglik)/d(sigma2)^2 |
-486.85 | -308.66 |
Gradient matches to 6 significant figures (guaranteed by Louis’s identity/the envelope theorem regardless of the Hessian gap — confirmed, not assumed). The Hessian is off by ~58% — large enough that the Newton direction it implies is a poor local model of the true objective.
Fix implemented and confirmed mathematically exact, but not
sufficient alone (see Sec. 7): added the same
missing-information correction sparseMissingInfo() already
computes, into agqStep()’s own Newton-step Hessian, but: -
Gated behind qm>0 only — exactly preserves bit-identical
behavior (confirmed: 0 difference in coef/sigma/deviance) for every path
that worked before this extension (plain cluster(),
cluster()+mix_re(), with or without yde=0). -
Restricted to the (p_star+qm) x (p_star+qm) block
(beta/sigma1/sigma2/ytau)
only — not the ha/hab (alpha) blocks,
avoiding sparseMissingInfo()’s expensive per-cluster
“active alpha” bookkeeping (tracking, for each cluster, which of
potentially many thousand alphas it touches) entirely. Justified by the
observed failure pattern (alpha’s own gradient trajectory stayed
well-behaved throughout the failing fit — the instability is isolated to
the beta/sigma/tau block) and confirmed after the fact: adding the
correction brought the corrected Hessian to -308.6585 — matching the
true marginal value (-308.6566) to within the finite-difference step
size’s own precision, i.e. essentially exact. - Mechanically: widened
agqStep()’s existing first loop (which already calls
ormeta once per AGQ node for rho_w) from
what=1L (logd only) to what=3L (also
g/s1/s2) ONLY when
qm>0 — a by-product of a call already being made every
iteration, not a new O(n*nAGQ) pass. Then, per cluster, built a small
nAGQ x ptot matrix (mirroring
sparseMissingInfo()’s own construction, minus its
active-alpha columns) and AGQ-weighted-crossprod’d it into a dense
ptot x ptot accumulator (ptot typically
<20, so this crossprod is cheap regardless of cluster size or
nAGQ). - Cost: no new O(n*nAGQ) Fortran pass
(rides the existing rho_w loop); adds
O(n*nAGQ*ptot) for the small per-cluster matrices and
O(nc*nAGQ*ptot^2) for the crossprods — both the same order
as, or smaller than, the per-node score/Hessian work
agqStep already does every iteration. Zero cost at all when
qm==0 (the overwhelming majority of fits).
Also checked: the correction’s magnitude in the
already-working cluster()+yde (no mix_re) case
— small (~4% relative to the naive Hessian, matching exactly the
FD-vs-analytic mismatch observed and previously attributed, incorrectly,
to ordinary finite-difference truncation error before this
investigation). Confirmed it does not disrupt that already-converging
case (still bit-identical-equivalent in practice — the correction there
is a small, harmless accuracy improvement, not a behavior change large
enough to alter convergence).
cluster()+mix_re()+yde: documented hard case, not
fixedDespite the missing-information correction being confirmed
mathematically exact (Sec. 6), it was not sufficient to
make cluster()+mix_re()+yde converge reliably. Two further
hypotheses were investigated and both found wanting by direct evidence —
recorded here so they are not re-attempted blindly in a future session
without new information.
Hypothesis: sigma2’s fixed starting value
(exactly 0, required for the mix_re-alone case — see
orm-random-effects-implementation.md Sec. 2) sits in a bad
region once yde is also active; nudge it off 0.
Tested directly: sigma2 <- 0.3*sigma.init when
qm>0. Result: worse, not better — 0/5 test
seeds converged (vs. 2/5 at the unmodified sigma2 <- 0).
Reverted immediately. Consistent with the existing, documented warning
in orm-random-effects-implementation.md Sec. 2 that a
nonzero starting value for sigma2 reintroduces a persistent
sign-bias problem; this was not re-derived from scratch here, just
re-confirmed empirically in the yde-active regime
specifically.
Root cause actually found, via scanning sigma2
from 0 to 0.84 (with the cluster mode re-found at each point — the TRUE
profile, not the Newton surrogate) at the exact point a real fit starts
from: the log-likelihood profile in sigma2,
holding other parameters at their current values, is genuinely
locally convex (Hessian positive, not
negative) near sigma2=0 once yde’s
tau is informative enough to compete with
sigma2 in explaining cluster-level variation —
sigma2=0.00 grad= 60.8 hb33=+762.8 <- starting point, convex
sigma2=0.05 grad= 96.9 hb33=+668.7
sigma2=0.10 grad=126.7 hb33=+518.5
sigma2=0.20 grad=159.8 hb33=+136.9
sigma2=0.30 grad=156.5 hb33=-176.8 <- sign flips here
sigma2=0.40 grad=130.5 hb33=-315.0
— confirmed via the SAME missing-information-corrected Hessian from
Sec. 6 (which matches this true profile essentially exactly at every
point checked, including this one: corrected +762.837 vs. true-FD
+762.830). A raw Newton step at a locally convex point moves toward the
stationary point of a local minimum, not maximum — a direction
no amount of step-halving can fix, since halving a non-ascent direction
is still non-ascent at every smaller step size. This exactly explains
the observed symptom: repeated halving down to minstepsize
with zero improvement, at the very first outer iteration.
Hypothesis: a Levenberg-Marquardt-style trust-region
escalation — when step-halving exhausts minstepsize without
improving the objective, escalate ridge damping (the existing
lambda mechanism, currently triggered only by an outright
singular solve()) and retry, rather than failing
immediately. Implemented and tested (wrapping
onestep()’s existing delta-solve + step-halving logic in an
additional outer retry loop, escalating the same lambda
ladder already used for singular-Hessian recovery). Result:
partial improvement (3/5 seeds converged, up from 2/5) but
unsatisfying and ultimately reverted: where it did let
a fit “succeed,” the fit landed on a different, almost certainly
spurious local optimum —
sigma1/sigma2 collapsed to ~1e-14 to 1e-20
(i.e. effectively 0, turning the random effect off entirely) with
tau alone absorbing the cluster-level signal — rather than
the true, nonzero sigma1/sigma2 values. The
remaining 2/5 seeds still exhausted the ridge-damping ladder with no
improving step found at all. A fit that “succeeds” at a visibly wrong
answer is worse than one that fails cleanly: it would not be flagged to
the user without them separately checking
sigma1/sigma2 after every such fit. Reverted
to the original onestep() control flow (no trust-region
escalation) — orm.rfit.r is unchanged from before this
investigation in that respect; only the missing-information correction
(Sec. 6) remains.
Final decision (Frank’s call, confirmed): treat this
specific three-way combination as a documented hard case rather than
attempt further numerical fixes. orm.fit() now issues a
one-time warn_once() warning (keyed
'orm.yde.mre') whenever both mre and
yde/ytrans are supplied together, describing
the failure mode (may fail to converge, or may converge to a degenerate
sigma1/sigma2 ~0 solution) and advising the
user to check sigma1/sigma2 after fitting
rather than assume convergence implies a valid fit. Documented in both
the Z/ytrans and mre roxygen
@param entries in orm.fit.r.
Why this looks like a genuine competing-local-optimum
problem, not (only) a numerical one: the degenerate
sigma1=sigma2~0 point found by the trust-region experiment
is itself a valid stationary point of the likelihood (with
tau alone explaining the cluster-level pattern) — not an
artifact of a broken Newton step. This is the same qualitative risk
flagged, for a different reason, in
orm-random-effects-implementation.md’s own open-items list
(“partial identifiability of (sigma1,sigma2) at small
nc”) — yde sharpens an existing
identifiability tension between the random-effect variance decomposition
and the fixed Y-dependent effect, rather than introducing an unrelated
new failure mode.
Worth preserving as a template for future changes to this code
(directly following orm-random-effects-implementation.md
Sec. 8’s own template):
qm==0/qyde==0 path, at every
checkpoint during Stage 2 development — including a full stash-based
(git stash/rebuild/compare/git stash pop/rebuild)
before/after comparison, not just an in-session re-run, specifically for
the cluster() and cluster()+mix_re() paths,
both before and after the missing-information correction was added.cluster()+mix_re()+yde
convexity finding: a single, isolated .Fortran(F_ormll,...)
call (no AGQ, no clustering, no
agqStep/clusterModeFind machinery at all) was
used to confirm the mix_re-pseudo-covariate/yde-tau cross-Hessian
formula (hbc) matches a brute-force finite difference of
that SAME single call’s own -2LL output exactly — ruling
out the Fortran accumulation itself as the source of the
later-discovered convexity problem before looking elsewhere.clusterModeFind() (re-finding the
cluster mode) at each perturbed point, not by trusting any of
agqStep’s own internally-consistent-but-potentially-wrong
outputs. This is what let the missing-information gap (Sec. 6) and the
separate convexity problem (Sec. 7) be told apart cleanly, rather than
conflated into one vague “doesn’t converge” finding.sigma2=0.38 for the missing-info correction;
sigma2=0 for the convexity scan), the identical check was
also run at qm=0 (no yde) or on the
already-working cluster()+yde (no mix_re)
case, to separate “this is a yde-specific problem” from
“this is how large these numbers always are under this methodology” —
caught, for example, that the ~4% FD-vs-analytic mismatch previously
seen in cluster()+yde testing was itself the SAME
missing-information term, just small enough there not to matter.sigma2 in {0, 0.05, ..., 0.84} sweep (Sec.
7) is what actually revealed the local-convexity structure; a
single-point Hessian/gradient check at sigma2=0 alone would
have shown “Hessian is positive” without the context of where the
function becomes concave again.sigma2 starting-value nudge
(Sec. 7) was deliberately tried, measured, and rejected on its own
evidence (0/5 seeds converged) before the larger trust-region
control-flow change was attempted — and that, in turn, was reverted on
its own evidence (the degenerate-optimum finding) rather than kept
merely because it was “mostly” working.R CMD check --as-cran run to
completion after every substantive round of changes, not deferred to the
end — caught one real, unrelated-but-introduced-this-session CRAN NOTE
(ormPredictYde’s use of tail() without
qualifying it, fixed with utils::tail()) early enough that
it didn’t accumulate with other issues.Unsolved: cluster()+mix_re()+yde
together (Sec. 7) — a warn_once() warning exists; no fix
exists. Candidate directions for a future session, none attempted here:
- A genuine trust-region method (not the ad hoc ridge-escalation tried
in Sec. 7) that rejects a step landing at a degenerate boundary
(sigma1/sigma2 near 0 when the pre-step values
were not) rather than accepting it as “converged” — would turn today’s
silent-wrong- answer risk into a clean failure at minimum, without
necessarily fixing convergence to the true optimum. -
Multiple-starting-point / restart strategies, explicitly informed by the
competing-local-optimum framing in Sec. 7 — if
sigma1=sigma2=0, tau=<data-determined> is a real,
nearby alternative mode, a second fit started from a
tau=0-biased or sigma-biased starting point
might reliably recover the non-degenerate mode when the unbiased
starting point doesn’t. - A direct, joint derivation of the profile
likelihood’s shape in (sigma1,sigma2,tau) jointly (not just
sigma2 alone, as scanned in Sec. 7) might reveal whether
the convex region’s width is itself predictable from the data
(e.g. from the relative scale of tau’s own non-clustered
MLE and mre’s own within-cluster variation) — which would
turn an ad hoc numerical nudge into a principled, data-driven one,
unlike the fixed-constant nudge rejected in Sec. 7.
ytrans beyond
m=1/'all': Stage 1/2 as implemented
support general ytrans (the Fortran/R machinery is
m-general throughout, not hardcoded to m=1),
but systematic testing concentrated on m=1 (ordinary
yde) and the 'all' special case
(m=k-2, discrete, uncensored Y only). A
borm()-style matrix-valued-tau recovery test
(per orm-yde-design.md Stage 3’s own test plan,
inst/tests/borm-yde.r §2 as the template) with
1<m<k-2 has not been run against orm’s
MLE specifically.
Large-k stress testing for
yde: orm-yde-design.md g’s own
verification plan calls for confirming, empirically (not just by
structural argument), that yde’s Schur-complement-style
infoMxop/sparseInfoMatrix extension doesn’t
touch the size/structure of the one segfault-prone path CLAUDE.md flags
(Matrix::solve on the sparse k x k intercept system,
observed to segfault at k~290,000 for probit/cloglog in the prior
random-effects work) — not yet run with yde active at that
scale.
anova(..., test='LR') for
qyde>0: disabled with an informative error
(Sec. 5) rather than fixed. A real fix would need
qyde-aware column remapping throughout the LR-refit
machinery (rebuilding a reduced model’s design matrix with the right
subset of both the original p columns AND the relevant
tau columns) — not attempted, flagged as a known gap rather
than silently wrong (which is what existed before the guard was
added).
nomogram() for qyde>0:
hard error, matching the random-effects document’s own recommendation
and (unlike that document’s open question) now actually consistent with
blrm()’s own ppo/cppo handling,
confirmed by direct comparison rather than left as an open question.
Interaction with the existing random-effects open
items (orm-random-effects-implementation.md Sec.
9’s four technical questions about yde +
cluster()/mre) — now partially answered by
this document: 1. “Every current call site sets
lp1=lp2=lp unconditionally.” Resolved for the
yde-active case: ormeta.f90‘s
qm>0 branch now computes e1/e2
from Z1/Z2/tau directly (Sec. 3),
rather than requiring lp1 != lp2 at the R level at all — a
cleaner resolution than literally passing different
lp1/lp2 would have been, and one that
preserves the cancellation-avoidance property
orm_accuracy.md requires. 2. “Does
clusterModeFind’s scalar g/h
accumulation still work?” Resolved: yes, unchanged — a random
intercept’s shift is common to both sides regardless of yde
(Sec. 3’s derivation), so no rederivation of the mode-finding formulas
was needed, only passing the right e1/e2
through for accuracy. 3. “Does agqStep’s
pseudo-covariate chain-rule logic generalize?” Resolved for the
Hessian’s shape (yes — yde’s tau is a separate
block from the sigma1/sigma2
pseudo-covariates, not folded into them, since yde’s
Z1 != Z2 in general while the pseudo-covariates’ own
“shared shift” trick requires Z1==Z2); resolved NEGATIVELY
for the values — the naive conditional-expectation Hessian this
machinery produces is insufficient once mix_re and
yde are both active (Sec. 6/7), the central finding of this
document. 4. “Does sparseMissingInfo’s Louis’s-identity
correction still apply?” Resolved: yes, in the sense that the SAME
correction mechanism (now also partially ported into
agqStep itself, Sec. 6) is what’s needed — but demonstrated
NOT sufficient by itself for the three-way combination (Sec. 7), the
open question this document leaves for future work.
ormrfit’s outer loop already used (unchanged
by this extension); referenced here only because Sec. 7’s rejected
trust-region experiment interacted with it (the outer SQUAREM
extrapolation operates generically on theta_full’s full
length, so needed no change itself when yde was added —
confirmed by inspection, not by a dedicated test, since the rejected
trust-region change was reverted before this interaction became
load-bearing).