torch_openreml.methods.Marginal¶
- class torch_openreml.methods.Marginal(trace_approx=False, subspace_fraction=0.01, exact_score_threshold=10.0)[source]¶
Bases:
objectMarginal REML score and AI for a supplied \(\symbf{V}\).
ai_step()is the model-aware entry point. It extracts \(\symbf{V}\) and its derivatives from the model, reuses a closed-form inverse when available, and otherwise applies the residual jitter rule.ai_step_from_tensors()is the stateless tensor-level entry point. It takes the marginal covariance \(\symbf{V}\) and its derivatives directly and dispatches to the no-inverse or with-inverse kernel. The no-inverse kernel forms \(\symbf{V}\) through Cholesky solves and never materialises \(\symbf{V}^{-1}\); the with-inverse kernel reuses a supplied \(\symbf{V}^{-1}\) and forms \(\symbf{P}\) explicitly.Configure the marginal method.
- Parameters:
trace_approx –
Falsefor exact traces,Trueto always estimate them, or"auto"to start with the estimate for large problems and switch to exact traces once the previous score norm falls belowexact_score_threshold.subspace_fraction – Probe-subspace fraction for Hutch++.
exact_score_threshold – Score-norm threshold below which
"auto"switches to exact traces.
- Raises:
ValueError – If an option is outside its valid range.
Methods
ai_step(model, y, x, free_params[, ...])Evaluate one marginal AI step for
model.ai_step_from_tensors(x, y, v, dv[, v_inv, ...])Dispatch one marginal REML score and AI step.
loglik(model, y, x, free_params)Evaluate the restricted log-likelihood for
model.loglik_from_tensors(x, y, v[, v_inv])Evaluate the marginal restricted log-likelihood from tensors.
preprocess_input(model, y, x, free_params[, ...])Prepare \(\symbf{V}\) and its derivatives for
model.reset()Reset the score history used by
trace_approx='auto'.Attributes
Minimum
nfortrace_approx="auto"to start with the stochastic trace estimate.- MIN_N_FOR_TRACE = 100¶
Minimum
nfortrace_approx="auto"to start with the stochastic trace estimate. Below this size exact traces are cheaper and more stable.
- loglik(model, y, x, free_params)[source]¶
Evaluate the restricted log-likelihood for
model.This evaluates
\[\ell = -\frac{1}{2}\left( \log|\symbf{V}| + \log|\symbf{X}^\top\symbf{V}^{-1}\symbf{X}| + \symbf{y}^\top\symbf{P}\symbf{y} \right),\]without forming the full projection matrix \(\symbf{P}\).
- Parameters:
model (MixedModelREML) – Model supplying \(\symbf{V}\).
y (torch.Tensor) – Response vector of shape
(n,).x (torch.Tensor) – Fixed-effect design matrix of shape
(n, p).free_params (torch.Tensor) – Free parameters of the model.
- Returns:
Scalar restricted log-likelihood.
- Return type:
torch.Tensor
- Raises:
ValueError – If
modelisNone.
- loglik_from_tensors(x, y, v, v_inv=None)[source]¶
Evaluate the marginal restricted log-likelihood from tensors.
- Parameters:
x – Fixed-effect design matrix of shape
(n, p).y – Response vector of shape
(n,).v – Marginal covariance matrix of shape
(n, n).v_inv – Optional precomputed inverse of
v. When supplied it isfactorisation. (used instead of forming V^{-1} from a Cholesky)
- Returns:
Scalar restricted log-likelihood.
- Return type:
torch.Tensor
- preprocess_input(model, y, x, free_params, grad=True)[source]¶
Prepare \(\symbf{V}\) and its derivatives for
model.- Parameters:
model (MixedModelREML) – Model supplying \(\symbf{V}\).
y (torch.Tensor) – Response vector of shape
(n,).x (torch.Tensor) – Fixed-effect design matrix of shape
(n, p).free_params (torch.Tensor) – Free parameters of the model.
grad (bool, optional) – Whether to compute
dv. Set toFalsefor loglik-only evaluation. Default:True.
- Returns:
Prepared tensors with keys
x,y,vandv_inv.v_invisNonewhen the model has no closed-form inverse; in that casevalready includes the1e-6 Ijitter. The derivative keydvis included only whengradisTrue.- Return type:
dict
- Raises:
ValueError – If
modelisNone.
- ai_step(model, y, x, free_params, require_loglik=True)[source]¶
Evaluate one marginal AI step for
model.The score and AI matrix are
\[s_k = \frac{1}{2}\left[ \symbf{q}_k^\top\symbf{P}\symbf{y} - \operatorname{tr} \left(\symbf{P}\dot{\symbf{V}}_k\right) \right], \qquad \symbf{I}_{kl} = \frac{1}{2}\symbf{q}_k^\top\symbf{P}\symbf{q}_l,\]with \(\symbf{q}_k = \dot{\symbf{V}}_k\symbf{P}\symbf{y}\).
trace_approxis resolved here:Truealways uses the stochastic trace estimate;Falsealways uses the exact trace;"auto"starts exact for small problems or after the previous score norm fell belowexact_score_threshold, and otherwise uses the estimate.
- Parameters:
model (MixedModelREML) – Model supplying \(\symbf{V}\).
y (torch.Tensor) – Response vector of shape
(n,).x (torch.Tensor) – Fixed-effect design matrix of shape
(n, p).free_params (torch.Tensor) – Free parameters of the model.
require_loglik (bool, optional) – Whether to evaluate the REML log-likelihood. Default:
True.
- Returns:
(score, ai, loglik).loglikistorch.nanwhenrequire_loglikisFalse.- Return type:
tuple
- Raises:
AttributeError – If
modelisNone. This is the error raised bypreprocess_inputwhen it dereferencesmodel.V; it is documented rather than converted so the low-level failure mode is explicit.
- ai_step_from_tensors(x, y, v, dv, v_inv=None, require_loglik=True, trace_approx=False, subspace_fraction=0.01)[source]¶
Dispatch one marginal REML score and AI step.
If
v_invisNonethis delegates to_ai_step_from_tensors_no_inverse(), which factorsvand avoids forming \(\symbf{V}^{-1}\). Otherwise it delegates to_ai_step_from_tensors_with_inverse(), which reuses the supplied inverse and forms \(\symbf{P}\) explicitly. The two branches use different stochastic trace estimators, so their approximate scores differ slightly; their exact scores agree.- Parameters:
x – Fixed-effect design matrix of shape
(n, p).y – Response vector of shape
(n,).v – Marginal covariance matrix of shape
(n, n).dv – Derivatives of
vwith shape(k, n, n). The first dimension is the parameter dimension.v_inv – Optional precomputed inverse of
v. IfNone, the no-inverse branch factorsvand uses Cholesky solves. A supplied value selects the with-inverse branch.require_loglik – If
True, return the restricted log-likelihood. IfFalse, returntorch.nanand skip the log-determinant calculations.trace_approx – If
True, estimate the trace term of the score with Hutch++. The AI matrix and log-likelihood remain exact. IfFalse, evaluate the trace exactly.subspace_fraction – Fraction of the
nobservations used as the probe-subspace dimension in the stochastic trace estimate. Each of the two probe matrices holdsint(n * subspace_fraction) + 1vectors. Must lie in[0, 1]; only used whentrace_approxisTrue. Default:0.01.
- Raises:
ValueError – If
dvhas a zero-length parameter dimension, or ifsubspace_fractionis outside[0, 1].- Returns:
(score, ai, loglik), wherescorehas shape(k,),aihas shape(k, k), andloglikis a scalar tensor, ortorch.nanwhenrequire_loglikisFalse.- Return type:
tuple