AI Logic

Architectures

Perceiver

Updated:

Structure of Perceiver. The left shows the overall flow on ImageNet: a learned 512×1024 latent array reads an input of 50,176 pixels through cross-attention and processes it with 6 latent Transformer blocks, this pair is repeated 8 times, and the result is averaged and passed through a linear layer to predict the class. The right shows the inside of cross-attention (queries from the latent array, keys and values from the input, cost O(MN)) and how Fourier position features are concatenated to the input.

Background and overview

Perceiver is a modality-agnostic classification model in which a small learned "latent array" repeatedly draws information from a huge input (pixels, audio waveforms, point clouds, and so on) through cross-attention, and a deep Transformer runs on that small latent array. It was published in 2021 by Jaegle et al. of DeepMind and accepted at ICML 2021.

Earlier models were built separately for each kind of input: convolutions for images, CNNs on spectrograms for audio, and dedicated networks for point clouds. Assumptions such as convolution's "look at nearby pixels" make learning efficient but tie a model to one kind of input. Self-attention, on the other hand, makes no assumptions about how the input is arranged, but its cost grows with the square of the input length. A 224×224 image has 50,176 pixels, and computing self-attention between every pair of pixels is impractical. That is why ViT groups an image into 16×16 patches before feeding it to a Transformer.

Perceiver solved this problem by making attention asymmetric.

  • Summarize the input into the latent array with cross-attention: Queries come from a small latent array (512 elements on ImageNet), while keys and values come from the huge input. The cost is the product of the input size MM and the latent array size NN, O(MN)O(MN), not M2M^2.
  • Run a deep Transformer on the latent array: Self-attention on the latent array costs O(N2)O(N^2), so layers can be stacked regardless of the input size.
  • Revisit the input many times: Cross-attention and the latent Transformer alternate repeatedly, pulling the needed information from the input as many times as necessary.

The position of each input element is conveyed by concatenating a Fourier-feature position encoding to it. With this mechanism, Perceiver took raw pixels without any convolution and reached 78.0% on ImageNet, about the same accuracy as ResNet-50 (77.6%) and ViT-B/16 (77.9%). With the same model form, it also came close to dedicated models on audio, video, and point cloud classification.

Architecture

Perceiver is built by alternately stacking two components: cross-attention and a latent Transformer (Section 3.1 and Figure 1 of the paper). In the figure at the top of the article, the left shows the overall flow on ImageNet and the right shows the inside of cross-attention.

Two arrays

  • Byte array (the input): Size M×CM \times C. For an image, the number of pixels is M=224×224=50,176M = 224 \times 224 = 50{,}176, and each pixel's feature has C=261C = 261 dimensions, concatenating the 3 RGB values with 258 position-encoding values.
  • Latent array: Size N×DN \times D. NN is a hyperparameter; on ImageNet the array is 512×1024512 \times 1024. Its initial value is a learned parameter that plays a role like a learned position embedding (initialized from a truncated normal distribution with standard deviation 0.02).

Processing steps (the best ImageNet model)

  1. Read the input with cross-attention: Queries built from the latent array attend to keys and values built from the byte array. The output has the same N×DN \times D shape as the latent array and is added to it as a residual. There is a single head.
  2. Think with the latent Transformer: Six pairs of self-attention and MLP (blocks) are stacked on the latent array. The Transformer has the same form as GPT-2, with no mask.
  3. Repeat steps 1 and 2: The pair of cross-attention and latent Transformer is repeated 8 times in total, giving 48 latent self-attention blocks altogether.
  4. Classify: Average the final latent array over its NN elements and predict the class with a linear layer.

Both cross-attention and self-attention are followed by an MLP (layer normalization → linear layer → GELU → linear layer), and everything is connected by residual connections.

Computational cost

Standard self-attention softmax(QK⊤)V\mathrm{softmax}(QK^{\top})V with queries Q∈RM×DQ \in \mathbb{R}^{M \times D}, keys KK, and values V∈RM×CV \in \mathbb{R}^{M \times C} costs O(M2)O(M^2). In Perceiver only the queries come from the latent array (N≪MN \ll M), so cross-attention costs O(MN)O(MN). With LL latent Transformer layers stacked, the total is as follows (Section 3.1 of the paper).

O(MN+LN2)(applying a Transformer directly to the input costs O(LM2))O(MN + LN^2) \quad \text{(applying a Transformer directly to the input costs } O(LM^2)\text{)}

Since the input size MM and the depth LL are decoupled, the network can be deep even when the input is large.

Weight sharing

Of the 8 cross-attentions, the second and later ones share weights, as do the corresponding blocks of the 8 latent Transformers. Sharing even the first cross-attention made training unstable, so only the first one has separate weights. Sharing reduced the parameters from 326.2 million to 44.9 million and raised ImageNet validation accuracy from 72.9% to 78.0% (Table 7 of the paper). The shared model can be viewed as an RNN that rereads the same input many times, unrolled along depth instead of time.

