torch_openreml.methods.Marginal

class torch_openreml.methods.Marginal(trace_approx=False, subspace_fraction=0.01, exact_score_threshold=10.0)[source]

Bases: object

Marginal 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 – False for exact traces, True to always estimate them, or "auto" to start with the estimate for large problems and switch to exact traces once the previous score norm falls below exact_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

MIN_N_FOR_TRACE

Minimum n for trace_approx="auto" to start with the stochastic trace estimate.

MIN_N_FOR_TRACE = 100

Minimum n for trace_approx="auto" to start with the stochastic trace estimate. Below this size exact traces are cheaper and more stable.

reset()[source]

Reset the score history used by trace_approx='auto'.

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 model is None.

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 is

  • factorisation. (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 to False for loglik-only evaluation. Default: True.

Returns:

Prepared tensors with keys x, y, v and v_inv. v_inv is None when the model has no closed-form inverse; in that case v already includes the 1e-6 I jitter. The derivative key dv is included only when grad is True.

Return type:

dict

Raises:

ValueError – If model is None.

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_approx is resolved here:

  • True always uses the stochastic trace estimate;

  • False always uses the exact trace;

  • "auto" starts exact for small problems or after the previous score norm fell below exact_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). loglik is torch.nan when require_loglik is False.

Return type:

tuple

Raises:

AttributeError – If model is None. This is the error raised by preprocess_input when it dereferences model.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_inv is None this delegates to _ai_step_from_tensors_no_inverse(), which factors v and 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 v with shape (k, n, n). The first dimension is the parameter dimension.

  • v_inv – Optional precomputed inverse of v. If None, the no-inverse branch factors v and uses Cholesky solves. A supplied value selects the with-inverse branch.

  • require_loglik – If True, return the restricted log-likelihood. If False, return torch.nan and 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. If False, evaluate the trace exactly.

  • subspace_fraction – Fraction of the n observations used as the probe-subspace dimension in the stochastic trace estimate. Each of the two probe matrices holds int(n * subspace_fraction) + 1 vectors. Must lie in [0, 1]; only used when trace_approx is True. Default: 0.01.

Raises:

ValueError – If dv has a zero-length parameter dimension, or if subspace_fraction is outside [0, 1].

Returns:

(score, ai, loglik), where score has shape (k,), ai has shape (k, k), and loglik is a scalar tensor, or torch.nan when require_loglik is False.

Return type:

tuple