torch_openreml.covariance.MarginalCovariance

class torch_openreml.covariance.MarginalCovariance(*args, **kwargs)[source]

Bases: Operator

Marginal 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 or Matrix;

  • G: the random-effect covariance, a \(q \times q\) Matrix or fixed tensor;

  • R: the residual covariance, an \(n \times n\) Matrix or fixed tensor.

Parameters are namespaced by these operand names. A parameter sigma^2 of a term gen inside a block-diagonal G is exposed as G/gen/sigma^2. If Z is itself parameterised, its parameters are exposed as Z/... and come before G and R, 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, G and R, or a single dictionary with keys "Z", "G" and "R".

  • **kwargs – The named operands Z, G and R.

Raises:
  • ValueError – If positional and keyword operands are mixed, or if the operands are not exactly Z, G and R.

  • TypeError – If an operand is not a Matrix or tensor, or if no operand is a Matrix.

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_params and list every node of the operand tree.

Attributes

fixed_param_defaults

Fixed parameter defaults.

fixed_param_index

Index of fixed parameters.

fixed_param_names

Fixed parameter names.

fixed_param_trans

Transforms for fixed parameters.

free_param_defaults

Free parameter defaults.

free_param_index

Index of free parameters.

free_param_names

Free parameter names.

free_param_trans

Transforms for free parameters.

num_fixed_params

Total number of fixed parameters.

num_free_params

Total number of free parameters.

num_params

Total number of parameters.

operands

Mapping from operand names to operand matrices or tensors.

param_defaults

Parameter defaults.

param_names

Parameter names.

param_specs

Parameter specifications, returned as stored rather than copied.

param_trans

Parameter transforms.

repr_dict

Key-value pairs used to build the string representation.

shape

Output matrix shape.

grad_mode

Gradient computation mode.

jacobian_method

Jacobian method used by auto_grad(), one of "jacrev", "jacfwd", or "jacobian".

jacobian_chunk_size

Number of outputs held per batch when auto_grad() differentiates with "jacrev", or None to compute the Jacobian in a single batch.

cache

Whether intermediate computation results are cached, toggled by enable_cache() and disable_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, G or R is not two-dimensional, if R is not square, or if Z.shape[1] and the dimensions of G disagree.

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), where grad has shape (num_free_params, n, n) and grad_names is the matching list of namespaced parameter names. Returns (None, []) when no operand has free parameters.

Return type:

tuple

Raises:
  • TypeError – If free_params is not a Torch tensor or a dict.

  • ValueError – If free_params has 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']