Transformers documentation

FLAVA

You are viewing v4.20.1 version. A newer version v4.47.1 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

FLAVA

Overview

The FLAVA model was proposed in FLAVA: A Foundational Language And Vision Alignment Model by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela and is accepted at CVPR 2022.

The paper aims at creating a single unified foundation model which can work across vision, language as well as vision-and-language multimodal tasks.

The abstract from the paper is the following:

State-of-the-art vision and vision-and-language models rely on large-scale visio-linguistic pretraining for obtaining good performance on a variety of downstream tasks. Generally, such models are often either cross-modal (contrastive) or multi-modal (with earlier fusion) but not both; and they often only target specific modalities or tasks. A promising direction would be to use a single holistic universal model, as a β€œfoundation”, that targets all modalities at once β€” a true vision and language foundation model should be good at vision tasks, language tasks, and cross- and multi-modal vision and language tasks. We introduce FLAVA as such a model and demonstrate impressive performance on a wide range of 35 tasks spanning these target modalities.

This model was contributed by aps. The original code can be found here.

FlavaConfig

class transformers.FlavaConfig

< >

( image_config_dict: typing.Dict[str, typing.Any] = None text_config_dict: typing.Dict[str, typing.Any] = None multimodal_config_dict: typing.Dict[str, typing.Any] = None image_codebook_config_dict: typing.Dict[str, typing.Any] = None hidden_size: int = 768 layer_norm_eps: float = 1e-12 projection_dim: int = 768 init_codebook: bool = True logit_scale_init_value: float = 2.6592 initializer_range: float = 0.02 ce_ignore_index: int = -100 mim_weight: float = 1.0 mlm_weight: float = 1.0 global_contrastive_weight: float = 1.0 itm_weight: float = 1.0 mmm_image_weight: float = 1.0 mmm_text_weight: float = 1.0 global_backprop_contrastive: bool = True skip_unmasked_multimodal_encoder: bool = True return_loss: bool = True **kwargs )

