Skip to content

Attention, masking and devices

These helpers are used by the modules above. They are documented here because the choices they make (fused attention, static shapes, device defaults) affect speed and memory.

Attention

All attention goes through torch.nn.functional.scaled_dot_product_attention, so the fused kernels of CUDA and Apple MPS are used when they apply. The three shared blocks are:

  • MultiHeadAttention: the attention itself, with boolean masks (True means "may attend");
  • FeedForward: the position-wise MLP after each attention;
  • PerceiverLayer: cross-attention from queries to a context, then a feed-forward block. The encoder and decoders are built from it.

On MPS the explicit attention path is used whenever gradients or dropout are active: the fused kernel rejects dropout, and the explicit path has faster backward passes there.

timber.modules.attention

Attention building blocks shared by the contextualizer, the Perceiver encoder and the decoders.

All attention goes through scaled_dot_product_attention (SDPA), so the fused CUDA/MPS kernels are used when available. Masks are boolean (True = may attend); no -inf float masks are materialised.

Shape conventions: batch is any flattened batch axis, query / key are sequence axes, dim is the channel axis.

MultiHeadAttention

Bases: Module

Multi-head (self- or cross-) attention with separate query/key/value projections.

Parameters:

Name Type Description Default
query_dim int

Channels of the query input.

required
key_value_dim int | None

Channels of the key/value input (defaults to query_dim).

None
num_heads int

Number of attention heads.

1
qk_dim int | None

Channels of the query/key projections (defaults to query_dim).

None
value_dim int | None

Channels of the value projection (defaults to qk_dim).

None
output_dim int | None

Channels of the output projection (defaults to query_dim).

None
dropout float

Dropout on the attention probabilities (training only).

0.0
bias bool

Whether the projections have a bias.

True
forward
forward(
    query: Tensor,
    key_value: Tensor | None = None,
    *,
    attn_mask: Tensor | None = None,
    is_causal: bool = False,
    need_weights: bool = False,
) -> tuple[torch.Tensor, torch.Tensor | None]

Attend from query to key_value (self-attention when key_value is None).

Parameters:

Name Type Description Default
query Tensor

(batch, query, query_dim).

required
key_value Tensor | None

(batch, key, key_value_dim) or None.

None
attn_mask Tensor | None

Optional boolean mask broadcastable to (batch, heads, query, key).

None
is_causal bool

Apply a causal mask (query i attends keys <= i).

False
need_weights bool

Also return the attention probabilities (batch, heads, query, key). This uses the explicit (non-fused) path, so keep it for analysis.

False

Returns:

Type Description
Tensor

(output, weights) with output (batch, query, output_dim); weights is

Tensor | None

None unless need_weights.

FeedForward

Bases: Module

Position-wise MLP: fc1 -> GELU -> dropout -> fc2.

Parameters:

Name Type Description Default
dim int

Input and output channels.

required
hidden_dim int

Hidden channels.

required
dropout float

Dropout after the activation (training only).

0.0
forward
forward(x: Tensor) -> torch.Tensor

(..., dim) -> (..., dim).

PerceiverLayer

Bases: Module

Pre-norm Perceiver layer: attention then MLP, each with a residual connection.

output = h + mlp(norm(h)) with h = attention(norm(query), norm(key_value)) [+ query]. The query residual can be disabled (used by the decoders, whose queries and outputs have different meanings).

Parameters:

Name Type Description Default
query_dim int

Channels of the queries (and of the output).

required
key_value_dim int | None

Channels of the keys/values for cross-attention, or None for self-attention.

None
num_heads int

Number of attention heads.

1
qk_dim int | None

Channels of the query/key projections (defaults to query_dim).

None
widening_factor int

MLP hidden size as a multiple of query_dim.

1
dropout float

Dropout on the attention probabilities.

0.0
use_query_residual bool

Add the (un-normalised) query to the attention output.

True
forward
forward(
    query: Tensor,
    key_value: Tensor | None = None,
    *,
    attn_mask: Tensor | None = None,
    need_weights: bool = False,
) -> tuple[torch.Tensor, torch.Tensor | None]

query (batch, query, query_dim), key_value (batch, key, key_value_dim).

Returns (output, weights) with output (batch, query, query_dim).

Patch masking

Pretraining hides a fraction patch_mask_ratio of the patches. Every row of the batch hides the same number of patches, so the kept and hidden patches can be picked with gather into tensors of fixed shape. The shapes do not depend on the random draw, which keeps MPS and torch.compile efficient.

timber.modules.masking

Vectorised patch masking and token dropout.

Every row masks the same number of patches, so the kept and masked patches can be selected with gather into tensors of static shape (no boolean indexing): this keeps shapes fixed for MPS and torch.compile.

PatchMask dataclass

A patch mask with the same number of masked patches in every row.

Attributes:

Name Type Description
keep Tensor

(batch, num_patches) boolean, True for kept (visible) patches.

kept_indices Tensor

(batch, num_kept) indices of the kept patches, increasing.

masked_indices Tensor

(batch, num_masked) indices of the masked patches, increasing.

from_keep classmethod
from_keep(keep: Tensor) -> PatchMask

Build from a (batch, num_patches) keep mask (bool or 0/1) with a constant count per row.

num_masked_patches

num_masked_patches(
    num_patches: int, mask_ratio: float
) -> int

Number of patches masked per row (rounding down: int(num_patches * mask_ratio)).

random_patch_mask

random_patch_mask(
    batch_size: int,
    num_patches: int,
    mask_ratio: float,
    device: device | str | None = None,
    generator: Generator | None = None,
) -> PatchMask

Mask int(num_patches * mask_ratio) random patches in each row, independently per row.

gather_patches

gather_patches(x: Tensor, indices: Tensor) -> torch.Tensor

Select patches along axis 1: x (batch, num_patches, dim), indices (batch, k) -> (batch, k, dim).

token_dropout

token_dropout(
    x: Tensor,
    p: float,
    training: bool,
    generator: Generator | None = None,
) -> torch.Tensor

Zero whole tokens with probability p and rescale the others by 1 / (1 - p).

Same behaviour as nn.Dropout1d on (batch, tokens, dim): x (batch, tokens, dim).

Devices and precision

get_accelerator() returns "cuda", "mps" or "cpu", in that order of preference. default_precision() returns "bf16-mixed" on CUDA and MPS and "32-true" on CPU; an explicit precision in the trainer always wins.

timber.device

Device and precision defaults (CUDA > MPS > CPU).

get_accelerator

get_accelerator() -> str

Best available accelerator: "cuda", "mps" or "cpu".

default_precision

default_precision(accelerator: str | None = None) -> str

Lightning precision for an accelerator: bf16-mixed on CUDA and MPS, 32-true on CPU.

None or "auto" use the best available accelerator (get_accelerator).