Covariance

class torchcast.covariance.Covariance(rank: int, init_diag_multi: float, method: str = 'log_cholesky', empty_idx: List[int] = (), predict_variance: Module | None = None, expected_kwargs: Sequence[str] | None = None, id: str | None = None, corr_mask: Tensor | None = None, stationary_idx: Sequence[int] = (), nonstationary_idx: Sequence[int] = ())

The Covariance can be used when you’d like more control over the covariance specification of a state- space model. For example, if you’re training on diverse time-serieses that vary in scale/behavior, you could use an torch.nn.Embedding to predict the variance of each series, with the group-ids as predictors:

kf = KalmanFilter(
    measures=measures,
    processes=processes,
    measure_covariance=Covariance.from_measures(
        measures,
        predict_variance=torch.nn.Sequential(
            torch.nn.Embedding(len(group_ids), len(measures), padding_idx=0),
            torch.nn.Softplus()
        ),
        expected_kwargs=['group_ids']
    ),
    process_covariance=Covariance.from_processes(
        processes,
        predict_variance=torch.nn.Sequential(
            torch.nn.Embedding(len(group_ids), Covariance.from_processes(processes).param_rank, padding_idx=0),
            torch.nn.Softplus()
        ),
        expected_kwargs=['group_ids']
    )
)
classmethod from_matrix(cov: Tensor, method: str = 'sd_corr', empty_idx: Collection[int] = (), **kwargs) → Covariance

Create a Covariance whose covariance (before any predict_variance) equals cov.

Parameters:
  • cov – A (rank, rank) covariance matrix, whose rows/columns in empty_idx are zero.

  • method – The parameterization, see Covariance.__init__().

  • empty_idx – Elements with no variance.

  • kwargs – Other arguments passed to Covariance.__init__().

classmethod from_measures(measures: Sequence[str], predict_variance: bool | Module = None, corr_groups: Sequence[Sequence[str]] | None = None, method: str | None = None, **kwargs) → Covariance
Parameters:
  • measures – The measures used in your StateSpaceModel.

  • predict_variance – Will the variance be predicted upon calling forward()? This is implemented as a multiplier on the base variance given from the ‘method’. You can either pass True in which case it is expected you will pass multipliers as ‘measure_var_multi’ when forward() is called; or you can pass a torch.nn.Module that will predict the multipliers, in which case you’ll pass input(s) to this module at forward. Either way please note these should output strictly positive values with shape (num_groups, num_times, len(measures)).

  • corr_groups – Optionally, groups of measures that are uncorrelated with those in other groups; measures not in any group form one more group together. See Covariance.from_processes().

  • method – The parameterization, see Covariance.__init__(). If not given, “log_cholesky”.

  • kwargs – Other arguments passed to Covariance.__init__().

Returns:

A Covariance object that can be used in your StateSpaceModel.

classmethod from_processes(processes: Sequence[Process], cov_type: str = 'process', predict_variance: bool | Module = None, corr_groups: Sequence[Sequence[str]] | None = None, stationary: Sequence[str] | Dict[str, bool] | None = None, method: str | None = None, **kwargs) → Covariance
Parameters:
  • processes – The processes used in your StateSpaceModel.

  • cov_type – The type of covariance, either ‘process’ or ‘initial’ (default: ‘process’).

  • predict_variance – Will the variance be predicted upon calling forward()? This is implemented as a multiplier on the base variance given from the ‘method’. You can either pass True in which case it is expected you will pass multipliers as ‘process_var_multi’ when forward() is called; or you can pass a torch.nn.Module that will predict the multipliers, in which case you’ll pass input(s) to this module at forward. Either way please note these should output strictly positive values with shape (num_groups, num_times, self.param_rank).

  • corr_groups – Optionally, groups of process ids whose processes are uncorrelated with those in other groups (within a group, and within each process, they stay correlated). Processes not in any group form one more group together. E.g. with processes ‘level_a’, ‘transient_a’, ‘level_b’, ‘transient_b’: corr_groups=[['transient_a', 'transient_b']] makes the transients correlated with each other, and the levels correlated with each other, but no transient correlated with any level. Note that “uncorrelated” has to be transitive this way: you can’t make ‘transient_a’ uncorrelated with ‘level_a’ only, while both stay correlated with ‘level_b’ (masking can’t guarantee a valid covariance for that pattern). For other masks, see corr_mask in Covariance.__init__().

  • stationary – Only for cov_type='initial': ids of decaying processes (e.g. LocalLevel with decay=(.5, .95)) whose initial covariance is their stationary covariance, rather than free parameters. For elements i and j of these processes it’s Q[i, j] / (1 - decay_i * decay_j), where Q is the (base) process-covariance and decay each element’s transition to itself (the KalmanFilter computes this); between these and other elements it’s zero (there’s no stationary covariance with, e.g., a random walk). These elements get no parameters here. With a learned decay this is recommended: otherwise the decay trades off against the initial variance (a faster decay with a larger initial variance fits the start of a series about as well as a slower decay with a smaller one), so the decay is pinned down by the first few timesteps rather than the whole series; the KalmanFilter warns about this. Each element of these processes needs process-noise, a decay that’s less than 1 (a learned decay may be bounded at 1, e.g. decay=(.5, 1.0): the stationary variance grows without bound as it nears 1, so the likelihood keeps it below, and an error is raised if it reaches 1), and no transitions into it from other elements. Either a list of process ids (all stationary) or a dict of process ids to True/False, where False keeps free parameters on purpose (silencing the warning): e.g. for a decaying level that captures how far series start from their long-run level after a common start event (sign-up, launch), whose initial spread is larger than its stationary one. Note that listing processes here changes this covariance’s parameters and its mask buffer (both shrink), so a state-dict saved without it won’t load into one with it: to warm-start, drop all of the saved initial_covariance.* entries, and set the free block with Covariance.set_matrix_() if needed.

  • method – The parameterization, see Covariance.__init__(). If not given, “log_cholesky”.

  • kwargs – Other arguments passed to Covariance.__init__().

