torch_openreml.covariance.SimpleMatrix¶
- class torch_openreml.covariance.SimpleMatrix(n, call, manual_grad=None, default=0.0)[source]¶
Bases:
MatrixA covariance matrix for simple, function-based parameterisations.
This is the easiest way to use
REMLwith a custom covariance structure: provide the number of parameters and a function that maps a flat parameter tensor to the covariance matrix. All parameters are free and use an identity transform (unconstrained). Thedefaultargument sets the value used for each free parameter when none are provided.For more advanced needs (custom transforms, fixed parameters, manual gradients), subclass
Matrixdirectly.- Parameters:
n (int) – Number of free parameters.
call (callable) – Function with signature
call(free_params) -> torch.Tensorthat constructs the covariance matrix from a flat 1D parameter tensor.manual_grad (callable, optional) – Function with signature
manual_grad(free_params) -> (grad, grad_names)for a closed-form Jacobian. IfNone(default), automatic differentiation is used.default (float or torch.Tensor, optional) – Default value for each parameter. Passed to
simple_param_specs(). Defaults to0.0.
Example:
import torch from torch_openreml.covariance import SimpleMatrix def my_v(free_params): n = free_params.shape[0] return torch.diag(free_params) mat = SimpleMatrix(n=3, call=my_v) mat(torch.tensor([1.0, 2.0, 3.0]))
tensor([[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]])mat.grad(torch.tensor([1.0, 2.0, 3.0]))
(tensor([[[1., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 1.]]]), ['theta_0', 'theta_1', 'theta_2'])Initialize a covariance matrix with parameter specifications.
- Parameters:
shape (tuple or None) – Expected output dimensions of the constructed matrix. Used for validation; the actual shape may be set by subclasses.
param_specs (dict) – Parameter specifications. Keys should be strings representing parameter names. Values should be dictionaries containing the specification for each parameter. Each specification dictionary should contain the keys
"fixed","default", and"trans", representing whether the parameter is fixed or free (bool), the default value (1D torch.Tensor), and the transform (Transform), respectively.
- Raises:
TypeError – If
param_specsdoes not follow any of the requirements listed in the argument description, or ifshapeis not a tuple or torch.Size.ValueError – If
shapevalues are non-negative.
Methods
__call__([free_params])Construct the matrix from a flat parameter tensor.
auto_grad([free_params])Compute the Jacobian of
build()with respect to free parameters using automatic differentiation.build_params([free_params, include_fixed, ...])Construct the full parameter tensor from free parameters.
get_intermediates(params)Retrieve cached intermediate computation results if still valid.
grad([free_params])Compute the Jacobian of
__call__()with respect to trainable parameters.manual_grad([free_params])Compute the Jacobian of
__call__()with respect to free parameters using a closed-form analytic expression.map_theta_to_dv(theta)An interface compatible with
torch_openreml.REMLthat maps parameters to the matrix Jacobian.map_theta_to_v(theta)An interface compatible with
torch_openreml.REMLthat maps parameters to a matrix.reset_intermediates()Clear the intermediate computation cache.
set_intermediates(params, intermediates)Cache intermediate computation results keyed by parameter hash.
trans_grad([free_params])Compute the element-wise derivative of the free parameter transforms.
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.
param_defaultsParameter defaults.
param_namesParameter names.
param_specsParameter specifications.
param_transParameter transforms.
repr_dictKey-value pairs used to build the string representation.
shapeOutput matrix shape.
- __call__(free_params=None)[source]¶
Construct the matrix from a flat parameter tensor.
Must be implemented by subclasses. Implementations should convert
free_paramsviabuild_params()to validate, include fixed parameters, and apply transforms before any computation.- Parameters:
free_params (torch.Tensor or dict) – Flat 1D parameter tensor or parameter dictionary. If omitted, default values are used. Default:
None.- Returns:
Constructed matrix of shape
shape.- Return type:
torch.Tensor
- manual_grad(free_params=None)[source]¶
Compute the Jacobian of
__call__()with respect to free parameters using a closed-form analytic expression.This method is optional. When implemented by a subclass,
grad()will invoke it in preference toauto_grad()under the default grad mode. If not implemented, calling this method raisesNotImplementedErrorandgrad()falls back to automatic differentiation.Implementations must satisfy the following contract:
Return
(None, [])if all parameters are fixed.Return a 3D gradient tensor of shape
(num_free_params, *shape)and a matching list of parameter names.Apply transform derivatives from
trans_grad()via the chain rule so that gradients are with respect to the raw (untransformed) parameters.
- 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), wheregradis a 3D tensor of shape(num_free_params, *shape)andgrad_namesis a list of the corresponding parameter names. Returns(None, [])if all parameters are fixed.- Return type:
tuple
- Raises:
NotImplementedError – If the subclass does not provide an analytic gradient.
grad()catches this and falls back toauto_grad().