As an analogy, the latent array is a team of 512 reporters. Everyone reads the huge source material (the input) directly, each summarizes what catches their attention in notes (cross-attention), the reporters discuss among themselves to consolidate their thinking (latent Transformer), and then they go back and reread the material. No matter how thick the material is, the effort of the discussion depends only on the number of reporters.

Position encoding: Fourier features

Attention is an operation whose result does not change when the input is permuted, so Perceiver's architecture itself does not know where each pixel was. Position information is therefore concatenated to each input element (Section 3.2 of the paper).

How it is built

  1. Scale coordinates to [−1,1][-1, 1]: For an image, the 2D coordinates (height and width, d=2d = 2), or for video, the 3D coordinates including time, xdx_d are each scaled to the range −1-1 to 11.
  2. Build sines and cosines per frequency: For KK frequencies fkf_k spaced evenly from 1 to μ/2\mu/2 (the Nyquist frequency of the target resolution μ\mu), compute the following values.
[sin⁡(fkπxd), cos⁡(fkπxd)],k=1,…,K\bigl[\sin(f_k \pi x_d),\ \cos(f_k \pi x_d)\bigr], \qquad k = 1, \dots, K
  1. Also concatenate the raw coordinates: The coordinate xdx_d itself is added as well, so the position encoding has size d(2K+1)d(2K + 1).
  2. Concatenate to the input features: Rather than adding it as in language Transformers, it is concatenated to the input features. The paper reports that this worked better.

On ImageNet, K=64K = 64 and μ=224\mu = 224, so the position encoding has 2×(2×64+1)=2582 \times (2 \times 64 + 1) = 258 dimensions, 261 including RGB. The idea is the same as the sinusoidal position encoding of the Transformer, but the frequencies are spaced evenly rather than as powers of 2, so the maximum frequency and the number of frequencies can be chosen independently.

Positions are built from the coordinates of the cropped region

On ImageNet, the coordinates inside the region cropped by data augmentation are mapped to [−1,1][-1, 1]. Using the coordinates of the whole original image led to overfitting: the model memorized the training data using a few pixels that always had the same (color, position) pairs. Using the coordinates of the cropped region applies data augmentation to position and aspect ratio as well, breaking this link.

The Fourier-feature position encoding knows that the input is an image (a 2D grid). Removing this knowledge as well, by replacing the position encoding with a learned 128-dimensional vector, lowered ImageNet accuracy from 78.0% to 70.9%. Perceiver is a model "without structural assumptions," but much of its accuracy relies on the assumptions built into the position encoding.

Experimental results

ImageNet (validation top-1 accuracy %; FF means Fourier features concatenated to the input; Tables 1 and 2 of the paper)

ModelAccuracyWith permuted pixelsInput range seen at once (pixels)
ResNet-50 (reported value)77.6——
ViT-B/16 (reported value)77.9——
ResNet-50 (FF)73.539.449
ViT-B/16 (FF)76.761.7256
Transformer (downsampled to 64×64, FF)57.057.04,096
Perceiver (FF)78.078.050,176
Perceiver (learned position encoding)70.970.950,176

"Permuted" means the pixels of every image are shuffled in the same order (the position encoding is built before shuffling). ResNet and ViT, which look at nearby pixels through convolutions, dropped sharply, while Perceiver, which assumes nothing about input order, was unchanged. This experiment shows it can be used for inputs that are not shaped like grids, such as point clouds or touch sensors. Training used LAMB for 120 epochs with RandAugment.

Number and arrangement of cross-attentions (Table 6 of the paper; latent self-attention fixed at 8 blocks × 6)

Cross-attentionAccuracyParameters
1 (only at the start)76.741.1M
8 (all at the start)73.744.9M
8 (interleaved with the latent Transformer)78.044.9M

Even with the same 8 cross-attentions, rereading the input repeatedly while thinking did better than reading it all at the start. Stacking only cross-attentions without the latent Transformer reached just 45.3% even with 8 of them (Table 5 of the paper).

AudioSet (audio event classification, mAP; Table 3 of the paper)

ModelAudioVideoAudio + video
ResNet-5038.0——
CNN-1443.1——
CNN-14 (without class balancing and Mixup)37.5——
Attention AV-fusion38.425.746.2
Perceiver (raw waveform)38.325.843.5
Perceiver (mel spectrogram)38.425.843.2

Even with the raw waveform (1.28 seconds, 61,440 samples split into 480 chunks of 128), accuracy was about the same as with a mel-scale spectrogram. When combining audio and video, dropping the entire video input with 30% probability during training improved results by more than 3 points.

