mr2.nn.attention.NeighborhoodSelfAttention

class mr2.nn.attention.NeighborhoodSelfAttention[source]

Bases: Module

Attention where each query attends to a neighborhood of the key and value.

Neighborhood attention is a type of attention where each query attends to a neighborhood of the key and value. It is a more efficient alternative to regular attention, especially for large input sizes [NAT].

This implementation uses flex_attention. For a more efficient implementation, see also [NATTEN].

References

[NAT]

Hassani, A. et al. “Neighborhood Attention Transformer” CVPR, 2023, https://arxiv.org/abs/2204.07143

__init__(n_channels_in: int, n_channels_out: int, n_heads: int, kernel_size: int | Sequence[int], dilation: int | Sequence[int] = 1, circular: bool | Sequence[bool] = False, features_last: bool = False, rope_embed_fraction: float = 1.0) → None[source]

Initialize a neighborhood attention module.

The parameters kernel_size, dilation, and circular can either be sequences, interpreted as per-dimension values, or scalars, interpreted as the same value for all dimensions.

Parameters:
  • n_channels_in (int) – The number of channels in the input tensor.

  • n_channels_out (int) – The number of channels in the output tensor.

  • n_heads (int) – The number of attention heads.

  • kernel_size (int | Sequence[int]) – The size of the attention neighborhood window.

  • dilation (int | Sequence[int], default: 1) – The dilation factor for the neighborhood.

  • circular (bool | Sequence[bool], default: False) – Whether the neighborhood wraps around the edges (circular padding)

  • features_last (bool, default: False) – Whether the channels are in the last dimension of the tensor, as common in visíon transformers. Otherwise, assume the channels are in the second dimension, as common in CNN models.

  • rope_embed_fraction (float, default: 1.0) – Fraction of channels to embed with RoPE.

forward(x: Tensor) → Tensor[source]

Apply neighborhood attention to the input tensor.

Parameters:

x (Tensor) – The input tensor, with shape (batch, channels, *spatial_dims) or (batch, *spatial_dims, channels) (if features_last).

Returns:

The output tensor after attention, with the same shape as the input tensor.