torch_openreml.covariance.MarginalCovariance¶
- class torch_openreml.covariance.MarginalCovariance(*args, **kwargs)[source]¶
Bases:
OperatorMarginal covariance operator.
\[\symbf{V} = \symbf{R} + \symbf{Z}\symbf{G}\symbf{Z}^{\top}\]The operator has exactly three named operands:
Z: the incidence matrix, an \(n \times q\) tensor orMatrix;G: the random-effect covariance, a \(q \times q\)Matrixor fixed tensor;R: the residual covariance, an \(n \times n\)Matrixor fixed tensor.
Parameters are namespaced by these operand names. A parameter
sigma^2of a termgeninside a block-diagonalGis exposed asG/gen/sigma^2. IfZis itself parameterised, its parameters are exposed asZ/...and come beforeGandR, preserving the parameter order \([\\symbf{Z}, \\symbf{G}, \\symbf{R}]\).This is the operator used by
MixedModelREML. It is not a general sum: it enforces the design/covariance shapes and evaluates \(\\symbf{R} + \\symbf{Z}\\symbf{G}\\symbf{Z}^{\\top}\) directly.Initialize the marginal covariance.
- Parameters:
*args – Either exactly three positional operands
Z,GandR, or a single dictionary with keys"Z","G"and"R".**kwargs – The named operands
Z,GandR.
- Raises:
ValueError – If positional and keyword operands are mixed, or if the operands are not exactly
Z,GandR.TypeError – If an operand is not a
Matrixor tensor, or if no operand is aMatrix.
Example:
import torch from torch_openreml.covariance import DummyMatrix, DiagonalMatrix, ScalarMatrix, MarginalCovariance z = DummyMatrix(["a", "b", "c", "a"]) g = DiagonalMatrix(3) r = ScalarMatrix(4) op = MarginalCovariance(Z=z, G=g, R=r) op(torch.zeros(4))
tensor([[2., 0., 0., 1.], [0., 2., 0., 0.], [0., 0., 2., 0.], [1., 0., 0., 2.]])Methods
__call__([free_params])Evaluate \(\symbf{R} + \symbf{Z}\symbf{G}\symbf{Z}^{\top}\).
auto_grad([free_params])Compute the Jacobian of
build()with respect to free parameters using automatic differentiation.build_operands([free_params])Evaluate each operand at the current free parameters.
build_params([free_params, include_fixed, ...])Construct the full parameter tensor by delegating to each operand.
disable_cache()Disable intermediate caching on this operator and its operands.
enable_cache()Enable intermediate caching on this operator and its operands.
free_param_tree([free_params])Report the free parameters each node of the operand tree receives.
get_default_dtype_device()Get the dtype and the device of the parameter defaults.
get_intermediates(params)Retrieve cached intermediate computation results if still valid.
grad([free_params])Compute the Jacobian of
__call__()with respect to trainable parameters.grad_tree([free_params])Compute the gradient of this operator and of every nested operand, returning each keyed by its path.
manual_grad([free_params])Compute the Jacobian of
__call__()analytically.manual_inverse([free_params])Return the inverse of the matrix from a closed-form expression.
operands_grad([free_params])Compute the Jacobian of each operand with respect to its parameters.
operands_manual_inverse([free_params])Compute each operand's closed-form inverse at the current free parameters.
reset_intermediates()Clear the intermediate caches of this operator and its operands.
resolve_dim(n)Resolve a matrix dimension from an integer or a vector of levels.
set_intermediates(params, intermediates)Cache intermediate computation results keyed by the parameter values.
set_param_specs(key, *[, fixed, default, trans])Update the fields of one or more parameter specifications in place.
trans_grad([free_params])Compute the element-wise derivative of the free parameter transforms.
tree([free_params])Evaluate this operator and every nested operand, returning each result keyed by its path.
walk([free_params])Validate
free_paramsand list every node of the operand tree.Attributes
fixed_param_defaultsFixed parameter defaults.
fixed_param_indexIndex of fixed parameters.
fixed_param_namesFixed parameter names.
fixed_param_transTransforms for fixed parameters.
free_param_defaultsFree parameter defaults.
free_param_indexIndex of free parameters.
free_param_namesFree parameter names.
free_param_transTransforms for free parameters.
num_fixed_paramsTotal number of fixed parameters.
num_free_paramsTotal number of free parameters.
num_paramsTotal number of parameters.
operandsMapping from operand names to operand matrices or tensors.
param_defaultsParameter defaults.
param_namesParameter names.
param_specsParameter specifications, returned as stored rather than copied.
param_transParameter transforms.
repr_dictKey-value pairs used to build the string representation.
shapeOutput matrix shape.
grad_modeGradient computation mode.
jacobian_methodJacobian method used by
auto_grad(), one of"jacrev","jacfwd", or"jacobian".jacobian_chunk_sizeNumber of outputs held per batch when
auto_grad()differentiates with"jacrev", orNoneto compute the Jacobian in a single batch.cacheWhether intermediate computation results are cached, toggled by
enable_cache()anddisable_cache().- __call__(free_params=None)[source]¶
Evaluate \(\symbf{R} + \symbf{Z}\symbf{G}\symbf{Z}^{\top}\).
- Parameters:
free_params (torch.Tensor or dict) – Flat 1D parameter tensor or parameter dictionary. If omitted, default values are used. Default:
None.- Returns:
The \(n \times n\) marginal covariance.
- Return type:
torch.Tensor
- Raises:
ValueError – If
Z,GorRis not two-dimensional, ifRis not square, or ifZ.shape[1]and the dimensions ofGdisagree.
Example:
import torch from torch_openreml.covariance import DummyMatrix, DiagonalMatrix, ScalarMatrix, MarginalCovariance z = DummyMatrix(["a", "b", "c", "a"]) g = DiagonalMatrix(3) r = ScalarMatrix(4) op = MarginalCovariance(Z=z, G=g, R=r) op(torch.zeros(4))
tensor([[2., 0., 0., 1.], [0., 2., 0., 0.], [0., 0., 2., 0.], [1., 0., 0., 2.]])
- manual_grad(free_params=None)[source]¶
Compute the Jacobian of
__call__()analytically.The derivatives are
\[\begin{split}\frac{\partial \symbf{V}}{\partial \theta_{\symbf{Z}}} &= \dot{\symbf{Z}}\symbf{G}\symbf{Z}^{\top} + \symbf{Z}\symbf{G}\dot{\symbf{Z}}^{\top}, \\ \frac{\partial \symbf{V}}{\partial \theta_{\symbf{G}}} &= \symbf{Z}\dot{\symbf{G}}\symbf{Z}^{\top}, \\ \frac{\partial \symbf{V}}{\partial \theta_{\symbf{R}}} &= \dot{\symbf{R}}.\end{split}\]Per-operand Jacobians from
operands_grad()are propagated through these expressions.- Parameters:
free_params (torch.Tensor or dict) – Flat 1D parameter tensor or parameter dictionary. If omitted, default values are used. Default:
None.- Returns:
(grad, grad_names), wheregradhas shape(num_free_params, n, n)andgrad_namesis the matching list of namespaced parameter names. Returns(None, [])when no operand has free parameters.- Return type:
tuple
- Raises:
TypeError – If
free_paramsis not a Torch tensor or a dict.ValueError – If
free_paramshas the wrong length or contains unexpected parameter names.
Example:
import torch from torch_openreml.covariance import DummyMatrix, DiagonalMatrix, ScalarMatrix, MarginalCovariance z = DummyMatrix(["a", "b", "c", "a"]) g = DiagonalMatrix(3) r = ScalarMatrix(4) op = MarginalCovariance(Z=z, G=g, R=r) grad, grad_names = op.manual_grad(torch.zeros(4)) grad
tensor([[[2., 0., 0., 2.], [0., 0., 0., 0.], [0., 0., 0., 0.], [2., 0., 0., 2.]], [[0., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 2., 0.], [0., 0., 0., 0.]], [[2., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 2., 0.], [0., 0., 0., 2.]]])grad_names['G/sigma^2_0', 'G/sigma^2_1', 'G/sigma^2_2', 'R/sigma^2']