ModelNet40 (40-class point cloud classification, accuracy %; Table 4 of the paper)

ModelAccuracy
PointNet++ (dedicated to point clouds, with extra geometric features)91.9
ResNet-50 (FF)66.3
ViT-B/2 (FF)78.9
Transformer (44×44)82.1
Perceiver85.7

It was the highest among the general-purpose models that force point clouds onto a grid. However, it does not reach PointNet++, which is dedicated to point clouds.

Practical considerations

Keep the following points in mind when using Perceiver.

  • It overfits easily: The paper itself states that "flexibility comes with significant overfitting." Even at ImageNet scale, without weight sharing the training accuracy was 87.7% versus 72.9% on validation, a wide gap. This is curbed with weight sharing, data augmentation, and position encodings based on the coordinates of the cropped region.
  • The design of the position encoding drives accuracy: The number of Fourier frequencies and the maximum frequency are chosen for each kind of input. In the paper, point clouds used a maximum frequency 10 times that of ImageNet (1120), and overfitting grew stronger when the number of frequencies exceeded 256.
  • The first cross-attention does not share weights: Sharing it made training unstable.
  • Computation is still heavy: Cross-attention scales linearly with input size, but it still reads 50,000 pixels 8 times. In the paper's table, the best ImageNet model costs about 707 billion FLOPs (counting multiplications and additions separately).
  • Classification output only: The Perceiver in this paper averages the latent array into one vector and predicts the class. For structured outputs such as per-pixel predictions, the follow-up Perceiver IO (which also uses cross-attention for the output) was proposed.
  • Availability in PyTorch: The paper's implementation is in JAX. Hugging Face transformers includes implementations of the follow-up Perceiver IO (such as PerceiverModel).

Having "no structural assumptions" can also be a disadvantage on tasks where the assumptions fit. For data with a clear grid structure such as images, CNNs and ViTs of similar accuracy are lighter to compute and tend to train more stably when data is scarce. Perceiver suits cases where several kinds of input should be handled by one model, or where large inputs that are not grid-shaped, such as point clouds, must be handled.

Comparison with other models

Perceiver is one of several approaches to handling large inputs with attention. Compared from the same viewpoints:

ModelHow it handles large inputsAttention costAssumptions about input structureInput types
TransformerFull self-attention over everythingO(M2)O(M^2)None (position encoding only)Mainly text
ViTGroups into 16×16 patchesSquare of the number of patchesImage grid (patch splitting)Images
Swin TransformerComputes only within small windowsLinear in image sizeImage grid and localityImages
Linformer, PerformerApproximates attention with low rank or kernelsLinear in input lengthNoneMainly text
PerceiverA small latent array reads the input via cross-attentionO(MN+LN2)O(MN + LN^2)None (position encoding only)Images, audio, video, point clouds

Compared with methods such as Linformer and Performer that use attention linear in input length at every layer, Perceiver differs in that only cross-attention touches the input, while deep processing happens on the small latent array. This lets the network be deep regardless of the input size.

Rough guidelines for choosing:

  • Handling images, audio, video, and more with one model form: Perceiver fits well. Only the position encoding and preprocessing change per input type.
  • Handling large inputs that are not grid-shaped (point clouds, collections of sensors, and so on): Perceiver, which is unaffected by permutation, can be used. If accuracy on point cloud classification is the top priority, also compare the PointNet family, which is dedicated to point clouds.
  • Prioritizing accuracy and low compute for image classification or detection: CNNs, ViT, and Swin Transformer, which exploit image structure, are better suited.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

"""
A small implementation of Perceiver (Chapter 3 and Appendix C of the paper).
Cross-attention (latent array -> input) and the latent Transformer are stacked alternately, with weights shared from the second iteration on.
"""


def fourier_features(h, w, num_bands=64, max_res=224):
  """Fourier features of Section 3.2: concatenate [sin(f_k π x_d), cos(f_k π x_d)] and x_d. Returns [h*w, d(2K+1)]"""
  ys, xs = torch.linspace(-1, 1, h), torch.linspace(-1, 1, w)          # Coordinates in [-1, 1]
  pos = torch.stack(torch.meshgrid(ys, xs, indexing="ij"), dim=-1).view(-1, 2)   # [h*w, 2]
  freqs = torch.linspace(1.0, max_res / 2, num_bands)                   # Evenly spaced from 1 to μ/2
  x = pos[..., None] * freqs * math.pi                                  # [h*w, 2, K]
  enc = torch.cat([x.sin(), x.cos()], dim=-1).view(pos.shape[0], -1)    # [h*w, 2*2K]
  return torch.cat([pos, enc], dim=-1)                                  # [h*w, 2(2K+1)]


