Perceiver

## [](#overview)Overview

The Perceiver IO model was proposed in [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira.

Perceiver IO is a generalization of [Perceiver](https://arxiv.org/abs/2103.03206) to handle arbitrary outputs in addition to arbitrary inputs. The original Perceiver only produced a single classification label. In addition to classification labels, Perceiver IO can produce (for example) language, optical flow, and multimodal videos with audio. This is done using the same building blocks as the original Perceiver. The computational complexity of Perceiver IO is linear in the input and output size and the bulk of the processing occurs in the latent space, allowing us to process inputs and outputs that are much larger than can be handled by standard Transformers. This means, for example, Perceiver IO can do BERT-style masked language modeling directly using bytes instead of tokenized inputs.

The abstract from the paper is the following:

_The recently-proposed Perceiver model obtains good results on several domains (images, audio, multimodal, point clouds) while scaling linearly in compute and memory with the input size. While the Perceiver supports many kinds of inputs, it can only produce very simple outputs such as class scores. Perceiver IO overcomes this limitation without sacrificing the original’s appealing properties by learning to flexibly query the model’s latent space to produce outputs of arbitrary size and semantics. Perceiver IO still decouples model depth from data size and still scales linearly with data size, but now with respect to both input and output sizes. The full Perceiver IO model achieves strong results on tasks with highly structured output spaces, such as natural language and visual understanding, StarCraft II, and multi-task and multi-modal domains. As highlights, Perceiver IO matches a Transformer-based BERT baseline on the GLUE language benchmark without the need for input tokenization and achieves state-of-the-art performance on Sintel optical flow estimation._

Here’s a TLDR explaining how Perceiver works:

The main problem with the self-attention mechanism of the Transformer is that the time and memory requirements scale quadratically with the sequence length. Hence, models like BERT and RoBERTa are limited to a max sequence length of 512 tokens. Perceiver aims to solve this issue by, instead of performing self-attention on the inputs, perform it on a set of latent variables, and only use the inputs for cross-attention. In this way, the time and memory requirements don’t depend on the length of the inputs anymore, as one uses a fixed amount of latent variables, like 256 or 512. These are randomly initialized, after which they are trained end-to-end using backpropagation.

Internally, [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel) will create the latents, which is a tensor of shape `(batch_size, num_latents, d_latents)`. One must provide `inputs` (which could be text, images, audio, you name it!) to the model, which it will use to perform cross-attention with the latents. The output of the Perceiver encoder is a tensor of the same shape. One can then, similar to BERT, convert the last hidden states of the latents to classification logits by averaging along the sequence dimension, and placing a linear layer on top of that to project the `d_latents` to `num_labels`.

This was the idea of the original Perceiver paper. However, it could only output classification logits. In a follow-up work, PerceiverIO, they generalized it to let the model also produce outputs of arbitrary size. How, you might ask? The idea is actually relatively simple: one defines outputs of an arbitrary size, and then applies cross-attention with the last hidden states of the latents, using the outputs as queries, and the latents as keys and values.

So let’s say one wants to perform masked language modeling (BERT-style) with the Perceiver. As the Perceiver’s input length will not have an impact on the computation time of the self-attention layers, one can provide raw bytes, providing `inputs` of length 2048 to the model. If one now masks out certain of these 2048 tokens, one can define the `outputs` as being of shape: `(batch_size, 2048, 768)`. Next, one performs cross-attention with the final hidden states of the latents to update the `outputs` tensor. After cross-attention, one still has a tensor of shape `(batch_size, 2048, 768)`. One can then place a regular language modeling head on top, to project the last dimension to the vocabulary size of the model, i.e. creating logits of shape `(batch_size, 2048, 262)` (as Perceiver uses a vocabulary size of 262 byte IDs).

![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/perceiver_architecture.jpg) Perceiver IO architecture. Taken from the [original paper](https://arxiv.org/abs/2105.15203)

This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/deepmind/deepmind-research/tree/master/perceiver).

Tips:

-   The quickest way to get started with the Perceiver is by checking the [tutorial notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Perceiver).
-   Refer to the [blog post](https://huggingface.co/blog/perceiver) if you want to fully understand how the model works and is implemented in the library. Note that the models available in the library only showcase some examples of what you can do with the Perceiver. There are many more use cases, including question answering, named-entity recognition, object detection, audio classification, video classification, etc.

**Note**:

-   Perceiver does **not** work with `torch.nn.DataParallel` due to a bug in PyTorch, see [issue #36035](https://github.com/pytorch/pytorch/issues/36035)

## [](#documentation-resources)Documentation resources

-   [Text classification task guide](../tasks/sequence_classification)
-   [Masked language modeling task guide](../tasks/masked_language_modeling)
-   [Image classification task guide](../tasks/image_classification)

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverModelOutput)Perceiver specific outputs

### class transformers.models.perceiver.modeling\_perceiver.PerceiverModelOutput

[](#transformers.models.perceiver.modeling_perceiver.PerceiverModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L61)

( logits: FloatTensor = Nonelast\_hidden\_state: FloatTensor = Nonehidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneattentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Base class for Perceiver base model’s outputs, with potential hidden states, attentions and cross-attentions.

### class transformers.models.perceiver.modeling\_perceiver.PerceiverDecoderOutput

[](#transformers.models.perceiver.modeling_perceiver.PerceiverDecoderOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L92)

( logits: FloatTensor = Nonecross\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverDecoderOutput.logits)**logits** (`torch.FloatTensor` of shape `(batch_size, num_labels)`) — Output of the basic decoder.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverDecoderOutput.cross_attentions)**cross\_attentions** (`tuple(torch.FloatTensor)`, _optional_, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) — Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.

Base class for Perceiver decoder outputs, with potential cross-attentions.

### class transformers.models.perceiver.modeling\_perceiver.PerceiverMaskedLMOutput

[](#transformers.models.perceiver.modeling_perceiver.PerceiverMaskedLMOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L110)

( loss: typing.Optional\[torch.FloatTensor\] = Nonelogits: FloatTensor = Nonehidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneattentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Base class for Perceiver’s masked language model outputs.

### class transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput

[](#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L141)

( loss: typing.Optional\[torch.FloatTensor\] = Nonelogits: FloatTensor = Nonehidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneattentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Base class for Perceiver’s outputs of sequence/image classification models, optical flow and multimodal autoencoding.

## [](#transformers.PerceiverConfig)PerceiverConfig

### class transformers.PerceiverConfig

[](#transformers.PerceiverConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/configuration_perceiver.py#L36)

( num\_latents = 256d\_latents = 1280d\_model = 768num\_blocks = 1num\_self\_attends\_per\_block = 26num\_self\_attention\_heads = 8num\_cross\_attention\_heads = 8qk\_channels = Nonev\_channels = Nonecross\_attention\_shape\_for\_attention = 'kv'self\_attention\_widening\_factor = 1cross\_attention\_widening\_factor = 1hidden\_act = 'gelu'attention\_probs\_dropout\_prob = 0.1initializer\_range = 0.02layer\_norm\_eps = 1e-12use\_query\_residual = Truevocab\_size = 262max\_position\_embeddings = 2048image\_size = 56train\_size = \[368, 496\]num\_frames = 16audio\_samples\_per\_frame = 1920samples\_per\_patch = 16output\_shape = \[1, 16, 224, 224\]\*\*kwargs )

This is the configuration class to store the configuration of a [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel). It is used to instantiate an Perceiver model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Perceiver [deepmind/language-perceiver](https://huggingface.co/deepmind/language-perceiver) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Example:

```
>>> from transformers import PerceiverModel, PerceiverConfig

>>> 
>>> configuration = PerceiverConfig()

>>> 
>>> model = PerceiverModel(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.PerceiverTokenizer)PerceiverTokenizer

### class transformers.PerceiverTokenizer

[](#transformers.PerceiverTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/tokenization_perceiver.py#L27)

( pad\_token = '\[PAD\]'bos\_token = '\[BOS\]'eos\_token = '\[EOS\]'mask\_token = '\[MASK\]'cls\_token = '\[CLS\]'sep\_token = '\[SEP\]'model\_max\_length = 2048\*\*kwargs )

Parameters

-   [](#transformers.PerceiverTokenizer.pad_token)**pad\_token** (`str`, _optional_, defaults to `"[PAD]"`) — The token used for padding, for example when batching sequences of different lengths.
-   [](#transformers.PerceiverTokenizer.bos_token)**bos\_token** (`str`, _optional_, defaults to `"[BOS]"`) — The BOS token (reserved in the vocab, but not actually used).
-   [](#transformers.PerceiverTokenizer.eos_token)**eos\_token** (`str`, _optional_, defaults to `"[EOS]"`) — The end of sequence token (reserved in the vocab, but not actually used).
    
    When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the `sep_token`.
    
-   [](#transformers.PerceiverTokenizer.mask_token)**mask\_token** (`str`, _optional_, defaults to `"[MASK]"`) — The MASK token, useful for masked language modeling.
-   [](#transformers.PerceiverTokenizer.cls_token)**cls\_token** (`str`, _optional_, defaults to `"[CLS]"`) — The CLS token (reserved in the vocab, but not actually used).
-   [](#transformers.PerceiverTokenizer.sep_token)**sep\_token** (`str`, _optional_, defaults to `"[SEP]"`) — The separator token, which is used when building a sequence from two sequences.

Construct a Perceiver tokenizer. The Perceiver simply uses raw bytes utf-8 encoding.

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### \_\_call\_\_

[](#transformers.PerceiverTokenizer.__call__)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/tokenization_utils_base.py#L2487)

( text: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\]\] = Nonetext\_pair: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\], NoneType\] = Nonetext\_target: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\]\] = Nonetext\_pair\_target: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\], NoneType\] = Noneadd\_special\_tokens: bool = Truepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Falsetruncation: typing.Union\[bool, str, transformers.tokenization\_utils\_base.TruncationStrategy\] = Nonemax\_length: typing.Optional\[int\] = Nonestride: int = 0is\_split\_into\_words: bool = Falsepad\_to\_multiple\_of: typing.Optional\[int\] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = Nonereturn\_token\_type\_ids: typing.Optional\[bool\] = Nonereturn\_attention\_mask: typing.Optional\[bool\] = Nonereturn\_overflowing\_tokens: bool = Falsereturn\_special\_tokens\_mask: bool = Falsereturn\_offsets\_mapping: bool = Falsereturn\_length: bool = Falseverbose: bool = True\*\*kwargs ) → [BatchEncoding](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.BatchEncoding)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences.

## [](#transformers.PerceiverFeatureExtractor)PerceiverFeatureExtractor

Preprocess an image or a batch of images.

## [](#transformers.PerceiverImageProcessor)PerceiverImageProcessor

### class transformers.PerceiverImageProcessor

[](#transformers.PerceiverImageProcessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/image_processing_perceiver.py#L44)

( do\_center\_crop: bool = Truecrop\_size: typing.Dict\[str, int\] = Nonedo\_resize: bool = Truesize: typing.Dict\[str, int\] = Noneresample: Resampling = <Resampling.BICUBIC: 3>do\_rescale: bool = Truerescale\_factor: typing.Union\[int, float\] = 0.00392156862745098do\_normalize: bool = Trueimage\_mean: typing.Union\[float, typing.List\[float\], NoneType\] = Noneimage\_std: typing.Union\[float, typing.List\[float\], NoneType\] = None\*\*kwargs )

Constructs a Perceiver image processor.

#### preprocess

[](#transformers.PerceiverImageProcessor.preprocess)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/image_processing_perceiver.py#L220)

( images: typing.Union\[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List\[ForwardRef('PIL.Image.Image')\], typing.List\[numpy.ndarray\], typing.List\[ForwardRef('torch.Tensor')\]\]do\_center\_crop: typing.Optional\[bool\] = Nonecrop\_size: typing.Union\[typing.Dict\[str, int\], NoneType\] = Nonedo\_resize: typing.Optional\[bool\] = Nonesize: typing.Union\[typing.Dict\[str, int\], NoneType\] = Noneresample: Resampling = Nonedo\_rescale: typing.Optional\[bool\] = Nonerescale\_factor: typing.Optional\[float\] = Nonedo\_normalize: typing.Optional\[bool\] = Noneimage\_mean: typing.Union\[float, typing.List\[float\], NoneType\] = Noneimage\_std: typing.Union\[float, typing.List\[float\], NoneType\] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = Nonedata\_format: ChannelDimension = <ChannelDimension.FIRST: 'channels\_first'>\*\*kwargs )

Preprocess an image or batch of images.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverTextPreprocessor)PerceiverTextPreprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverTextPreprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverTextPreprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2846)

( config: PerceiverConfig )

Text preprocessing for Perceiver Encoder. Can be used to embed `inputs` and add positional encodings.

The dimensionality of the embeddings is determined by the `d_model` attribute of the configuration.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor)PerceiverImagePreprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverImagePreprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L3003)

( configprep\_type = 'conv'spatial\_downsample: int = 4temporal\_downsample: int = 1position\_encoding\_type: str = 'fourier'in\_channels: int = 3out\_channels: int = 64conv\_after\_patching: bool = Falseconv\_after\_patching\_in\_channels: int = 54conv2d\_use\_batchnorm: bool = Trueconcat\_or\_add\_pos: str = 'concat'project\_pos\_dim: int = -1\*\*position\_encoding\_kwargs )

Image preprocessing for Perceiver Encoder.

Note: the _out\_channels_ argument refers to the output channels of a convolutional layer, if _prep\_type_ is set to “conv1x1” or “conv”. If one adds absolute position embeddings, one must make sure the _num\_channels_ of the position encoding kwargs are set equal to the _out\_channels_.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverOneHotPreprocessor)PerceiverOneHotPreprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverOneHotPreprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverOneHotPreprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L3232)

( config: PerceiverConfig )

One-hot preprocessor for Perceiver Encoder. Can be used to add a dummy index dimension to the input.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor)PerceiverAudioPreprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverAudioPreprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L3258)

( configprep\_type: str = 'patches'samples\_per\_patch: int = 96position\_encoding\_type: str = 'fourier'concat\_or\_add\_pos: str = 'concat'out\_channels = 64project\_pos\_dim = -1\*\*position\_encoding\_kwargs )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.config)**config** (\[_PerceiverConfig_\]) — Model configuration.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.prep_type)**prep\_type** (`str`, _optional_, defaults to `"patches"`) — Preprocessor type to use. Only “patches” is supported.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.samples_per_patch)**samples\_per\_patch** (`int`, _optional_, defaults to 96) — Number of samples per patch.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.position_encoding_type)**position\_encoding\_type** (`str`, _optional_, defaults to `"fourier"`) — Type of position encoding to use. Can be “trainable” or “fourier”.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.concat_or_add_pos)**concat\_or\_add\_pos** (`str`, _optional_, defaults to `"concat"`) — How to concatenate the position encoding to the input. Can be “concat” or “add”.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.out_channels)**out\_channels** (`int`, _optional_, defaults to 64) — Number of channels in the output.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.project_pos_dim)**project\_pos\_dim** (`int`, _optional_, defaults to -1) — Dimension of the position encoding to project to. If -1, no projection is applied.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPreprocessor.*position_encoding_kwargs)\***\*position\_encoding\_kwargs** (`Dict`, _optional_) — Keyword arguments for the position encoding.

Audio preprocessing for Perceiver Encoder.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor)PerceiverMultimodalPreprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverMultimodalPreprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L3355)

( modalities: typing.Mapping\[str, typing.Callable\[..., typing.Tuple\[torch.Tensor, typing.Optional\[torch.Tensor\], torch.Tensor\]\]\]mask\_probs: typing.Union\[typing.Mapping\[str, float\], NoneType\] = Nonemin\_padding\_size: int = 2 )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor.modalities)**modalities** (`Mapping[str, PreprocessorType]`) — Dict mapping modality name to preprocessor.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor.mask_probs)**mask\_probs** (`Dict[str, float]`) — Dict mapping modality name to masking probability of that modality.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor.min_padding_size)**min\_padding\_size** (`int`, _optional_, defaults to 2) — The minimum padding size for all modalities. The final output will have num\_channels equal to the maximum channels across all modalities plus min\_padding\_size.

Multimodal preprocessing for Perceiver Encoder.

Inputs for each modality are preprocessed, then padded with trainable position embeddings to have the same number of channels.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionDecoder)PerceiverProjectionDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverProjectionDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2051)

( config )

Baseline projection decoder (no cross-attention).

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicDecoder)PerceiverBasicDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverBasicDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2077)

( config: PerceiverConfigoutput\_num\_channels: intposition\_encoding\_type: typing.Optional\[str\] = 'trainable'output\_index\_dims: typing.Optional\[int\] = Nonenum\_channels: typing.Optional\[int\] = 128subsampled\_index\_dims: typing.Optional\[int\] = Noneqk\_channels: typing.Optional\[int\] = Nonev\_channels: typing.Optional\[int\] = Nonenum\_heads: typing.Optional\[int\] = 1widening\_factor: typing.Optional\[int\] = 1use\_query\_residual: typing.Optional\[bool\] = Falseconcat\_preprocessed\_input: typing.Optional\[bool\] = Falsefinal\_project: typing.Optional\[bool\] = Trueposition\_encoding\_only: typing.Optional\[bool\] = False\*\*position\_encoding\_kwargs )

Cross-attention-based decoder. This class can be used to decode the final hidden states of the latents using a cross-attention operation, in which the latents produce keys and values.

The shape of the output of this class depends on how one defines the output queries (also called decoder queries).

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder)PerceiverClassificationDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverClassificationDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2263)

( config\*\*decoder\_kwargs )

Cross-attention based classification decoder. Light-weight wrapper of `PerceiverBasicDecoder` for logit output. Will turn the output of the Perceiver encoder which is of shape (batch\_size, num\_latents, d\_latents) to a tensor of shape (batch\_size, num\_labels). The queries are of shape (batch\_size, 1, num\_labels).

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverOpticalFlowDecoder)PerceiverOpticalFlowDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverOpticalFlowDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverOpticalFlowDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2309)

( configoutput\_image\_shapeoutput\_num\_channels = 2rescale\_factor = 100.0\*\*decoder\_kwargs )

Cross-attention based optical flow decoder.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicVideoAutoencodingDecoder)PerceiverBasicVideoAutoencodingDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverBasicVideoAutoencodingDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicVideoAutoencodingDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2344)

( config: PerceiverConfigoutput\_shape: typing.List\[int\]position\_encoding\_type: str\*\*decoder\_kwargs )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicVideoAutoencodingDecoder.config)**config** (\[_PerceiverConfig_\]) — Model configuration.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicVideoAutoencodingDecoder.output_shape)**output\_shape** (`List[int]`) — Shape of the output as (batch\_size, num\_frames, height, width), excluding the channel dimension.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverBasicVideoAutoencodingDecoder.position_encoding_type)**position\_encoding\_type** (`str`) — The type of position encoding to use. Can be either “trainable”, “fourier”, or “none”.

Cross-attention based video-autoencoding decoder. Light-weight wrapper of \[_PerceiverBasicDecoder_\] with video reshaping logic.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder)PerceiverMultimodalDecoder

### class transformers.models.perceiver.modeling\_perceiver.PerceiverMultimodalDecoder

[](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2421)

( config: PerceiverConfigmodalities: typing.Dict\[str, transformers.models.perceiver.modeling\_perceiver.PerceiverAbstractDecoder\]num\_outputs: intoutput\_num\_channels: intmin\_padding\_size: typing.Optional\[int\] = 2subsampled\_index\_dims: typing.Union\[typing.Dict\[str, transformers.models.perceiver.modeling\_perceiver.PerceiverAbstractDecoder\], NoneType\] = None\*\*decoder\_kwargs )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.config)**config** (\[_PerceiverConfig_\]) — Model configuration.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.modalities)**modalities** (`Dict[str, PerceiverAbstractDecoder]`) — Dictionary mapping modality name to the decoder of that modality.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.num_outputs)**num\_outputs** (`int`) — The number of outputs of the decoder.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.output_num_channels)**output\_num\_channels** (`int`) — The number of channels in the output.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.min_padding_size)**min\_padding\_size** (`int`, _optional_, defaults to 2) — The minimum padding size for all modalities. The final output will have num\_channels equal to the maximum channels across all modalities plus min\_padding\_size.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder.subsampled_index_dims)**subsampled\_index\_dims** (`Dict[str, PerceiverAbstractDecoder]`, _optional_) — Dictionary mapping modality name to the subsampled index dimensions to use for the decoder query of that modality.

Multimodal decoding by composing uni-modal decoders. The _modalities_ argument of the constructor is a dictionary mapping modality name to the decoder of that modality. That decoder will be used to construct queries for that modality. Modality-specific queries are padded with trainable modality-specific parameters, after which they are concatenated along the time dimension.

Next, there is a shared cross attention operation across all modalities.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionPostprocessor)PerceiverProjectionPostprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverProjectionPostprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionPostprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2982)

( in\_channels: intout\_channels: int )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionPostprocessor.in_channels)**in\_channels** (`int`) — Number of channels in the input.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverProjectionPostprocessor.out_channels)**out\_channels** (`int`) — Number of channels in the output.

Projection postprocessing for Perceiver. Can be used to project the channels of the decoder output to a lower dimension.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPostprocessor)PerceiverAudioPostprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverAudioPostprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPostprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2955)

( config: PerceiverConfigin\_channels: intpostproc\_type: str = 'patches' )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPostprocessor.config)**config** (\[_PerceiverConfig_\]) — Model configuration.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPostprocessor.in_channels)**in\_channels** (`int`) — Number of channels in the input.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverAudioPostprocessor.postproc_type)**postproc\_type** (`str`, _optional_, defaults to `"patches"`) — Postprocessor type to use. Currently, only “patches” is supported.

Audio postprocessing for Perceiver. Can be used to convert the decoder output to audio features.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationPostprocessor)PerceiverClassificationPostprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverClassificationPostprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationPostprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2935)

( config: PerceiverConfigin\_channels: int )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationPostprocessor.config)**config** (\[_PerceiverConfig_\]) — Model configuration.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationPostprocessor.in_channels)**in\_channels** (`int`) — Number of channels in the input.

Classification postprocessing for Perceiver. Can be used to convert the decoder output to classification logits.

## [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPostprocessor)PerceiverMultimodalPostprocessor

### class transformers.models.perceiver.modeling\_perceiver.PerceiverMultimodalPostprocessor

[](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPostprocessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L2901)

( modalities: typing.Mapping\[str, typing.Callable\[..., typing.Any\]\]input\_is\_dict: bool = False )

Parameters

-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPostprocessor.modalities)**modalities** (`Mapping[str, PostprocessorType]`) — Dictionary mapping modality name to postprocessor class for that modality.
-   [](#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPostprocessor.input_is_dict)**input\_is\_dict** (`bool`, _optional_, defaults to `False`) — If True, input is assumed to be dictionary structured, and outputs keep the same dictionary shape. If False, input is a tensor which is sliced up during postprocessing by _modality\_sizes_.

Multimodal postprocessing for Perceiver. Can be used to combine modality-specific postprocessors into a single postprocessor.

## [](#transformers.PerceiverModel)PerceiverModel

### class transformers.PerceiverModel

[](#transformers.PerceiverModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L716)

( configdecoder = Noneinput\_preprocessor: typing.Callable\[..., typing.Tuple\[torch.Tensor, typing.Optional\[torch.Tensor\], torch.Tensor\]\] = Noneoutput\_postprocessor: typing.Callable\[..., typing.Any\] = None )

The Perceiver: a scalable, fully attentional architecture. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L752)

( inputs: FloatTensorattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonesubsampled\_output\_points: typing.Union\[typing.Dict\[str, torch.Tensor\], NoneType\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverModelOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverModelOutput) or `tuple(torch.FloatTensor)`

The [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverImageProcessor, PerceiverModel
>>> from transformers.models.perceiver.modeling_perceiver import (
...     PerceiverTextPreprocessor,
...     PerceiverImagePreprocessor,
...     PerceiverClassificationDecoder,
... )
>>> import torch
>>> import requests
>>> from PIL import Image

>>> 
>>> 
>>> 
>>> 
>>> 
>>> config = PerceiverConfig()
>>> preprocessor = PerceiverTextPreprocessor(config)
>>> decoder = PerceiverClassificationDecoder(
...     config,
...     num_channels=config.d_latents,
...     trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
...     use_query_residual=True,
... )
>>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)

>>> 
>>> tokenizer = PerceiverTokenizer()
>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids

>>> with torch.no_grad():
...     outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2]

>>> 
>>> criterion = torch.nn.CrossEntropyLoss()

>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)

>>> 
>>> 
>>> config = PerceiverConfig(image_size=224)
>>> preprocessor = PerceiverImagePreprocessor(
...     config,
...     prep_type="conv1x1",
...     spatial_downsample=1,
...     out_channels=256,
...     position_encoding_type="trainable",
...     concat_or_add_pos="concat",
...     project_pos_dim=256,
...     trainable_position_encoding_kwargs=dict(
...         num_channels=256,
...         index_dims=config.image_size**2,
...     ),
... )

>>> model = PerceiverModel(
...     config,
...     input_preprocessor=preprocessor,
...     decoder=PerceiverClassificationDecoder(
...         config,
...         num_channels=config.d_latents,
...         trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
...         use_query_residual=True,
...     ),
... )

>>> 
>>> image_processor = PerceiverImageProcessor()
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt").pixel_values

>>> with torch.no_grad():
...     outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2]

>>> 
>>> criterion = torch.nn.CrossEntropyLoss()

>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)```

## [](#transformers.PerceiverForMaskedLM)PerceiverForMaskedLM

### class transformers.PerceiverForMaskedLM

[](#transformers.PerceiverForMaskedLM)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L954)

( config: PerceiverConfig )

Parameters

-   [](#transformers.PerceiverForMaskedLM.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for masked language modeling. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForMaskedLM.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L986)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = Noneinput\_ids: typing.Optional\[torch.Tensor\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverMaskedLMOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverMaskedLMOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForMaskedLM](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForMaskedLM) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoTokenizer, PerceiverForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")

>>> 
>>> text = "This is an incomplete sentence where some words are missing."
>>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")
>>> 
>>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id
>>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids

>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
19.87

>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2048, 262]

>>> 
>>> text = "This is an incomplete sentence where some words are missing."
>>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")

>>> 
>>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id

>>> 
>>> with torch.no_grad():
...     outputs = model(**encoding)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2048, 262]

>>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()
>>> tokenizer.decode(masked_tokens_predictions)
' missing.'```

## [](#transformers.PerceiverForSequenceClassification)PerceiverForSequenceClassification

### class transformers.PerceiverForSequenceClassification

[](#transformers.PerceiverForSequenceClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1089)

( config )

Parameters

-   [](#transformers.PerceiverForSequenceClassification.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for text classification. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForSequenceClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1110)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = Noneinput\_ids: typing.Optional\[torch.Tensor\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForSequenceClassification) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoTokenizer, PerceiverForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")

>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2]```

## [](#transformers.PerceiverForImageClassificationLearned)PerceiverForImageClassificationLearned

### class transformers.PerceiverForImageClassificationLearned

[](#transformers.PerceiverForImageClassificationLearned)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1214)

( config )

Parameters

-   [](#transformers.PerceiverForImageClassificationLearned.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for image classification, for tasks such as ImageNet.

This model uses learned position embeddings. In other words, this model is not given any privileged information about the structure of images. As shown in the paper, this model can achieve a top-1 accuracy of 72.7 on ImageNet.

[PerceiverForImageClassificationLearned](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationLearned) uses [PerceiverImagePreprocessor](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor) (with `prep_type="conv1x1"`) to preprocess the input images, and [PerceiverClassificationDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder) to decode the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel) into classification logits.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForImageClassificationLearned.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1245)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = Nonepixel\_values: typing.Optional\[torch.Tensor\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForImageClassificationLearned](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationLearned) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoImageProcessor, PerceiverForImageClassificationLearned
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("deepmind/vision-perceiver-learned")
>>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")

>>> inputs = image_processor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 1000]

>>> 
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: tabby, tabby cat```

## [](#transformers.PerceiverForImageClassificationFourier)PerceiverForImageClassificationFourier

### class transformers.PerceiverForImageClassificationFourier

[](#transformers.PerceiverForImageClassificationFourier)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1357)

( config )

Parameters

-   [](#transformers.PerceiverForImageClassificationFourier.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for image classification, for tasks such as ImageNet.

This model uses fixed 2D Fourier position embeddings. As shown in the paper, this model can achieve a top-1 accuracy of 79.0 on ImageNet, and 84.5 when pre-trained on a large-scale dataset (i.e. JFT).

[PerceiverForImageClassificationLearned](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationLearned) uses [PerceiverImagePreprocessor](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor) (with `prep_type="pixels"`) to preprocess the input images, and [PerceiverClassificationDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder) to decode the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel) into classification logits.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForImageClassificationFourier.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1389)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = Nonepixel\_values: typing.Optional\[torch.Tensor\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForImageClassificationFourier](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationFourier) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoImageProcessor, PerceiverForImageClassificationFourier
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("deepmind/vision-perceiver-fourier")
>>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")

>>> inputs = image_processor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 1000]

>>> 
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: tabby, tabby cat```

## [](#transformers.PerceiverForImageClassificationConvProcessing)PerceiverForImageClassificationConvProcessing

### class transformers.PerceiverForImageClassificationConvProcessing

[](#transformers.PerceiverForImageClassificationConvProcessing)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1500)

( config )

Parameters

-   [](#transformers.PerceiverForImageClassificationConvProcessing.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for image classification, for tasks such as ImageNet.

This model uses a 2D conv+maxpool preprocessing network. As shown in the paper, this model can achieve a top-1 accuracy of 82.1 on ImageNet.

[PerceiverForImageClassificationLearned](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationLearned) uses [PerceiverImagePreprocessor](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor) (with `prep_type="conv"`) to preprocess the input images, and [PerceiverClassificationDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder) to decode the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel) into classification logits.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForImageClassificationConvProcessing.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1533)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = Nonepixel\_values: typing.Optional\[torch.Tensor\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForImageClassificationConvProcessing](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForImageClassificationConvProcessing) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoImageProcessor, PerceiverForImageClassificationConvProcessing
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("deepmind/vision-perceiver-conv")
>>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")

>>> inputs = image_processor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 1000]

>>> 
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: tabby, tabby cat```

## [](#transformers.PerceiverForOpticalFlow)PerceiverForOpticalFlow

### class transformers.PerceiverForOpticalFlow

[](#transformers.PerceiverForOpticalFlow)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1644)

( config )

Parameters

-   [](#transformers.PerceiverForOpticalFlow.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for optical flow, for tasks such as Sintel and KITTI. [PerceiverForOpticalFlow](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForOpticalFlow) uses [PerceiverImagePreprocessor](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor) (with _prep\_type=“patches”_) to preprocess the input images, and [PerceiverOpticalFlowDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverOpticalFlowDecoder) to decode the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel).

As input, one concatenates 2 subsequent frames along the channel dimension and extract a 3 x 3 patch around each pixel (leading to 3 x 3 x 3 x 2 = 54 values for each pixel). Fixed Fourier position encodings are used to encode the position of each pixel in the patch. Next, one applies the Perceiver encoder. To decode, one queries the latent representation using the same encoding used for the input.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForOpticalFlow.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1694)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForOpticalFlow](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForOpticalFlow) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import PerceiverForOpticalFlow
>>> import torch

>>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")

>>> 
>>> 
>>> 
>>> 
>>> patches = torch.randn(1, 2, 27, 368, 496)
>>> outputs = model(inputs=patches)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 368, 496, 2]```

## [](#transformers.PerceiverForMultimodalAutoencoding)PerceiverForMultimodalAutoencoding

### class transformers.PerceiverForMultimodalAutoencoding

[](#transformers.PerceiverForMultimodalAutoencoding)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1789)

( config: PerceiverConfig )

Parameters

-   [](#transformers.PerceiverForMultimodalAutoencoding.config)**config** ([PerceiverConfig](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Example use of Perceiver for multimodal (video) autoencoding, for tasks such as Kinetics-700.

[PerceiverForMultimodalAutoencoding](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForMultimodalAutoencoding) uses [PerceiverMultimodalPreprocessor](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor) to preprocess the 3 modalities: images, audio and class labels. This preprocessor uses modality-specific preprocessors to preprocess every modality separately, after which they are concatenated. Trainable position embeddings are used to pad each modality to the same number of channels to make concatenation along the time dimension possible. Next, one applies the Perceiver encoder.

[PerceiverMultimodalDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder) is used to decode the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel). This decoder uses each modality-specific decoder to construct queries. The decoder queries are created based on the inputs after preprocessing. However, autoencoding an entire video in a single forward pass is computationally infeasible, hence one only uses parts of the decoder queries to do cross-attention with the latent representation. This is determined by the subsampled indices for each modality, which can be provided as additional input to the forward pass of [PerceiverForMultimodalAutoencoding](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForMultimodalAutoencoding).

[PerceiverMultimodalDecoder](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder) also pads the decoder queries of the different modalities to the same number of channels, in order to concatenate them along the time dimension. Next, cross-attention is performed with the latent representation of [PerceiverModel](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverModel).

Finally, `~models.perceiver.modeling_perceiver.PerceiverMultiModalPostprocessor` is used to turn this tensor into an actual video. It first splits up the output into the different modalities, and then applies the respective postprocessor for each modality.

Note that, by masking the classification label during evaluation (i.e. simply providing a tensor of zeros for the “label” modality), this auto-encoding model becomes a Kinetics 700 video classifier.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.PerceiverForMultimodalAutoencoding.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/perceiver/modeling_perceiver.py#L1905)

( inputs: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonesubsampled\_output\_points: typing.Union\[typing.Dict\[str, torch.Tensor\], NoneType\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonelabels: typing.Optional\[torch.Tensor\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.perceiver.modeling\_perceiver.PerceiverClassifierOutput](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.models.perceiver.modeling_perceiver.PerceiverClassifierOutput) or `tuple(torch.FloatTensor)`

The [PerceiverForMultimodalAutoencoding](/docs/transformers/v4.30.0/en/model_doc/perceiver#transformers.PerceiverForMultimodalAutoencoding) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import PerceiverForMultimodalAutoencoding
>>> import torch
>>> import numpy as np

>>> 
>>> images = torch.randn((1, 16, 3, 224, 224))
>>> audio = torch.randn((1, 30720, 1))
>>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))

>>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")

>>> 
>>> 
>>> nchunks = 128
>>> image_chunk_size = np.prod((16, 224, 224)) // nchunks
>>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks
>>> 
>>> chunk_idx = 0
>>> subsampling = {
...     "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),
...     "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),
...     "label": None,
... }

>>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)
>>> logits = outputs.logits
>>> list(logits["audio"].shape)
[1, 240]

>>> list(logits["image"].shape)
[1, 6272, 3]

>>> list(logits["label"].shape)
[1, 700]```