Returns:

A Covariance object that can be used in your StateSpaceModel.

get_corr_cholesky() → Tensor

The cholesky factor of the correlation matrix (of the param_rank block, i.e. excluding empty_idx, and before any predict_variance). Not used by torchcast internally, but can be useful if (e.g.) you want to set up an LKJ prior for your model: torch.distributions.LKJCholesky(cov.param_rank, eta).log_prob(cov.get_corr_cholesky()).

get_off_diag_idx(i: int, j: int) → int

The index of the pair of elements (i, j) (in either order, of 0..rank-1) in the off-diagonal parameters (corr_unconstrained for “sd_corr”, cholesky_off_diag for “log_cholesky”), accounting for empty_idx, and for pairs masked out by a binary corr_mask (which have no parameter). See Covariance.get_param_idx().

get_param_idx(i: int) → int

The index of element i (of 0..rank-1) in the per-element parameters (log_std_devs for “sd_corr”, cholesky_log_diag for “log_cholesky”), accounting for empty_idx. E.g., to freeze some elements’ std-devs and correlations (the frozen entries get exactly zero gradients):

cov = Covariance.from_processes(processes, cov_type='initial', method='sd_corr')
keep_std = torch.ones_like(cov.log_std_devs)
keep_std[cov.get_param_idx(3)] = 0
cov.log_std_devs.register_hook(lambda g: g * keep_std)
keep_corr = torch.ones_like(cov.corr_unconstrained)
keep_corr[cov.get_off_diag_idx(3, 0)] = 0
cov.corr_unconstrained.register_hook(lambda g: g * keep_corr)

For “sd_corr”, these entries are interpretable on their own; for “log_cholesky” they’re entries of the cholesky factor, which mix scale and correlation.

static log_chol_to_chol(log_diag: Tensor, off_diag: Tensor) → Tensor

Deprecated: use torchcast.covariance.log_chol_to_chol().

set_matrix_(cov: Tensor) → Covariance

Set this module’s parameters (in-place) so that its covariance (before any predict_variance) equals cov.

Parameters:

cov – A (rank, rank) covariance matrix, whose rows/columns in empty_idx are zero (as are its entries masked out by a binary corr_mask); or just the (param_rank, param_rank) block for the non-empty elements.

Returns:

This module.

to_method(method: str) → Covariance

A copy of this module with a different parameterization (method) but the same covariance (exactly, up to floating-point error), e.g. to convert a fitted model: model.initial_covariance = model.initial_covariance.to_method('sd_corr'). Other attributes (id, empty_idx, predict_variance) are carried over. Note that a model’s state-dict saved after converting can only be loaded into a model created with the new method.

Helpers

torchcast.covariance.log_chol_to_chol(log_diag: Tensor, off_diag: Tensor) → Tensor

A lower-triangular cholesky factor from its log-diagonal and its off-diagonal entries (filled into the strict lower triangle in the order of torch.tril_indices(rank, rank, -1)), as parameterized by Covariance(method='log_cholesky').

Parameters:
  • log_diag – Tensor whose last dim is rank.

  • off_diag – Tensor whose last dim is rank * (rank - 1) / 2.

Returns:

Tensor with trailing dims (rank, rank).

torchcast.covariance.corr_cholesky_from_unconstrained(u: Tensor, rank: int) → Tensor

The cholesky factor of a correlation matrix, from unconstrained parameters: tanh(u) are canonical partial correlations, filled into the strict lower triangle in the order of torch.tril_indices(rank, rank, -1). Row i is L[i, j] = z_ij * sqrt(1 - sum_{k<j} L[i, k]^2), L[i, i] = sqrt(1 - sum_{k<i} L[i, k]^2), so each row has unit norm.

Parameters:
  • u – Tensor whose last dim is rank * (rank - 1) / 2.

  • rank – Size of the correlation matrix.

Returns:

Tensor with trailing dims (rank, rank).

torchcast.covariance.corr_cholesky_to_unconstrained(L: Tensor, eps: float = 1e-12) → Tensor

Inverse of corr_cholesky_from_unconstrained(). Best done in float64 (eps clamps the partial correlations away from +/-1, for near-singular correlation matrices).

torchcast.covariance.cov2corr(cov: Tensor) → Tensor

The correlation matrix (or matrices, over leading dims) of a covariance matrix.