mr2.nn.attention.LinearSelfAttention

class mr2.nn.attention.LinearSelfAttention[source]

Bases: Module

Linear multi-head self-attention via kernel trick.

Uses a ReLU kernel to compute attention in O(N) [KAT20] time and space.

References

[KAT20]

Katharopoulos, Angelos, et al. Transformers are RNNs: Fast autoregressive transformers with linear attention. ICML 2020. https://arxiv.org/abs/2006.16236

__init__(n_channels_in: int, n_channels_out: int, n_heads: int, eps: float = 1e-6, features_last: bool = False)[source]

Initialize linear self-attention layer.

Parameters:
  • n_channels_in (int) – Input channel dimension.

  • n_channels_out (int) – Output channel dimension.

  • n_heads (int) – Number of attention heads.

  • eps (float, default: 1e-6) – Small epsilon for numerical stability in normalization.

  • features_last (bool, default: False) – Whether the channel dimension is the last dimension, as common in transformer models, or the second dimension, as common in image models.

__call__(x: Tensor) → Tensor[source]

Apply linear self-attention.

Parameters:

x (Tensor) – Tensor of shape batch, channels, *spatial_dims or (batch, *spatial_dims, channels if features_last)

Returns:

Tensor after attention with n_channels_out channels and the same spatial shape as the input.

forward(x: Tensor) → Tensor[source]

Apply linear self-attention.