Parameters

  • text_config_dict (dict, optional) — Dictionary of configuration options used to initialize FlavaTextConfig.
  • image_config_dict (dict, optional) — Dictionary of configuration options used to initialize FlavaImageConfig.
  • multimodal_config_dict (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, defaults 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_unmasked_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:

>>> from transformers import FlavaModel, FlavaForPreTraining, FlavaConfig

>>> # Initializing a FlavaConfig with style configuration
>>> configuration = FlavaConfig()

>>> # Initializing a FlavaModel and FlavaForPreTraining model 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

< >

( 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 configuration.

to_dict

< >

( ) β†’ Dict[str, any]

Returns

Dict[str, any]

Dictionary of all the attributes that make up this configuration instance,

Serializes this instance to a Python dictionary. Override the default to_dict().

FlavaTextConfig

class transformers.FlavaTextConfig

< >

( 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 FlavaTextModel. 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 Better 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 for 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 store 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:

>>> from transformers import FlavaTextModel, FlavaTextConfig

>>> # Initializing a FlavaTextModel with  style configuration
>>> configuration = FlavaTextConfig()

>>> # Initializing a FlavaTextConfig from the  style configuration
>>> model = FlavaTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

FlavaImageConfig

class transformers.FlavaImageConfig

< >

( 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 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 for 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.
  • 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 FlavaImageModel. 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:

>>> from transformers import FlavaImageModel, FlavaImageConfig

>>> # Initializing a FlavaImageModel with  style configuration
>>> configuration = FlavaImageConfig()

>>> # Initializing a FlavaImageModel model from the  style configuration
>>> model = FlavaImageModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

FlavaMultimodalConfig

class transformers.FlavaMultimodalConfig

< >

( 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 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 for 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.
  • 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 FLAVA 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:

>>> from transformers import FlavaMultimodalModel, FlavaMultimodalConfig

>>> # Initializing a FlavaMultimodalModel with  style configuration
>>> configuration = FlavaMultimodalConfig()

>>> # Initializing a FlavaMultimodalModel model from the  style configuration
>>> model = FlavaMultimodalModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

FlavaImageCodebookConfig

class transformers.FlavaImageCodebookConfig

< >

( 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

< >

( feature_extractor tokenizer )

Parameters

Constructs a FLAVA processor which wraps a FLAVA feature extractor and a FLAVA tokenizer into a single processor.

FlavaProcessor offers all the functionalities of FlavaFeatureExtractor and BertTokenizerFast. See the __call__() and decode() for more information.

batch_decode

< >

( *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

< >

( *args **kwargs )

This method forwards all its arguments to BertTokenizerFast’s decode(). Please refer to the docstring of this method for more information.

FlavaFeatureExtractor

class transformers.FlavaFeatureExtractor

< >

( do_resize: bool = True size: typing.Union[int, typing.Tuple[int, int]] = 224 resample: int = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Union[int, typing.Tuple[int, int]] = 224 do_normalize: bool = True image_mean: typing.Tuple[float, float, float] = [0.48145466, 0.4578275, 0.40821073] image_std: typing.Tuple[float, float, float] = [0.26862954, 0.26130258, 0.27577711] 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 codebook_do_resize: bool = True codebook_size: bool = 112 codebook_resample: int = <Resampling.LANCZOS: 1> codebook_do_center_crop: bool = True codebook_crop_size: int = 112 codebook_do_map_pixels: bool = True codebook_do_normalize: bool = True codebook_image_mean: typing.Tuple[float, float, float] = [0.0, 0.0, 0.0] codebook_image_std: typing.Tuple[float, float, float] = [1.0, 1.0, 1.0] **kwargs: typing.Any )

Parameters

  • do_resize (bool, optional, defaults to True) — Whether to resize the input to a certain size.
  • size (int, optional, defaults to 224) — Resize the input to the given size. Only has an effect if do_resize is set to True.
  • resample (int, optional, defaults to PIL.Image.BICUBIC) — An optional resampling filter. This can be one of PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image.BICUBIC or PIL.Image.LANCZOS. Only has an effect
  • do_center_crop (bool, optional, defaults to True) — Whether to crop the input at the center. If the input size is smaller than crop_size along any edge, the image is padded with 0’s and then center cropped.
  • crop_size (int, optional, defaults to 224) — Desired output size when applying center-cropping. Only has an effect if do_center_crop is set to True.
  • do_normalize (bool, optional, defaults to True) — Whether or not to normalize the input with image_mean and image_std.
  • image_mean (Tuple[float, float, float], optional, defaults to [0.485, 0.456, 0.406]) — The sequence of means for each channel, to be used when normalizing images.
  • image_std (Tuple[float, float, float], optional, defaults to [0.229, 0.224, 0.225]) — The sequence of standard deviations for each channel, to be used when normalizing images.
  • input_size_patches (int, optional, defaults to 14) — Number of patches in the image in height and width direction. 14x14 = 196 total patches.
  • total_mask_patches (int, optional, defaults to 75) — Total number of patches that should be masked.
  • mask_group_min_patches (int, optional, defaults to 16) — Minimum number of patches that should be masked.
  • mask_group_max_patches (int, optional, defaults to None) — Maximum number of patches that should be masked.
  • mask_group_min_aspect_ratio (float, optional, defaults to 0.3) — Minimum aspect ratio of the mask window.
  • mask_group_max_aspect_ratio (float, optional, defaults to None) — Maximum aspect ratio of the mask window
  • codebook_do_resize (bool, optional, defaults to True) — Whether to resize the input for codebook to a certain codebook_size.
  • codebook_size (int, optional, defaults to 224) — Resize the input for codebook to the given size. Only has an effect if codebook_do_resize is set to True.
  • codebook_resample (int, optional, defaults to PIL.Image.BICUBIC) — An optional resampling filter. This can be one of PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image.BICUBIC or PIL.Image.LANCZOS. Only has an effect
  • 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.
  • codebook_crop_size (int, optional, defaults to 224) — Desired output size for codebook input when applying center-cropping. Only has an effect if codebook_do_center_crop is set to True.
  • 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.
  • codebook_image_mean (Tuple[float, float, float], optional, defaults to [0, 0, 0]) — The sequence of means for each channel, to be used when normalizing images for codebook.
  • codebook_image_std (Tuple[float, float, 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.

Constructs a FLAVA feature extractor.

This feature extractor inherits from FeatureExtractionMixin which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

FlavaForPreTraining

class transformers.FlavaForPreTraining

< >

( 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

< >

( input_ids: typing.Optional[torch.LongTensor] = None input_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_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 BertTokenizer 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 BertTokenizer. 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]:

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — Pixel values. Pixel values can be obtained using FlavaFeatureExtractor. See FlavaFeatureExtractor.__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]:

  • 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 computing 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 computing 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]:

  • 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.

    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_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_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_multimodal_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 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 the 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.

  • contrastive_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

< >

( 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

< >

( 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.LongTensor] = 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 FlavaFeatureExtractor. See FlavaFeatureExtractor.__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 the vocabulary. Indices can be obtained using BertTokenizer. 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]:

  • 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]:

  • 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.
  • 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 (<class '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 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:

>>> from PIL import Image
>>> import requests
>>> from transformers import FlavaProcessor, FlavaModel

>>> model = FlavaModel.from_pretrained("facebook/flava-full")
>>> processor = FlavaProcessor.from_pretrained("facebook/flava-full")

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

>>> inputs = 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

< >

( 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 BertTokenizer. 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]:

  • 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]:

  • 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.

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

< >

( 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 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 FlavaFeatureExtractor. See FlavaFeatureExtractor.__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]:

  • 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.

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.

FlavaImageCodebook

class transformers.FlavaImageCodebook

< >

( 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 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

< >

( pixel_values: FloatTensor )

get_codebook_indices

< >

( pixel_values: Tensor )

get_codebook_probs

< >

( pixel_values: Tensor )

FlavaTextModel

class transformers.FlavaTextModel

< >

( 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

< >

( 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 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 BertTokenizer. 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]:

  • 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]:

  • 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.

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, 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_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 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:

>>> from transformers import BertTokenizer, FlavaTextModel
>>> import torch

>>> tokenizer = BertTokenizer.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_state

FlavaImageModel

class transformers.FlavaImageModel

< >

( 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

< >

( 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 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 FlavaFeatureExtractor. See FlavaFeatureExtractor.__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]:

  • 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.

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 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_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 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:

>>> from transformers import FlavaFeatureExtractor, FlavaImageModel
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> feature_extractor = FlavaFeatureExtractor.from_pretrained("facebook/flava-full")
>>> model = FlavaImageModel.from_pretrained("facebook/flava-full")

>>> inputs = feature_extractor(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, 768]

FlavaMultimodalModel

class transformers.FlavaMultimodalModel

< >

( 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

< >

( 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: typing.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]:

  • 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.

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 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 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_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:

>>> from transformers import BertTokenizer, FlavaMultimodalModel
>>> import torch

>>> tokenizer = BertTokenizer.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_state