FlavaConfig

ict, optional) —
Dictionary of configuration options used to initialize FlavaImageConfig.   multimodal_config (dict, optional) —
Dictionary of configuration options used to initialize FlavaMultimodalConfig.   hidden_size (int, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.   layer_norm_eps (float, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers.   projection_dim (int, optional, defaults to 512) —
Dimentionality of text and image projection layers.   logit_scale_init_value (float, optional, defaults to 2.6592) —
The inital value of the logit_scale paramter. Default is used as per the original FLAVA/CLIP
implementation.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   ce_ignore_index (int, optional, de


FlavaConfig

faults to -100) —
Cross entropy index to ignore.   mim_weight (float, optional, defaults to 1.0) —
Weight to be assigned to MIM (Masked Image Modeling) unimodal loss   mlm_weight (float, optional, defaults to 1.0) —
Weight to be assigned to MLM (Masked Language Modeling) unimodal loss   global_contrastive_weight (float, optional, defaults to 1.0) —
Weight to be assigned to global contrastive cross-alignment loss.   itm_weight (float, optional, defaults to 1.0) —
Weight to be assigned to image-text matching multimodal loss.   mmm_image_weight (float, optional, defaults to 1.0) —
Weight to be assigned to MMM loss’s image part.   mmm_text_weight (float, optional, defaults to 1.0) —
Weight to be assigned to MMM loss’s text part.   global_backprop_contrastive (bool, optional, defaults to True) —
Whether to use global backpropgation through all workers in contrastive loss.   skip_unmas


FlavaConfig

ked_multimodal_encoder (bool, optional, defaults to True) —
Whether to skip running unmasked multimodal encoder whose outputs are not used by FLAVA losses.   return_loss (bool, optional, defaults to True) —
Whether to return loss or not   kwargs (optional) —
Dictionary of keyword arguments.    FlavaConfig is the configuration class to store the configuration of a FlavaModel. It is used to
instantiate FLAVA model according to the specified arguments, defining the text model, image model, image codebook
and multimodal model configs. Instantiating a configuration with the defaults will yield a similar configuration to
that of the FLAVA facebook/flava-full architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import Flav


FlavaConfig

aConfig, FlavaModel, FlavaForPreTraining
>>> # Initializing a FlavaConfig with style configuration
>>> configuration = FlavaConfig()
>>> # Initializing a FlavaModel and FlavaForPreTraining model (with random weights) from the style configuration
>>> model = FlavaModel(configuration)
>>> model_pre = FlavaForPreTraining(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> configuration_pre = model_pre.config  from_configs  < source > ( image_config: FlavaImageConfig text_config: FlavaTextConfig multimodal_config: FlavaMultimodalConfig image_codebook_config: FlavaImageCodebookConfig **kwargs  ) → FlavaConfig  Returns
FlavaConfig

An instance of a configuration object
  Instantiate a FlavaConfig (or a derived class) from flava text model configuration, flava image model
configuration, flava multimodal model and flava codebook model configurat


FlavaTextConfig

class transformers.FlavaTextConfig  < source > ( vocab_size: int = 30522 type_vocab_size: int = 2 max_position_embeddings: int = 512 position_embedding_type: str = 'absolute' hidden_size: int = 768 num_hidden_layers: int = 12 num_attention_heads: int = 12 intermediate_size: int = 3072 hidden_act: str = 'gelu' hidden_dropout_prob: float = 0.0 attention_probs_dropout_prob: float = 0.0 initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 pad_token_id: int = 0 qkv_bias: bool = True **kwargs  )   Parameters   vocab_size (int, optional, defaults to 30522) —
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
inputs_ids passed when calling FlavaTextModel.   type_vocab_size (int, optional, defaults to 2) —
The vocabulary size of the token_type_ids passed when calling FlavaTextM


FlavaTextConfig

odel. Note that even though
text encoder allows token_type_ids’s value as 2, for text-only pretraining and fine-tuning, only 1 is
used similar to RoBERTa.   max_position_embeddings (int, optional, defaults to 512) —
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048). For VL, max_length passed to model is 77.   position_embedding_type (str, optional, defaults to "absolute") —
Type of position embedding. Choose one of "absolute", "relative_key", "relative_key_query". For
positional embeddings use "absolute". For more information on "relative_key", please refer to
Self-Attention with Relative Position Representations (Shaw et al.).
For more information on "relative_key_query", please refer to Method 4 in Improve Transformer Models
with Be


FlavaTextConfig

tter Relative Position Embeddings (Huang et al.).   hidden_size (int, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.   num_hidden_layers (int, optional, defaults to 12) —
Number of hidden layers in the Transformer encoder.   num_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder.   intermediate_size (int, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.   hidden_act (str or function, optional, defaults to "gelu") —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
"relu", "selu" and "gelu_new" are supported.   hidden_dropout_prob (float, optional, defaults to 0.1) —
The dropout probabilitiy f


FlavaTextConfig

or all fully connected layers in the embeddings, encoder, and pooler.   attention_probs_dropout_prob (float, optional, defaults to 0.1) —
The dropout ratio for the attention probabilities.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   layer_norm_eps (float, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers.   image_size (int, optional, defaults to 224) —
The size (resolution) of each image.   patch_size (int, optional, defaults to 16) —
The size (resolution) of each patch.   num_channels (int, optional, defaults to 3) —
The number of input channels.   qkv_bias (bool, optional, defaults to True) —
Whether to add a bias to the queries, keys and values.    This is the configuration class to st


FlavaTextConfig

ore the configuration of a FlavaTextModel. It is used to instantiate an
FLAVA 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 FLAVA
facebook/flava-full architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import FlavaTextConfig, FlavaTextModel
>>> # Initializing a FlavaTextModel with  style configuration
>>> configuration = FlavaTextConfig()
>>> # Initializing a FlavaTextModel model (with random weights) from the style configuration
>>> model = FlavaTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.con


FlavaImageConfig

class transformers.FlavaImageConfig  < source > ( hidden_size: int = 768 num_hidden_layers: int = 12 num_attention_heads: int = 12 intermediate_size: int = 3072 hidden_act: int = 'gelu' hidden_dropout_prob: float = 0.0 attention_probs_dropout_prob: float = 0.0 initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 image_size: int = 224 patch_size: int = 16 num_channels: int = 3 qkv_bias: bool = True mask_token: bool = True vocab_size: int = 8192 **kwargs  )   Parameters   hidden_size (int, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.   num_hidden_layers (int, optional, defaults to 12) —
Number of hidden layers in the Transformer encoder.   num_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer


FlavaImageConfig

 encoder.   intermediate_size (int, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.   hidden_act (str or function, optional, defaults to "gelu") —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
"relu", "selu" and "gelu_new" are supported.   hidden_dropout_prob (float, optional, defaults to 0.0) —
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.   attention_probs_dropout_prob (float, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   layer_norm_eps (float,


FlavaImageConfig

 optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers.   image_size (int, optional, defaults to 224) —
The size (resolution) of each image.   patch_size (int, optional, defaults to 16) —
The size (resolution) of each patch.   num_channels (int, optional, defaults to 3) —
The number of input channels.   qkv_bias (bool, optional, defaults to True) —
Whether to add a bias to the queries, keys and values.   mask_token (bool, optional, defaults to True) —
Whether to use a mask token or not. Used in MIM (Masked Image Modeling) loss for FLAVA.   vocab_size (int, optional, defaults to 8192) —
Vocabulary size of the FlavaImageCodebook used in conjunction with FlavaImageModel for MIM (Masked
Image Modeling) loss for FLAVA.    This is the configuration class to store the configuration of a Fl


FlavaImageConfig

avaImageModel. It is used to instantiate an
FLAVA 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 FLAVA
facebook/flava-full architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import FlavaImageConfig, FlavaImageModel
>>> # Initializing a FlavaImageModel with  style configuration
>>> configuration = FlavaImageConfig()
>>> # Initializing a FlavaImageModel model (with random weights) from the style configuration
>>> model = FlavaImageModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.conf


FlavaMultimodalConfig

class transformers.FlavaMultimodalConfig  < source > ( hidden_size: int = 768 num_hidden_layers: int = 6 num_attention_heads: int = 12 intermediate_size: int = 3072 hidden_act: int = 'gelu' hidden_dropout_prob: int = 0.0 attention_probs_dropout_prob: int = 0.0 initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 qkv_bias: bool = True use_cls_token: bool = True **kwargs  )   Parameters   hidden_size (int, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.   num_hidden_layers (int, optional, defaults to 6) —
Number of hidden layers in the Transformer encoder.   num_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder.   intermediate_size (int, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.   hidden_act (str or function, optional, defau


FlavaMultimodalConfig

lts to "gelu") —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
"relu", "selu" and "gelu_new" are supported.   hidden_dropout_prob (float, optional, defaults to 0.0) —
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.   attention_probs_dropout_prob (float, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   layer_norm_eps (float, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers.   qkv_bias (bool, optional, defaults to True) —
Whether to add a bias to the queries, keys and values.   use_cls_token (bool, optional, defaults to True) —
Whether to use an extra CLS token for multimodal settings. Usually needed by the F


FlavaMultimodalConfig

LAVA model.    This is the configuration class to store the configuration of a FlavaMultimodalModel. It is used to instantiate
an FLAVA 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 FLAVA
facebook/flava-full architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import FlavaMultimodalConfig, FlavaMultimodalModel
>>> # Initializing a FlavaMultimodalModel with  style configuration
>>> configuration = FlavaMultimodalConfig()
>>> # Initializing a FlavaMultimodalModel model (with random weights) from the style configuration
>>> model = FlavaMultimodalModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config


FlavaImageCodebookConfig

class transformers.FlavaImageCodebookConfig  < source > ( num_groups: int = 4 input_channels: int = 3 num_blocks_per_group: int = 2 hidden_size: int = 256 vocab_size: int = 8192 freeze: int = True initializer_range: float = 0.02 **kwargs  )


FlavaProcessor

class transformers.FlavaProcessor  < source > ( image_processor = None tokenizer = None **kwargs  )   Parameters   image_processor (FlavaImageProcessor, optional) — The image processor is a required input.   tokenizer (BertTokenizerFast, optional) — The tokenizer is a required input.    Constructs a FLAVA processor which wraps a FLAVA image processor and a FLAVA tokenizer into a single processor. FlavaProcessor offers all the functionalities of FlavaImageProcessor and BertTokenizerFast. See the
__call__() and decode() for more information.  batch_decode  < source > ( *args **kwargs  )    This method forwards all its arguments to BertTokenizerFast’s batch_decode(). Please
refer to the docstring of this method for more information.  decode  < source > ( *args **kwargs  )    This method forwards all its arguments to BertTokenizerFast’s decode(). Please refer to
the docstring of this method for more information.


FlavaImageProcessor

class transformers.FlavaImageProcessor  < source > ( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.Iterable[float], NoneType] = None image_std: typing.Union[float, typing.Iterable[float], NoneType] = None return_image_mask: bool = False input_size_patches: int = 14 total_mask_patches: int = 75 mask_group_min_patches: int = 16 mask_group_max_patches: typing.Optional[int] = None mask_group_min_aspect_ratio: float = 0.3 mask_group_max_aspect_ratio: typing.Optional[float] = None return_codebook_pixels: bool = False codebook_do_resize: bool = True codebook_size: bool = None codebook_resample: int = <Resampling.LANCZOS: 1> codebook_do_center_crop: bool = True codebook_crop_size: int = None


FlavaImageProcessor

codebook_do_rescale: bool = True codebook_rescale_factor: typing.Union[int, float] = 0.00392156862745098 codebook_do_map_pixels: bool = True codebook_do_normalize: bool = True codebook_image_mean: typing.Union[float, typing.Iterable[float], NoneType] = None codebook_image_std: typing.Union[float, typing.Iterable[float], NoneType] = None **kwargs  )   Parameters   do_resize (bool, optional, defaults to True) —
Whether to resize the image’s (height, width) dimensions to the specified size. Can be overridden by the
do_resize parameter in preprocess.   size (Dict[str, int] optional, defaults to {"height" -- 224, "width": 224}):
Size of the image after resizing. Can be overridden by the size parameter in preprocess.   resample (PILImageResampling, optional, defaults to PILImageResampling.BICUBIC) —
Resampling filter to use if resizing the image. Can be overridden by the resample parameter in
preprocess.   do_center_crop (bool, optional, defaults to True) —
Whethe


FlavaImageProcessor

r to center crop the images. Can be overridden by the do_center_crop parameter in preprocess.   crop_size (Dict[str, int] optional, defaults to {"height" -- 224, "width": 224}):
Size of image after the center crop (crop_size["height"], crop_size["width"]). Can be overridden by the
crop_size parameter in preprocess.   do_rescale (bool, optional, defaults to True) —
Whether to rescale the image by the specified scale rescale_factor. Can be overridden by the do_rescale
parameter in preprocess.   rescale_factor (int or float, optional, defaults to 1/255) —
Scale factor to use if rescaling the image. Can be overridden by the rescale_factor parameter in
preprocess.   do_normalize (bool, optional, defaults to True) —
Whether to normalize the image. Can be overridden by the do_normalize parameter in preprocess.   image_mean (float or List[float], optional, defaults to IMAGENET_STANDARD_MEAN) —
Mean to use if normalizing the image. This is a float or list of floats t


FlavaImageProcessor

he length of the number of
channels in the image. Can be overridden by the image_mean parameter in the preprocess method.   image_std (float or List[float], optional, defaults to IMAGENET_STANDARD_STD) —
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the image_std parameter in the preprocess method.   return_image_mask (bool, optional, defaults to False) —
Whether to return the image mask. Can be overridden by the return_image_mask parameter in preprocess.   input_size_patches (int, optional, defaults to 14) —
Number of patches in the image in height and width direction. 14x14 = 196 total patches. Can be overridden
by the input_size_patches parameter in preprocess.   total_mask_patches (int, optional, defaults to 75) —
Total number of patches that should be masked. Can be overridden by the total_mask_patches parameter in
preprocess.   mask_group_min


FlavaImageProcessor

_patches (int, optional, defaults to 16) —
Minimum number of patches that should be masked. Can be overridden by the mask_group_min_patches
parameter in preprocess.   mask_group_max_patches (int, optional) —
Maximum number of patches that should be masked. Can be overridden by the mask_group_max_patches
parameter in preprocess.   mask_group_min_aspect_ratio (float, optional, defaults to 0.3) —
Minimum aspect ratio of the mask window. Can be overridden by the mask_group_min_aspect_ratio parameter
in preprocess.   mask_group_max_aspect_ratio (float, optional) —
Maximum aspect ratio of the mask window. Can be overridden by the mask_group_max_aspect_ratio parameter
in preprocess.   codebook_do_resize (bool, optional, defaults to True) —
Whether to resize the input for codebook to a certain. Can be overridden by the codebook_do_resize
parameter in preprocess. codebook_size.   codebook_size (Dict[str, int], optional, defaults to {"height" -- 224, "width": 224}):
R


FlavaImageProcessor

esize the input for codebook to the given size. Can be overridden by the codebook_size parameter in
preprocess.   codebook_resample (PILImageResampling, optional, defaults to PILImageResampling.LANCZOS) —
Resampling filter to use if resizing the codebook image. Can be overridden by the codebook_resample
parameter in preprocess.   codebook_do_center_crop (bool, optional, defaults to True) —
Whether to crop the input for codebook at the center. If the input size is smaller than
codebook_crop_size along any edge, the image is padded with 0’s and then center cropped. Can be
overridden by the codebook_do_center_crop parameter in preprocess.   codebook_crop_size (Dict[str, int], optional, defaults to {"height" -- 224, "width": 224}):
Desired output size for codebook input when applying center-cropping. Can be overridden by the
codebook_crop_size parameter in preprocess.   codebook_do_rescale (bool, optional, defaults to True) —
Whether to rescale the input for cod


FlavaImageProcessor

ebook by the specified scale codebook_rescale_factor. Can be
overridden by the codebook_do_rescale parameter in preprocess.   codebook_rescale_factor (int or float, optional, defaults to 1/255) —
Defines the scale factor to use if rescaling the codebook image. Can be overridden by the
codebook_rescale_factor parameter in preprocess.   codebook_do_map_pixels (bool, optional, defaults to True) —
Whether to map the pixel values of the codebook input to (1 - 2e)x + e. Can be overridden by the
codebook_do_map_pixels parameter in preprocess.   codebook_do_normalize (bool, optional, defaults to True) —
Whether or not to normalize the input for codebook with codebook_image_mean and codebook_image_std. Can
be overridden by the codebook_do_normalize parameter in preprocess.   codebook_image_mean (Optional[Union[float, Iterable[float]]], optional, defaults to [0, 0, 0]) —
The sequence of means for each channel, to be used when normalizing images for codebook. Can be ov


FlavaImageProcessor

erridden
by the codebook_image_mean parameter in preprocess.   codebook_image_std (Optional[Union[float, Iterable[float]]], optional, defaults to [0.5, 0.5, 0.5]) —
The sequence of standard deviations for each channel, to be used when normalizing images for codebook. Can
be overridden by the codebook_image_std parameter in preprocess.    Constructs a Flava image processor.  preprocess  < source > ( 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_resize: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Union[typing.Dict[str, int], NoneType] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.U


FlavaImageProcessor

nion[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_image_mask: typing.Optional[bool] = None input_size_patches: typing.Optional[int] = None total_mask_patches: typing.Optional[int] = None mask_group_min_patches: typing.Optional[int] = None mask_group_max_patches: typing.Optional[int] = None mask_group_min_aspect_ratio: typing.Optional[float] = None mask_group_max_aspect_ratio: typing.Optional[float] = None return_codebook_pixels: typing.Optional[bool] = None codebook_do_resize: typing.Optional[bool] = None codebook_size: typing.Union[typing.Dict[str, int], NoneType] = None codebook_resample: typing.Optional[int] = None codebook_do_center_crop: typing.Optional[bool] = None codebook_crop_size: typing.Union[typing.Dict[str, int], NoneType] = None codebook_do_rescale: typing.Optional[bool] = None codebook_rescale_factor: typing.Optional[float] = None codebook_do_map_pixels: typing.Optional[


FlavaImageProcessor

bool] = None codebook_do_normalize: typing.Optional[bool] = None codebook_image_mean: typing.Optional[typing.Iterable[float]] = None codebook_image_std: typing.Optional[typing.Iterable[float]] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs  )   Parameters   images (ImageInput) —
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set do_rescale=False.   do_resize (bool, optional, defaults to self.do_resize) —
Whether to resize the image.   size (Dict[str, int], optional, defaults to self.size) —
Size of the image.   resample (int, optional, defaults to self.resample) —
Resampling filter to use if resizing the image. This can be one


FlavaImageProcessor

 of the enum PILImageResampling, Only
has an effect if do_resize is set to True.   do_center_crop (bool, optional, defaults to self.do_center_crop) —
Whether to center crop the image.   crop_size (Dict[str, int], optional, defaults to self.crop_size) —
Size of the center crop. Only has an effect if do_center_crop is set to True.   do_rescale (bool, optional, defaults to self.do_rescale) —
Whether to rescale the image values between [0 - 1].   rescale_factor (float, optional, defaults to self.rescale_factor) —
Rescale factor to rescale the image by if do_rescale is set to True.   do_normalize (bool, optional, defaults to self.do_normalize) —
Whether to normalize the image.   image_mean (float or List[float], optional, defaults to self.image_mean) —
Image mean.   image_std (float or List[float], optional, defaults to self.image_std) —
Image standard deviation.   return_image_mask (bool, optional, defaults to self.return_image_mask) —
Whether to return the imag


FlavaImageProcessor

e mask.   input_size_patches (int, optional, defaults to self.input_size_patches) —
Size of the patches to extract from the image.   total_mask_patches (int, optional, defaults to self.total_mask_patches) —
Total number of patches to extract from the image.   mask_group_min_patches (int, optional, defaults to self.mask_group_min_patches) —
Minimum number of patches to extract from the image.   mask_group_max_patches (int, optional, defaults to self.mask_group_max_patches) —
Maximum number of patches to extract from the image.   mask_group_min_aspect_ratio (float, optional, defaults to self.mask_group_min_aspect_ratio) —
Minimum aspect ratio of the patches to extract from the image.   mask_group_max_aspect_ratio (float, optional, defaults to self.mask_group_max_aspect_ratio) —
Maximum aspect ratio of the patches to extract from the image.   return_codebook_pixels (bool, optional, defaults to self.return_codebook_pixels) —
Whether to return the codebook pixels


FlavaImageProcessor

.   codebook_do_resize (bool, optional, defaults to self.codebook_do_resize) —
Whether to resize the codebook pixels.   codebook_size (Dict[str, int], optional, defaults to self.codebook_size) —
Size of the codebook pixels.   codebook_resample (int, optional, defaults to self.codebook_resample) —
Resampling filter to use if resizing the codebook pixels. This can be one of the enum
PILImageResampling, Only has an effect if codebook_do_resize is set to True.   codebook_do_center_crop (bool, optional, defaults to self.codebook_do_center_crop) —
Whether to center crop the codebook pixels.   codebook_crop_size (Dict[str, int], optional, defaults to self.codebook_crop_size) —
Size of the center crop of the codebook pixels. Only has an effect if codebook_do_center_crop is set
to True.   codebook_do_rescale (bool, optional, defaults to self.codebook_do_rescale) —
Whether to rescale the codebook pixels values between [0 - 1].   codebook_rescale_factor (float, optiona


FlavaImageProcessor

l, defaults to self.codebook_rescale_factor) —
Rescale factor to rescale the codebook pixels by if codebook_do_rescale is set to True.   codebook_do_map_pixels (bool, optional, defaults to self.codebook_do_map_pixels) —
Whether to map the codebook pixels values.   codebook_do_normalize (bool, optional, defaults to self.codebook_do_normalize) —
Whether to normalize the codebook pixels.   codebook_image_mean (float or List[float], optional, defaults to self.codebook_image_mean) —
Codebook pixels mean to normalize the codebook pixels by if codebook_do_normalize is set to True.   codebook_image_std (float or List[float], optional, defaults to self.codebook_image_std) —
Codebook pixels standard deviation to normalize the codebook pixels by if codebook_do_normalize is
set to True.   return_tensors (str or TensorType, optional) —
The type of tensors to return. Can be one of:
Unset: Return a list of np.ndarray.
TensorType.TENSORFLOW or 'tf': Return a batch of type t


FlavaImageProcessor

f.Tensor.
TensorType.PYTORCH or 'pt': Return a batch of type torch.Tensor.
TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.
   data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) —
The channel dimension format for the output image. Can be one of:
ChannelDimension.FIRST: image in (num_channels, height, width) format.
ChannelDimension.LAST: image in (height, width, num_channels) format.
   input_data_format (ChannelDimension or str, optional) —
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
"channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
"channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
"none" or ChannelDimension.NONE: image in (height, width) format.
    Preprocess an image or bat


FlavaForPreTraining

class transformers.FlavaForPreTraining  < source > ( config: FlavaConfig image_codebook: typing.Optional[torch.nn.modules.module.Module] = None  )   Parameters   config (FlavaConfig) — 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() method to load the model weights.   image_codebook (nn.Module) — If passed, the image codebook will be set to this. Otherwise. it will
be initialized using the image_codebook_config defined in the config first as the first parameter.    The FLAVA model for pretraining which outputs losses, embeddings, logits and transformer outputs. This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( input_ids: typing.Optional[torch.LongTensor] = None input


FlavaForPreTraining

_ids_masked: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None codebook_pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None image_attention_mask: typing.Optional[torch.Tensor] = None skip_unmasked_multimodal_encoder: bool = None mlm_labels: typing.Optional[torch.Tensor] = None mim_labels: typing.Optional[torch.Tensor] = None itm_labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: bool = True return_dict: typing.Optional[bool] = None return_loss: typing.Optional[bool] = None  ) → transformers.models.flava.modeling_flava.FlavaForPreTrainingOutput or tuple(torch.FloatTensor)  Parameters   input_ids_masked (torch.LongTensor of shape (batch_size, text


FlavaForPreTraining

_seq_len)) —
Indices of input sequence tokens in the vocabulary. These ones are the masked version of the original task
to be used with MLM. Indices can be obtained using AutoTokenizer along with
DataCollatorForMaskedLanguageModeling. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details. What are input IDs?   input_ids (torch.LongTensor of shape (batch_size, text_seq_len)) —
Indices of input sequence tokens in the vocabulary. Indices can be obtained using AutoTokenizer. See
PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input
IDs?   token_type_ids (torch.LongTensor of shape (batch_size, text_seq_len), optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
What are token type IDs?
   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel val


FlavaForPreTraining

ues. Pixel values can be obtained using AutoImageProcessor. See
FlavaImageProcessor.call() for details.   bool_masked_pos (torch.BoolTensor of shape (batch_size, image_num_patches)) —
Boolean masked positions. Indicates which patches are masked (1) and which aren’t (0).   interpolate_pos_encoding (bool, optional) —
Whether to interpolate the pre-trained position encodings.   image_attention_mask (torch.FloatTensor of shape (batch_size, image_num_patches), optional) —
Mask to avoid performing attention on padding token indices specifically for images. Mask values selected
in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   skip_unmasked_multimodal_encoder (bool, optional) —
Skip any calculations for multimodal encoder for unmasked inputs. FLAVA pretraining doesn’t need unmasked
multimodal embeddings or outputs as of now.   mlm_labels (torch.LongTensor of shape (batch_size, text_seq_len), optional) —
Labels for computin


FlavaForPreTraining

g the left-to-right language and multimodal masked modeling loss (next word prediction).
Indices should be in [-100, 0, ..., text_config.vocab_size - 1] (see input_ids docstring). Tokens with
indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., text_config.vocab_size - 1].   mim_labels (torch.LongTensor of shape (batch_size, image_num_patches), optional) —
Labels for computing the image and multimodal masked modeling loss. Indices should be in [-100, 0, ..., image_config.vocab_size - 1]. Tokens with indices set to -100 are ignored (masked), the loss is only
computed for the tokens with labels in [0, ..., image_config.vocab_size - 1]. If not passed, they are
generated automatically using the image codebook assigned to the model. By default, it uses
FlavaImageCodebook. See FlavaImageCodebook to understand how to generate mim_labels.   itm_labels (torch.LongTensor of shape (batch_size, 1), optional) —
Labels for comput


FlavaForPreTraining

ing the image-text matching loss. 0 means the pairs don’t match and 1 means they match.
The pairs with 0 will be skipped for calculation of MMM and global contrastive losses as well.   return_loss (bool, optional, default to None) —
Whether to return calculated loss or not.   attention_mask (torch.FloatTensor of shape (batch_size, text_seq_len), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_


FlavaForPreTraining

states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.
Examples —   Returns
transformers.models.flava.modeling_flava.FlavaForPreTrainingOutput or tuple(torch.FloatTensor)

A transformers.models.flava.modeling_flava.FlavaForPreTrainingOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (<class 'transformers.models.flava.configuration_flava.FlavaConfig'>) and inputs.
loss (torch.FloatTensor, optional, returned when return_loss is True) — Total loss calculated for this model.
loss_info (FlavaLosses) — Detailed info for FLAVA Pretraining losses. Check FlavaLosses class description for the information on
the keys.
image_embeddings (torch.FloatTensor of shape (batch_size, output_d


FlavaForPreTraining

im), optional, returned when pixel_values are present) — The image embeddings which are basically the pooled output of FlavaImageModel.
image_output (BaseModelOutputWithPooling, optional, returned when pixel_values are present) — The output of the FlavaImageModel.
text_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids are present) — The text embeddings which are basically the pooled output of FlavaTextModel.
text_output (BaseModelOutputWithPooling, optional, returned when input_ids are present) — The output of the FlavaTextModel.
multimodal_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids and pixel_values are present and skip_unmasked_multimodal_encoder is None or False) — The multimodal embeddings which are basically the pooled output of FlavaTextModel.
multimodal_output (BaseModelOutputWithPooling, returned when input_ids and pixel_values are present and skip_unmasked_m


FlavaForPreTraining

ultimodal_encoder is None or False) — The output of the FlavaMultimodalModel.
image_masked_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when pixel_values are present) — The image embeddings which are basically the pooled output of FlavaImageModel. Uses bool_masked_pos
to create masked images.
image_masked_output (BaseModelOutputWithPooling, optional, returned when pixel_values are present) — The output of the FlavaImageModel. Uses bool_masked_pos to create masked images.
text_masked_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids_masked are present) — The text embeddings which are basically the pooled output of FlavaTextModel.
text_masked_output (BaseModelOutputWithPooling, optional, returned when input_ids_masked are present) — The output of the FlavaTextModel.
multimodal_masked_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids and


FlavaForPreTraining

 pixel_values are present) — The multimodal embeddings which are basically the pooled output of FlavaTextModel.
multimodal_masked_output (BaseModelOutputWithPooling, returned when input_ids_masked and pixel_values are present) — The output of the FlavaMultimodalModel.
mim_logits (torch.FloatTensor of shape (batch_size, num_image_patches, image_vocab_size) or of shape (total_masked_patches, image_vocab_size) , optional, returned when pixel_values are present and input_ids_masked are not) — The logits for MIM unimodal loss. Uses book_masked_pos to get masked patches. The flattened output is
returned when bool_masked_pos has some of the patches masked.
mlm_logits (torch.FloatTensor of shape (batch_size, text_seq_length, text_vocab_size) or of shape (total_masked_seq_length, text_vocab_size), optional, returned when input_ids_masked are present and pixel_values are not) — The logits for MLM unimodal loss. The flattened output is returned when input_ids_masked has some of
t


FlavaForPreTraining

he tokens masked.
itm_logits (torch.FloatTensor of shape (batch_size, 2), optional, returned when input_ids_masked and pixel_values are present) — The logits for ITM loss. Note that ITM loss is calculated on masked pairs in FLAVA.
mmm_image_logits (torch.FloatTensor of shape (batch_size, num_image_patches, image_vocab_size) or of shape(total_masked_patches, image_vocab_size), optional, returned when pixel_values and input_ids_masked are present) — The logits for MMM image multimodal loss. Uses book_masked_pos to get masked patches. The flattened
output is returned when bool_masked_pos has some of the patches masked.
mmm_text_logits (torch.FloatTensor of shape (batch_size, text_seq_length, text_vocab_size) or of shape ((total_masked_seq_length, text_vocab_size)), *optional*, returned when pixel_valuesandinput_ids_maskedare present) -- The logits for MMM text multimodal loss. The flattened output is returned wheninput_ids_masked` has
some of the tokens masked.
contrastiv


FlavaForPreTraining

e_logits_per_image (torch.FloatTensor of shape (image_batch_size, text_batch_size)) — The scaled dot product scores between image_embeddings and text_embeddings but passed through FLAVA’s
image_projection and text_projection layers respectively. This represents the image-text similarity
scores. This is calculated on unmasked images and texts.
contrastive_logits_per_text (torch.FloatTensor of shape (text_batch_size, image_batch_size)) — The scaled dot product scores between text_embeddings and image_embeddings but passed through FLAVA’s
text_projection and image_projection layers respectively. This is calculated on unmasked images and
texts.
  The FlavaForPreTraining 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


FlavaModel

class transformers.FlavaModel  < source > ( config: FlavaConfig  )   Parameters   config (FlavaConfig) — 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() method to load the model weights.    The bare FLAVA Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Long


FlavaModel

Tensor] = None image_attention_mask: typing.Optional[torch.Tensor] = None skip_multimodal_encoder: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: bool = True return_dict: typing.Optional[bool] = None  ) → transformers.models.flava.modeling_flava.FlavaModelOutput or tuple(torch.FloatTensor)  Parameters   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
FlavaImageProcessor.call() for details.   bool_masked_pos (torch.BoolTensor of shape (batch_size, image_num_patches)) —
Boolean masked positions. Indicates which patches are masked (1) and which aren’t (0).   interpolate_pos_encoding (bool, optional) —
Whether to interpolate the pre-trained position encodings.   input_ids (torch.LongTensor of shape (batch_size, image_num_patches + text_seq_len)) —
Indices of input sequence tokens in


FlavaModel

 the vocabulary. Indices can be obtained using AutoTokenizer. See
PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input
IDs?   token_type_ids (torch.LongTensor of shape (batch_size, image_num_patches + text_seq_len), optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
What are token type IDs?
   attention_mask (torch.FloatTensor of shape (batch_size, image_num_patches + text_seq_len), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indi


FlavaModel

cates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   skip_multimodal_encoder (bool, optional) —
Skip any calculations for multimodal encoder. Useful if multimodal encoding is not going to be used.   Returns
transformers.models.flava.modeling_flava.FlavaModelOutput or tuple(torch.FloatTensor)

A transformers.models.flava.modeling_flava.FlavaModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (<c


FlavaModel

lass 'transformers.models.flava.configuration_flava.FlavaConfig'>) and inputs.
image_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when pixel_values are present) — The image embeddings which are basically the pooled output of FlavaImageModel.
image_output (BaseModelOutputWithPooling, optional, returned when pixel_values are present) — The output of the FlavaImageModel.
text_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids are present) — The text embeddings which are basically the pooled output of FlavaTextModel.
text_output (BaseModelOutputWithPooling, optional, returned when input_ids are present) — The output of the FlavaTextModel.
multimodal_embeddings (torch.FloatTensor of shape (batch_size, output_dim), optional, returned when input_ids and pixel_values are present and skip_multimodal_encoder is None or False) — The multimodal embeddings which are


FlavaModel

 basically the pooled output of FlavaTextModel.
multimodal_output (BaseModelOutputWithPooling, returned when input_ids and pixel_values are present and skip_multimodal_encoder is None or False) — The output of the FlavaMultimodalModel.
  The FlavaModel 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:   Copied >>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, FlavaModel
>>> model = FlavaModel.from_pretrained("facebook/flava-full")
>>> processor = AutoProcessor.from_pretrained("facebook/flava-full")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs


FlavaModel

= processor(text=["a photo of a cat"], images=image, return_tensors="pt", padding=True)
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.contrastive_logits_per_image  # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities  get_text_features  < source > ( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  )   Parameters   input_ids (torch.LongTensor of shape (batch_size, text_seq_length)) —
Indices of input sequence tokens in the vocabulary. Indices can be obtained using AutoTokenizer. See
PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() f


FlavaModel

or details. What are input
IDs?   token_type_ids (torch.LongTensor of shape (batch_size, text_seq_length), optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
What are token type IDs?
   attention_mask (torch.FloatTensor of shape (batch_size, text_seq_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all atte


FlavaModel

ntion layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.    The FlavaModel 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.  get_image_features  < source > ( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None interpolate_pos_encoding: typing.Optional[bool] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None


FlavaModel

output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  )   Parameters   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
FlavaImageProcessor.call() for details.   bool_masked_pos (torch.BoolTensor of shape (batch_size, image_num_patches)) —
Boolean masked positions. Indicates which patches are masked (1) and which aren’t (0).   interpolate_pos_encoding (bool, optional) —
Whether to interpolate the pre-trained position encodings.   attention_mask (torch.FloatTensor of shape (batch_size, image_num_patches), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_hea


FlavaModel

ds,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.    The FlavaModel 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


FlavaImageCodebook

class transformers.FlavaImageCodebook  < source > ( config: FlavaImageCodebookConfig **kwargs: typing.Any  )   Parameters   config (FlavaImageCodebookConfig) — 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() method to load the model weights.    The FLAVA’s image codebook model inspired from DALL-E’s original encoder. Outputs raw hidden states and can be


FlavaImageCodebook

used
to generate image tokens for an image based on DALL-E’s vocab. Used to generate labels for MIM. Use
get_codebook_indices to get image tokens for an image. This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( pixel_values: FloatTensor  )     get_codebook_indices  < source > ( pixel_values: Tensor  )     get_codebook_probs  < source > ( pixel_values: Tensor  )


FlavaTextModel

class transformers.FlavaTextModel  < source > ( config: FlavaTextConfig add_pooling_layer: bool = True  )   Parameters   config (FlavaTextConfig) — 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() method to load the model weights.    The bare FLAVA Text Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Op


FlavaTextModel

tional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, text_seq_length)) —
Indices of input sequence tokens in the vocabulary. Indices can be obtained using AutoTokenizer. See
PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input
IDs?   token_type_ids (torch.LongTensor of shape (batch_size, text_seq_length), optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
What are token t


FlavaTextModel

ype IDs?
   attention_mask (torch.FloatTensor of shape (batch_size, text_seq_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   retu


FlavaTextModel

rn_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (FlavaTextConfig) and inputs.
last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.
pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) — Last layer hidden-state of the first token of the sequence (classification token) after further processing
through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models


FlavaTextModel

, this returns
the classification token after processing through a linear layer and a tanh activation function. The linear
layer weights are trained from the next sentence prediction (classification) objective during pretraining.
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
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_si


FlavaTextModel

ze, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The FlavaTextModel 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.  Example:   Copied >>> from transformers import AutoTokenizer, FlavaTextModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/flava-full")
>>> model = FlavaTextModel.from_pretrained("facebook/flava-full")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_


FlavaImageModel

class transformers.FlavaImageModel  < source > ( config: FlavaImageConfig add_pooling_layer: bool = True  )   Parameters   config (FlavaImageConfig) — 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() method to load the model weights.    The bare FLAVA Image Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None interpolate_pos_encoding: typing.Optional[bool] = None attention_mask: typing.Optional[to


FlavaImageModel

rch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)  Parameters   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
FlavaImageProcessor.call() for details.   bool_masked_pos (torch.BoolTensor of shape (batch_size, image_num_patches)) —
Boolean masked positions. Indicates which patches are masked (1) and which aren’t (0).   interpolate_pos_encoding (bool, optional) —
Whether to interpolate the pre-trained position encodings.   attention_mask (torch.FloatTensor of shape (batch_size, image_num_patches), optional) —
Mask to avoid perform


FlavaImageModel

ing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_outputs.BaseModelOu


FlavaImageModel

tputWithPooling or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (FlavaImageConfig) and inputs.
last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.
pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) — Last layer hidden-state of the first token of the sequence (classification token) after further processing
through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
the classification token after processing through a linear layer and a tanh activation function. The linear
layer weights are trained from the next sente


FlavaImageModel

nce prediction (classification) objective during pretraining.
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
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 after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The FlavaImageModel forward


FlavaImageModel

 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.  Example:   Copied >>> from transformers import AutoImageProcessor, FlavaImageModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/flava-full")
>>> model = FlavaImageModel.from_pretrained("facebook/flava-full")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 197,


FlavaMultimodalModel

class transformers.FlavaMultimodalModel  < source > ( config: FlavaMultimodalConfig add_pooling_layer = True  )   Parameters   config (FlavaMultimodalConfig) — 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() method to load the model weights.    The bare FLAVA Multimodal Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( hidden_states: Tensor attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typi


FlavaMultimodalModel

ng.Optional[bool] = None  ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)  Parameters   hidden_states (torch.FloatTensor of shape (batch_size, image_num_patches + text_seq_len, hidden_size)) —
The concatenated hidden states of unimodal encoders.   attention_mask (torch.FloatTensor of shape (batch_size, image_num_patches + text_seq_len), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?
   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See a


FlavaMultimodalModel

ttentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (FlavaMultimodalConfig) and inputs.
last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.
pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) — Last layer hidden-state of the first token of the sequenc


FlavaMultimodalModel

e (classification token) after further processing
through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
the classification token after processing through a linear layer and a tanh activation function. The linear
layer weights are trained from the next sentence prediction (classification) objective during pretraining.
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple


FlavaMultimodalModel

of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The FlavaMultimodalModel 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.  Example:   Copied >>> from transformers import AutoTokenizer, FlavaMultimodalModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/flava-full")
>>> model = FlavaMultimodalModel.from_pretrained("facebook/flava-full")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_st


Overview

The VisionEncoderDecoderModel can be used to initialize an image-to-text model with any
pretrained Transformer-based vision model as the encoder (e.g. ViT, BEiT, DeiT, Swin)
and any pretrained language model as the decoder (e.g. RoBERTa, GPT2, BERT, DistilBERT).
The effectiveness of initializing image-to-text-sequence models with pretrained checkpoints has been shown in (for
example) TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models by Minghao Li, Tengchao Lv, Lei Cui,


Overview

Yijuan Lu, Dinei Florencio, Cha Zhang,
Zhoujun Li, Furu Wei.
After such a VisionEncoderDecoderModel has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples below
for more information).
An example application is image captioning, in which the encoder is used to encode the image, after which an autoregressive language model generates
the caption. Another example is optical character recognition. Refer to TrOCR, which is an instance of VisionEncoderDecoderModel


Randomly initializing VisionEncoderDecoderModel from model configurations.

VisionEncoderDecoderModel can be randomly initialized from an encoder and a decoder config. In the following example, we show how to do this using the default ViTModel configuration for the encoder
and the default BertForCausalLM configuration for the decoder.
  Copied >>> from transformers import BertConfig, ViTConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel
>>> config_encoder = ViTConfig()
>>> config_decoder = BertConfig()
>>> config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
>>> model = VisionEncoderDecoderModel(config=config)


Initialising VisionEncoderDecoderModel from a pretrained encoder and a pretrained decoder.

VisionEncoderDecoderModel can be initialized from a pretrained encoder checkpoint and a pretrained decoder checkpoint. Note that any pretrained Transformer-based vision model, e.g. Swin, can serve as the encoder and both pretrained auto-encoding models, e.g. BERT, pretrained causal language models, e.g. GPT2, as well as the pretrained decoder part of sequence-to-sequence models, e.g. decoder of BART, can be used as the decoder.
Depending on which architecture you choose as the decoder, the cross-attention layers might be randomly initialized.
In


itializing VisionEncoderDecoderModel from a pretrained encoder and decoder checkpoint requires the model to be fine-tuned on a downstream task, as has been shown in the Warm-starting-encoder-decoder blog post.
To do so, the VisionEncoderDecoderModel class provides a VisionEncoderDecoderModel.from_encoder_decoder_pretrained() method.
  Copied >>> from transformers import VisionEncoderDecoderModel
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "microsoft/swin-base-patch4-window7-224-in22k", "bert-base-uncased"
... )


Loading an existing VisionEncoderDecoderModel checkpoint and perform inference.

To load fine-tuned checkpoints of the VisionEncoderDecoderModel class, VisionEncoderDecoderModel provides the from_pretrained(...) method just like any other model architecture in Transformers.
To perform inference, one uses the generate method, which allows to autoregressively generate text. This method supports various forms of decoding, such as greedy, beam search and multinomial sampling.
  Copied >>> import requests
>>> from PIL import Image
>>> from transformers import GPT2TokenizerFast, ViTImageProcessor, VisionEncoderDecoderModel
>>> # load a fine-tuned image captioning model and corresponding tokenizer and image processor
>>> model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-caption


ing")
>>> tokenizer = GPT2TokenizerFast.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> image_processor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> # let's perform inference on an image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values
>>> # autoregressively generate caption (uses greedy decoding by default)
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_text)
a cat laying on a blanket next to a cat laying on a be


Loading a PyTorch checkpoint into TFVisionEncoderDecoderModel .

TFVisionEncoderDecoderModel.from_pretrained() currently doesn’t support initializing the model from a
PyTorch checkpoint. Passing from_pt=True to this method will throw an exception. If there are only PyTorch
checkpoints for a particular vision encoder-decoder model, a workaround is:
  Copied >>> from transformers import VisionEncoderDecoderModel, TFVisionEncoderDecoderModel
>>> _model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> _model.encoder.save_pretrained("./encoder")
>>> _model.decoder.save_pretrained("./decoder")
>>> model = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "./encoder", "./decoder", encoder_from_pt=True, decoder_from_pt=True
... )
>>> # This is only for copying some specific attributes of this particular model.
>>> model.config = _model.config


Training

Once the model is created, it can be fine-tuned similar to BART, T5 or any other encoder-decoder model on a dataset of (image, text) pairs.
As you can see, only 2 inputs are required for the model in order to compute a loss: pixel_values (which are the
images) and labels (which are the input_ids of the encoded target sequence).
  Copied >>> from transformers import ViTImageProcessor, BertTokenizer, VisionEncoderDecoderModel
>>> from datasets import load_dataset
>>> image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "google/v


Training

it-base-patch16-224-in21k", "bert-base-uncased"
... )
>>> model.config.decoder_start_token_id = tokenizer.cls_token_id
>>> model.config.pad_token_id = tokenizer.pad_token_id
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values
>>> labels = tokenizer(
...     "an image of two cats chilling on a couch",
...     return_tensors="pt",
... ).input_ids
>>> # the forward function automatically creates the correct decoder_input_ids
>>> loss = model(pixel_values=pixel_values, labels=labels).loss
This model was contributed by nielsr. This model’s TensorFlow and Flax versions
were contributed by ydshieh


VisionEncoderDecoderConfig

class transformers.VisionEncoderDecoderConfig  < source > ( **kwargs  )   Parameters   kwargs (optional) —
Dictionary of keyword arguments. Notably:
encoder (PretrainedConfig, optional) — An instance of a configuration object that defines
the encoder config.
decoder (PretrainedConfig, optional) — An instance of a configuration object that defines
the decoder config.
    VisionEncoderDecoderConfig is the configuration class to store the configuration of a
VisionEncoderDecoderModel. It is used to instantiate a Vision-Encoder-Text-Decoder model according to the
specified arguments, defining the encoder and decoder configs. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentatio


VisionEncoderDecoderConfig

n from PretrainedConfig for more information.  Examples:   Copied >>> from transformers import BertConfig, ViTConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel
>>> # Initializing a ViT & BERT style configuration
>>> config_encoder = ViTConfig()
>>> config_decoder = BertConfig()
>>> config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
>>> # Initializing a ViTBert model (with random weights) from a ViT & bert-base-uncased style configurations
>>> model = VisionEncoderDecoderModel(config=config)
>>> # Accessing the model configuration
>>> config_encoder = model.config.encoder
>>> config_decoder = model.config.decoder
>>> # set decoder config to causal lm
>>> config_decoder.is_decoder =


VisionEncoderDecoderConfig

 True
>>> config_decoder.add_cross_attention = True
>>> # Saving the model, including its configuration
>>> model.save_pretrained("my-model")
>>> # loading model and config from pretrained folder
>>> encoder_decoder_config = VisionEncoderDecoderConfig.from_pretrained("my-model")
>>> model = VisionEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)  from_encoder_decoder_configs  < source > ( encoder_config: PretrainedConfig decoder_config: PretrainedConfig **kwargs  ) → VisionEncoderDecoderConfig  Returns
VisionEncoderDecoderConfig

An instance of a configuration object
  Instantiate a VisionEncoderDecoderConfig (or a derived class) from a pre-trained encoder model
configuration and decoder model configuratio


VisionEncoderDecoderModel

class transformers.VisionEncoderDecoderModel  < source > ( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None decoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None  )   Parameters   config (VisionEncoderDecoderConfig) — 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() method to load the model weights.    This class can be used to initialize an image-to-text-sequence model with any pretrained vision autoencoding model
as the encoder and any pretrained text autoregressive model as the decoder. The encoder is loaded via
from_pretrained() function and the decoder is loaded via from_pretrained()
function. Cross-attention layers are automatically added to the decode


VisionEncoderDecoderModel

r and should be fine-tuned on a downstream
generative task, like image captioning. The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
tasks was shown in Leveraging Pre-trained Checkpoints for Sequence Generation
Tasks by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
Zhou, Wei Li, Peter J. Liu. Additionally, in TrOCR: Transformer-based Optical Character Recognition with Pre-trained
Models it is shown how leveraging large pretrained vision models for optical
character recognition (OCR) yields a significant performance improvement. After such a Vision-Encoder-Text-Decoder model has been trained/fine-tuned, it can be saved/loaded just like any
other models (see the examples for more information). This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or


VisionEncoderDecoderModel

saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior. VisionEncoderDecoderModel is a generic model class that will be instantiated as a transformer architecture with
one of the base vision model classes of the library as encoder and another one as decoder when created with the
:meth~transformers.AutoModel.from_pretrained class method for the encoder and
:meth~transformers.AutoModelForCausalLM.from_pretrained class method for the decoder.  forward  < source > ( pixel_values: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None encoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = None past_key_values: typing.Optional[typing.Tuple[ty


VisionEncoderDecoderModel

ping.Tuple[torch.FloatTensor]]] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs  ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)  Parameters   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using an image processor (e.g. if you use ViT as the encoder,
you should use AutoImageProcessor). See ViTImageProcessor.call() for details.   decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) —
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and
PreTr


VisionEncoderDecoderModel

ainedTokenizer.call() for details.
What are input IDs?
If past_key_values is used, optionally only the last decoder_input_ids have to be input (see
past_key_values).
For training, decoder_input_ids are automatically created by the model by shifting the labels to the
right, replacing -100 by the pad_token_id and prepending them with the decoder_start_token_id.   decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also
be used by default.   encoder_outputs (tuple(torch.FloatTensor), optional) —
This tuple must consist of (last_hidden_state, optional: hidden_states, optional: attentions)
last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) is a tensor
of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the
decoder.   pas


VisionEncoderDecoderModel

t_key_values (tuple(tuple(torch.FloatTensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) —
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that
don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all
decoder_input_ids of shape (batch_size, sequence_length).   decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) —
Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded
representation. This is useful if you want more control over how to convert decoder_input_ids indices
into associated vectors than the model’s internal embedding lookup matrix.   labels (torch.Lo


VisionEncoderDecoderModel

ngTensor of shape (batch_size, sequence_length), optional) —
Labels for computing the masked language modeling loss for the decoder. Indices should be in [-100, 0, ..., config.vocab_size] (see input_ids docstring) Tokens with indices set to -100 are ignored
(masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
If set to True, the model will return a ~utils.Seq2SeqLMOutput instead of a plain tuple.   k


VisionEncoderDecoderModel

wargs (optional) — Remaining dictionary of keyword arguments. Keyword arguments come in two flavors:
Without a prefix which will be input as **encoder_kwargs for the encoder forward function.
With a decoder_ prefix which will be input as **decoder_kwargs for the decoder forward function.
   Returns
transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (VisionEncoderDecoderConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.
logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (tuple(tuple(torch.F


VisionEncoderDecoderModel

loatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape
(batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head).
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used (see past_key_values input) to speed up sequential decoding.
decoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the decoder at the output of eac


VisionEncoderDecoderModel

h layer plus the initial embedding outputs.
decoder_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, after the attention softmax, used to compute the weighted average in the
self-attention heads.
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.
encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional)


VisionEncoderDecoderModel

— Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_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 encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
  The VisionEncoderDecoderModel forwar


VisionEncoderDecoderModel

d 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:   Copied >>> from transformers import AutoProcessor, VisionEncoderDecoderModel
>>> import requests
>>> from PIL import Image
>>> import torch
>>> processor = AutoProcessor.from_pretrained("microsoft/trocr-base-handwritten")
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
>>> # load image from the IAM dataset
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
>>> # training
>>> model.config.decoder_start_token_id = processor.tokenizer.cls_token_id
>>> model.config.pad_token_id = processor.tokenizer.pad_tok


VisionEncoderDecoderModel

en_id
>>> model.config.vocab_size = model.config.decoder.vocab_size
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
>>> text = "hello world"
>>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(pixel_values=pixel_values, labels=labels)
>>> loss = outputs.loss
>>> # inference (generation)
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]  from_encoder_decoder_pretrained  < source > ( encoder_pretrained_model_name_or_path: str = None decoder_pretrained_model_name_or_path: str = None *model_args **kwargs  )   Parameters   encoder_pretrained_model_name_or_path (str, optional) —
Information necessary to initiate the image encoder. Can be either:
A string, the model id of a pretrained model hosted inside a model repo on huggingface.co. An
example is google/vit-base-patch16-224-in21k.
A path to a director


VisionEncoderDecoderModel

y containing model weights saved using
save_pretrained(), e.g., ./my_model_directory/.
A path or url to a tensorflow index checkpoint file (e.g, ./tf_model/model.ckpt.index). In
this case, from_tf should be set to True and a configuration object should be provided as
config argument. This loading path is slower than converting the TensorFlow checkpoint in a
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
   decoder_pretrained_model_name_or_path (str, optional, defaults to None) —
Information necessary to initiate the text decoder. Can be either:
A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
Valid model ids can be located at the root-level, like bert-base-uncased, or namespaced under a
user or organization name, like dbmdz/bert-base-german-cased.
A path to a directory containing model weights saved using
save_pretrained(), e.g., ./my_model_directory/.
A


VisionEncoderDecoderModel

 path or url to a tensorflow index checkpoint file (e.g, ./tf_model/model.ckpt.index). In
this case, from_tf should be set to True and a configuration object should be provided as
config argument. This loading path is slower than converting the TensorFlow checkpoint in a
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
   model_args (remaining positional arguments, optional) —
All remaning positional arguments will be passed to the underlying model’s __init__ method.   kwargs (remaining dictionary of keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True).
To update the encoder configuration, use the prefix encoder_ for each configuration parameter.
To update the decoder configuration, use the prefix decoder_ for each configuration parameter.
To update the parent model configuration, do not use a pr


VisionEncoderDecoderModel

efix for each configuration parameter.
Behaves differently depending on whether a config is provided or automatically loaded.    Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
checkpoints. The model is set in evaluation mode by default using model.eval() (Dropout modules are deactivated). To train
the model, you need to first set it back in training mode with model.train().  Example:   Copied >>> from transformers import VisionEncoderDecoderModel
>>> # initialize a vit-bert from a pretrained ViT and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "google/vit-base-patch16-224-in21k", "bert-base-uncased"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./vit-bert")
>>> # load fine-tuned model
>>> model = VisionEncoderDecoderModel.from_pretrained(".


TFVisionEncoderDecoderModel

class transformers.TFVisionEncoderDecoderModel  < source > ( *args **kwargs  )   Parameters   config (VisionEncoderDecoderConfig) — 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() method to load the model weights.    This class can be used to initialize an image-to-text-sequence model with any pretrained vision autoencoding model
as the encoder and any pretrained text autoregressive model as the decoder. The encoder is loaded via
from_pretrained() function and the decoder is loaded via from_pretrained()
function. Cross-attention layers are automatically added to the decoder and should be fine-tuned on a downstream
generative task, like image captioning. The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
tasks was shown in Leveraging Pre-tra


TFVisionEncoderDecoderModel

ined Checkpoints for Sequence Generation
Tasks by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
Zhou, Wei Li, Peter J. Liu. Additionally, in TrOCR: Transformer-based Optical Character Recognition with Pre-trained
Models it is shown how leveraging large pretrained vision models for optical
character recognition (OCR) yields a significant performance improvement. After such a Vision-Encoder-Text-Decoder model has been trained/fine-tuned, it can be saved/loaded just like any
other models (see the examples for more information). This model inherits from TFPreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a tf.keras.Model subclass. Use it
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
behavior. TFVisionEnc


TFVisionEncoderDecoderModel

oderDecoderModel is a generic model class that will be instantiated as a transformer architecture
with one of the base vision model classes of the library as encoder and another one of the base model classes as
decoder when created with the from_pretrained() class method for the encoder and
from_pretrained() class method for the decoder.  call  < source > ( pixel_values: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None labels: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False **kwargs  ) → tran


TFVisionEncoderDecoderModel

sformers.modeling_tf_outputs.TFSeq2SeqLMOutput or tuple(tf.Tensor)  Parameters   pixel_values (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using the vision’s model’s image processor. For example, using
AutoImageProcessor. See ViTImageProcessor.call() for details.   decoder_input_ids (np.ndarray or tf.Tensor of shape (batch_size, target_sequence_length), optional) —
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?
If past_key_values is used, optionally only the last decoder_input_ids have to be input (see
past_key_values).
Provide for sequence to sequence training to the decoder. Indices can be obtained using
PreTrainedTokenizer. See Pre


TFVisionEncoderDecoderModel

TrainedTokenizer.encode() and PreTrainedTokenizer.call() for
details.   decoder_attention_mask (np.ndarray or tf.Tensor of shape (batch_size, target_sequence_length), optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also
be used by default.   encoder_outputs (tuple(tuple(tf.Tensor), optional) —
This tuple must consist of (last_hidden_state, optional: hidden_states, optional: attentions)
last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size)) is a tensor of hidden-states at the output
of the last layer of the encoder. Used in the cross-attention of the decoder.   past_key_values (tuple(tuple(tf.Tensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) —
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If past_key_values are used