AltCLIP
Last updated
Last updated
The AltCLIP model was proposed in by Zhongzhi Chen, Guang Liu, Bo-Wen Zhang, Fulong Ye, Qinghong Yang, Ledell Wu. AltCLIP (Altering the Language Encoder in CLIP) is a neural network trained on a variety of image-text and text-text pairs. By switching CLIP’s text encoder with a pretrained multilingual text encoder XLM-R, we could obtain very close performances with CLIP on almost all tasks, and extended original CLIP’s capabilities such as multilingual understanding.
The abstract from the paper is the following:
In this work, we present a conceptually simple and effective method to train a strong bilingual multimodal representation model. Starting from the pretrained multimodal representation model CLIP released by OpenAI, we switched its text encoder with a pretrained multilingual text encoder XLM-R, and aligned both languages and image representations by a two-stage training schema consisting of teacher learning and contrastive learning. We validate our method through evaluations of a wide range of tasks. We set new state-of-the-art performances on a bunch of tasks including ImageNet-CN, Flicker30k- CN, and COCO-CN. Further, we obtain very close performances with CLIP on almost all tasks, suggesting that one can simply alter the text encoder in CLIP for extended capabilities such as multilingual understanding.
The usage of AltCLIP is very similar to the CLIP. the difference between CLIP is the text encoder. Note that we use bidirectional attention instead of casual attention and we take the [CLS] token in XLM-R to represent text embedding.
AltCLIP is a multi-modal vision and language model. It can be used for image-text similarity and for zero-shot image classification. AltCLIP uses a ViT like transformer to get visual features and a bidirectional language model to get the text features. Both the text and visual features are then projected to a latent space with identical dimension. The dot product between the projected image and text features is then used as a similar score.
To feed images to the Transformer encoder, each image is split into a sequence of fixed-size non-overlapping patches, which are then linearly embedded. A [CLS] token is added to serve as representation of an entire image. The authors also add absolute position embeddings, and feed the resulting sequence of vectors to a standard Transformer encoder. The can be used to resize (or rescale) and normalize images for the model.
The wraps a and a into a single instance to both encode the text and prepare the images. The following example shows how to get the image-text similarity scores using and .
Copied
Tips:
This model is build on CLIPModel
, so use it like a original CLIP.
( text_config = Nonevision_config = Noneprojection_dim = 768logit_scale_init_value = 2.6592**kwargs )
Parameters
projection_dim (int
, optional, defaults to 512) — Dimentionality of text and vision 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 CLIP implementation.
kwargs (optional) — Dictionary of keyword arguments.
Example:
Copied
from_text_vision_configs
Returns
An instance of a configuration object
( vocab_size = 250002hidden_size = 1024num_hidden_layers = 24num_attention_heads = 16intermediate_size = 4096hidden_act = 'gelu'hidden_dropout_prob = 0.1attention_probs_dropout_prob = 0.1max_position_embeddings = 514type_vocab_size = 1initializer_range = 0.02initializer_factor = 0.02layer_norm_eps = 1e-05pad_token_id = 1bos_token_id = 0eos_token_id = 2position_embedding_type = 'absolute'use_cache = Trueproject_dim = 768**kwargs )
Parameters
hidden_size (int
, optional, defaults to 1024) — Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (int
, optional, defaults to 24) — Number of hidden layers in the Transformer encoder.
num_attention_heads (int
, optional, defaults to 16) — Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (int
, optional, defaults to 4096) — Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer encoder.
hidden_act (str
or Callable
, optional, defaults to "gelu"
) — The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
, "relu"
, "silu"
and "gelu_new"
are supported.
hidden_dropout_prob (float
, optional, defaults to 0.1) — The dropout probability 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.
max_position_embeddings (int
, optional, defaults to 514) — 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).
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-5) — The epsilon used by the layer normalization layers.
use_cache (bool
, optional, defaults to True
) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True
.
project_dim (int
, optional, defaults to 768) — The dimentions of the teacher model before the mapping layer.
Examples:
Copied
( hidden_size = 768intermediate_size = 3072projection_dim = 512num_hidden_layers = 12num_attention_heads = 12num_channels = 3image_size = 224patch_size = 32hidden_act = 'quick_gelu'layer_norm_eps = 1e-05attention_dropout = 0.0initializer_range = 0.02initializer_factor = 1.0**kwargs )
Parameters
hidden_size (int
, optional, defaults to 768) — Dimensionality of the encoder layers and the pooler layer.
intermediate_size (int
, optional, defaults to 3072) — Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.
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.
image_size (int
, optional, defaults to 224) — The size (resolution) of each image.
patch_size (int
, optional, defaults to 32) — The size (resolution) of each patch.
hidden_act (str
or function
, optional, defaults to "quick_gelu"
) — The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
, "relu"
, "selu"
and "gelu_new"
`"quick_gelu"
are supported.
layer_norm_eps (float
, optional, defaults to 1e-5) — The epsilon used by the layer normalization layers.
attention_dropout (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.
initializer_factor (`float“, optional, defaults to 1) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).
Example:
Copied
( image_processor = Nonetokenizer = None**kwargs )
Parameters
Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single processor.
batch_decode
( *args**kwargs )
decode
( *args**kwargs )
( config: AltCLIPConfig )
forward
( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Nonereturn_loss: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.altclip.modeling_altclip.AltCLIPOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.
attention_mask (torch.Tensor
of shape (batch_size, sequence_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.
position_ids (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]
.
return_loss (bool
, optional) — Whether or not to return the contrastive loss.
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.
Returns
transformers.models.altclip.modeling_altclip.AltCLIPOutput
or tuple(torch.FloatTensor)
A transformers.models.altclip.modeling_altclip.AltCLIPOutput
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.altclip.configuration_altclip.AltCLIPConfig'>
) and inputs.
loss (torch.FloatTensor
of shape (1,)
, optional, returned when return_loss
is True
) — Contrastive loss for image-text similarity.
logits_per_image:(torch.FloatTensor
of shape (image_batch_size, text_batch_size)
) — The scaled dot product scores between image_embeds
and text_embeds
. This represents the image-text similarity scores.
logits_per_text:(torch.FloatTensor
of shape (text_batch_size, image_batch_size)
) — The scaled dot product scores between text_embeds
and image_embeds
. This represents the text-image similarity scores.
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
get_text_features
( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonetoken_type_ids = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → text_features (torch.FloatTensor
of shape (batch_size, output_dim
)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.
attention_mask (torch.Tensor
of shape (batch_size, sequence_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.
position_ids (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]
.
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.
Returns
text_features (torch.FloatTensor
of shape (batch_size, output_dim
)
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
get_image_features
( pixel_values: typing.Optional[torch.FloatTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → image_features (torch.FloatTensor
of shape (batch_size, output_dim
)
Parameters
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.
Returns
image_features (torch.FloatTensor
of shape (batch_size, output_dim
)
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
( config )
forward
( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_attentions: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndProjection
or tuple(torch.FloatTensor)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.
attention_mask (torch.Tensor
of shape (batch_size, sequence_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.
position_ids (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]
.
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.
Returns
transformers.modeling_outputs.BaseModelOutputWithPoolingAndProjection
or tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutputWithPoolingAndProjection
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.altclip.configuration_altclip.AltCLIPTextConfig'>
) 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.
projection_state (tuple(torch.FloatTensor)
, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
of shape (batch_size,config.project_dim)
.
Text embeddings before the projection layer, used to mimic the last hidden state of the teacher encoder.
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
( config: AltCLIPVisionConfig )
forward
Parameters
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.
Returns
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.
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
This model was contributed by .
text_config (dict
, optional) — Dictionary of configuration options used to initialize .
vision_config (dict
, optional) — Dictionary of configuration options used to initialize .
This is the configuration class to store the configuration of a . It is used to instantiate an AltCLIP 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 AltCLIP architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
( text_config: AltCLIPTextConfigvision_config: AltCLIPVisionConfig**kwargs ) →
Instantiate a (or a derived class) from altclip text model configuration and altclip vision model configuration.
vocab_size (int
, optional, defaults to 250002) — Vocabulary size of the AltCLIP model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling .
type_vocab_size (int
, optional, defaults to 2) — The vocabulary size of the token_type_ids
passed when calling
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 . For more information on "relative_key_query"
, please refer to Method 4 in .
This is the configuration class to store the configuration of a . It is used to instantiate a AltCLIP text 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 AltCLIP architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
This is the configuration class to store the configuration of a . It is used to instantiate an AltCLIP 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 AltCLIP architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
image_processor () — The image processor is a required input.
tokenizer () — The tokenizer is a required input.
offers all the functionalities of and . See the __call__()
and for more information.
This method forwards all its arguments to XLMRobertaTokenizerFast’s . Please refer to the docstring of this method for more information.
This method forwards all its arguments to XLMRobertaTokenizerFast’s . Please refer to the docstring of this method for more information.
Indices can be obtained using . See and for details.
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
text_embeds(torch.FloatTensor
of shape (batch_size, output_dim
) — The text embeddings obtained by applying the projection layer to the pooled output of .
image_embeds(torch.FloatTensor
of shape (batch_size, output_dim
) — The image embeddings obtained by applying the projection layer to the pooled output of .
text_model_output(BaseModelOutputWithPooling
): The output of the .
vision_model_output(BaseModelOutputWithPooling
): The output of the .
The forward method, overrides the __call__
special method.
Indices can be obtained using . See and for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
The text embeddings obtained by applying the projection layer to the pooled output of .
The forward method, overrides the __call__
special method.
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
The image embeddings obtained by applying the projection layer to the pooled output of .
The forward method, overrides the __call__
special method.
Indices can be obtained using . See and for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
The forward method, overrides the __call__
special method.
( pixel_values: typing.Optional[torch.FloatTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → or tuple(torch.FloatTensor)
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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.altclip.configuration_altclip.AltCLIPVisionConfig'>
) and inputs.
The forward method, overrides the __call__
special method.