class MLP(nn.Module):
  def __init__(self, dim):
    super().__init__()
    self.net = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, dim))

  def forward(self, x):
    return x + self.net(x)                                             # Residual connection


class CrossAttend(nn.Module):
  """Queries from the latent array [B, N, D], keys and values from the input [B, M, C]. Cost is O(MN)"""

  def __init__(self, latent_dim, input_dim, heads=1):
    super().__init__()
    self.norm_q, self.norm_kv = nn.LayerNorm(latent_dim), nn.LayerNorm(input_dim)
    self.attn = nn.MultiheadAttention(latent_dim, heads, kdim=input_dim, vdim=input_dim, batch_first=True)
    self.mlp = MLP(latent_dim)

  def forward(self, latent, data):
    kv = self.norm_kv(data)
    out, _ = self.attn(self.norm_q(latent), kv, kv, need_weights=False)
    return self.mlp(latent + out)                                      # Add to the latent array as a residual


class LatentTransformer(nn.Module):
  """Self-attention on the latent array (no mask). Cost is O(N^2)"""

  def __init__(self, dim, depth=6, heads=8):
    super().__init__()
    layer = nn.TransformerEncoderLayer(dim, heads, dim, dropout=0.0, activation="gelu",
                                       batch_first=True, norm_first=True)
    self.blocks = nn.TransformerEncoder(layer, depth)

  def forward(self, x):
    return self.blocks(x)


class Perceiver(nn.Module):
  def __init__(self, input_dim=261, num_latents=512, latent_dim=1024, num_iters=8, depth=6, num_classes=1000):
    super().__init__()
    self.latents = nn.Parameter(torch.empty(num_latents, latent_dim))  # Learned initial latent array
    nn.init.trunc_normal_(self.latents, std=0.02, a=-2, b=2)
    self.first_cross = CrossAttend(latent_dim, input_dim)              # The first one is not shared
    self.shared_cross = CrossAttend(latent_dim, input_dim)             # Shared from the second on
    self.latent_tf = LatentTransformer(latent_dim, depth)              # Shared across all iterations
    self.num_iters = num_iters
    self.head = nn.Linear(latent_dim, num_classes)

  def forward(self, data):                                             # data: [B, M, C]
    z = self.latents.expand(data.shape[0], -1, -1)
    for i in range(self.num_iters):
      z = (self.first_cross if i == 0 else self.shared_cross)(z, data)
      z = self.latent_tf(z)
    return self.head(z.mean(dim=1))                                    # Average over N, then a linear layer


# Small example: a 32×32 image (M = 1024), RGB + Fourier features (K = 16 -> 2×33 = 66 dims)
img = torch.randn(2, 32 * 32, 3)
pos = fourier_features(32, 32, num_bands=16, max_res=32).expand(2, -1, -1)
data = torch.cat([img, pos], dim=-1)                                   # Concatenate, not add: [2, 1024, 69]
model = Perceiver(input_dim=69, num_latents=64, latent_dim=128, num_iters=2, depth=2, num_classes=10)
model.train()
logits = model(data)                                                   # [2, 10]

FAQ

Q. Why can Perceiver take 50,000 pixels directly?
A.

Because the only part that touches the input directly is cross-attention, whose queries come from a small latent array. Ordinary self-attention needs computation proportional to the square of the input size MM, but cross-attention only needs the product of MM and the latent array size NN (512 on ImageNet), O(MN)O(MN). Deep processing is done by the Transformer on the latent array, whose cost is N2N^2 and independent of the input size.

Q. Does Perceiver really assume nothing about input structure?
A.

The model architecture assumes nothing, but the position encoding carries knowledge of the input's shape. For images, Fourier features are built from 2D (height and width) coordinates. Replacing the position encoding with learned vectors that know nothing about the structure lowered ImageNet accuracy from 78.0% to 70.9%. Even so, unlike convolution-based models such as ResNet, its accuracy does not change when pixels are permuted.

Q. Why is cross-attention repeated many times?
A.

Because summarizing 50,000 inputs into 512 latents in a single pass risks missing needed details. By rereading the input based on what the latent Transformer has worked out, the model can extract needed information later. In the paper's comparison, with the same 8 cross-attentions, reading everything at the start gave 73.7%, while interleaving them with the latent Transformer gave 78.0%.

References

  1. Jaegle, A., Gimeno, F., Brock, A., Zisserman, A., Vinyals, O., & Carreira, J. (2021). Perceiver: General Perception with Iterative Attention. ICML 2021. arXiv:2103.03206.
  2. Jaegle, A., et al. (2021). Perceiver IO: A General Architecture for Structured Inputs & Outputs. arXiv:2107.14795.
  3. Vaswani, A., et al. (2017). Attention Is All You Need. arXiv:1706.03762.