Skip to content

Encoder

The encoder (paper module E) compresses the contextualised patches of an entity into a fixed number of latent embedding e: 512 latent vectors of dimension 256 in the paper, whatever the number of channels. The design follows Perceiver IO (Jaegle et al., 2022): a small set of learned latent queries e_queries reads the (large) input through cross-attention, then refines itself.

What it does

  1. Cross-attention. The latent queries attend to the contextualized patches (keys and values), so that each query gathers the information it needs from the whole recording.
  2. Latent self-attention. num_self_attention_layers layers let the latents exchange information.
  3. Blocks. The cross-attention and self-attention are repeated num_blocks times. Each block re-attends the refined latents to the same patches. The latents of every block are kept, because the paper's analyses read several of them.

An optional CLS token is appended to the latents (use_cls_token); the head uses it when pooling is "cls_token".

Patch masking

During pretraining, a fraction patch_mask_ratio (0.7 in the paper) of the contextualized patches is hidden from the encoder. The masking takes place after the contextualizer and before the encoder: the contextualizer sees the whole recording, and the encoder only reads the patches that are not masked. The model must then infer the hidden content from the rest instead of copying its input.

The paper draws each patch independently with a Bernoulli(patch_mask_ratio) trial. The implementation hides exactly floor(patch_mask_ratio * number of patches) patches in every row of the batch, so that the kept patches form a tensor of static shape (efficient on MPS and with torch.compile). The expected fraction is the same. The encoder selects the kept patches before the cross-attention, so keys and values are only computed for them.

Options that matter

Option Default Experiments Effect
num_latents 512 512 Number of latent queries, which gives the size of the latent embedding.
latent_dim 256 256 Width of the latents.
num_blocks 2 2 Cross-attention and self-attention blocks (L_blocks).
num_self_attention_layers 4 4 Latent self-attention layers per block (L_enc).
num_cross_attention_heads 1 1 Heads of the cross-attention.
use_cls_token True Appends a CLS latent.
latent_dropout_ratio 0.0 Drops whole latents during training.

References

Jaegle, A. et al. (2022). Perceiver IO: A General Architecture for Structured Inputs & Outputs. ICLR.

Reference API

timber.modules.encoder

Perceiver IO encoder (paper module E): latents cross-attend to the patches, then self-attend.

The encoder is a stack of blocks. Each block has its own cross-attention from the latents to the (kept) patches, followed by num_self_attention_layers latent self-attention layers. An optional CLS token is appended after the latents.

Patch masking is applied by selecting the kept patches (kept_indices) before the cross-attention, so keys and values are only computed for visible patches; this is equivalent to masking them out of the attention.

PerceiverEncoder

Bases: Module

Perceiver IO encoder over contextualised patches.

Parameters:

Name Type Description Default
patch_dim int

Channels of the input patches.

required
num_latents int

Number of latent tokens.

required
latent_dim int

Channels of the latents.

required
num_blocks int

Number of encoder blocks (each with its own cross-attention).

1
num_self_attention_layers int

Self-attention layers per block.

4
num_self_attention_heads int

Heads of the latent self-attention.

1
num_cross_attention_heads int

Heads of the cross-attention.

1
self_attention_widening_factor int

MLP widening of the self-attention layers.

1
cross_attention_widening_factor int

MLP widening of the cross-attention layers.

1
dropout float

Dropout on the attention probabilities.

0.0
use_cls_token bool

Append a trainable CLS token after the latents.

False
latent_dropout_ratio float

Probability to drop each latent token (training only, before every block).

0.0
use_gradient_checkpointing bool

Recompute each block in the backward pass (training only).

False
initializer_range float

Standard deviation of the CLS token initialisation.

0.02
use_cls_token property
use_cls_token: bool

Whether a CLS latent is appended to the latents.

num_tokens property
num_tokens: int

Latent tokens in the output (latents plus the CLS token).

forward
forward(
    patch_embeddings: Tensor,
    kept_indices: Tensor | None = None,
    num_blocks: int | None = None,
    need_weights: bool = False,
) -> EncoderOutput

Encode the patches into latents.

Parameters:

Name Type Description Default
patch_embeddings Tensor

(batch, num_patches, patch_dim).

required
kept_indices Tensor | None

Optional (batch, num_kept) indices of the visible patches (see PatchMask); all patches are used when None.

None
num_blocks int | None

Run only the first num_blocks blocks (default: all).

None
need_weights bool

Return the cross-attention probabilities of every block and the probabilities of its last self-attention layer.

False

Returns:

Type Description
EncoderOutput

EncoderOutput.

PerceiverEncoderBlock

Bases: Module

Cross-attention from the latents to the patches, then latent self-attention layers.

forward
forward(
    latents: Tensor,
    patches: Tensor,
    need_weights: bool = False,
) -> tuple[
    torch.Tensor, torch.Tensor | None, torch.Tensor | None
]

latents (batch, tokens, latent_dim), patches (batch, kept, patch_dim) -> latents, cross-attention and last self-attention probabilities (None unless need_weights).

EncoderOutput dataclass

Output of PerceiverEncoder.

Attributes:

Name Type Description
latents Tensor

(batch, num_tokens, latent_dim) after the last block, with num_tokens = num_latents (+ 1 with the CLS token, last position).

block_latents tuple[Tensor, ...]

Latents after every block (block_latents[-1] is latents).

cross_attentions tuple[Tensor, ...] | None

Per block (batch, heads, num_tokens, num_kept_patches) when requested.

self_attentions tuple[Tensor | None, ...] | None

Per block, the last latent self-attention layer (batch, heads, num_tokens, num_tokens) when requested.