Contract trailing feature axes with a linear readout.
Parameters:
| Name |
Type |
Description |
Default |
features
|
Tensor
|
Feature tensor with shape (*shared, *feature_axes).
|
required
|
readout
|
Tensor
|
Readout tensor with shape (out_channels, *feature_axes).
|
required
|
shared_dims
|
int
|
Number of leading axes in features to preserve.
|
2
|
Returns:
| Type |
Description |
Tensor
|
Contracted tensor with shape (*shared, out_channels).
|
Source code in src/tensorsig/tensor_ops/linear.py
| def contract_features_with_readout(
features: Tensor,
readout: Tensor,
shared_dims: int = 2,
) -> Tensor:
"""Contract trailing feature axes with a linear readout.
Parameters
----------
features : Tensor
Feature tensor with shape ``(*shared, *feature_axes)``.
readout : Tensor
Readout tensor with shape ``(out_channels, *feature_axes)``.
shared_dims : int, optional
Number of leading axes in ``features`` to preserve.
Returns
-------
Tensor
Contracted tensor with shape ``(*shared, out_channels)``.
"""
if isinstance(shared_dims, bool) or not isinstance(shared_dims, int):
raise TypeError("shared_dims must be an integer.")
if shared_dims < 0:
raise ValueError("shared_dims must be non-negative.")
if features.ndim < shared_dims:
raise ValueError(
f"features must have at least {shared_dims} shared dimensions, "
f"got {features.ndim}."
)
expected_readout_ndim = features.ndim - shared_dims + 1
if readout.ndim != expected_readout_ndim:
raise ValueError(
f"readout must have {expected_readout_ndim} dimensions, got {readout.ndim}."
)
if features.shape[shared_dims:] != readout.shape[1:]:
raise ValueError(
f"Feature axes {features.shape[shared_dims:]} do not match readout axes "
f"{readout.shape[1:]}."
)
if readout.dtype != features.dtype:
raise ValueError("readout and features must have the same dtype.")
if readout.device != features.device:
raise ValueError("readout and features must be on the same device.")
shared_shape = features.shape[:shared_dims]
out_channels = readout.shape[0]
feature_size = prod(features.shape[shared_dims:])
features_flat = features.reshape(*shared_shape, feature_size)
readout_flat = readout.reshape(out_channels, feature_size)
return torch.matmul(features_flat, readout_flat.T)
|