GroupViT
Last updated
Last updated
The GroupViT model was proposed in by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang. Inspired by , GroupViT is a vision-language model that can perform zero-shot semantic segmentation on any given vocabulary categories.
The abstract from the paper is the following:
Grouping and recognition are important components of visual scene understanding, e.g., for object detection and semantic segmentation. With end-to-end deep learning systems, grouping of image regions usually happens implicitly via top-down supervision from pixel-level recognition labels. Instead, in this paper, we propose to bring back the grouping mechanism into deep networks, which allows semantic segments to emerge automatically with only text supervision. We propose a hierarchical Grouping Vision Transformer (GroupViT), which goes beyond the regular grid structure representation and learns to group image regions into progressively larger arbitrary-shaped segments. We train GroupViT jointly with a text encoder on a large-scale image-text dataset via contrastive losses. With only text supervision and without any pixel-level annotations, GroupViT learns to group together semantic regions and successfully transfers to the task of semantic segmentation in a zero-shot manner, i.e., without any further fine-tuning. It achieves a zero-shot accuracy of 52.3% mIoU on the PASCAL VOC 2012 and 22.4% mIoU on PASCAL Context datasets, and performs competitively to state-of-the-art transfer-learning methods requiring greater levels of supervision.
Tips:
You may specify output_segmentation=True
in the forward of GroupViTModel
to get the segmentation logits of input texts.
This model was contributed by . The TensorFlow version was contributed by with the help of , , and . The original code can be found .
A list of official BOINC AI and community (indicated by 🌎) resources to help you get started with GroupViT.
The quickest way to get started with GroupViT is by checking the (which showcase zero-shot segmentation inference).
One can also check out the to play with GroupViT.
( text_config = Nonevision_config = Noneprojection_dim = 256projection_intermediate_dim = 4096logit_scale_init_value = 2.6592**kwargs )
Parameters
projection_dim (int
, optional, defaults to 256) — Dimentionality of text and vision projection layers.
projection_intermediate_dim (int
, optional, defaults to 4096) — Dimentionality of intermediate layer of text and vision projection layers.
logit_scale_init_value (float
, optional, defaults to 2.6592) — The inital value of the logit_scale parameter. Default is used as per the original GroupViT implementation.
kwargs (optional) — Dictionary of keyword arguments.
from_text_vision_configs
Returns
An instance of a configuration object
( vocab_size = 49408hidden_size = 256intermediate_size = 1024num_hidden_layers = 12num_attention_heads = 4max_position_embeddings = 77hidden_act = 'quick_gelu'layer_norm_eps = 1e-05dropout = 0.0attention_dropout = 0.0initializer_range = 0.02initializer_factor = 1.0pad_token_id = 1bos_token_id = 49406eos_token_id = 49407**kwargs )
Parameters
hidden_size (int
, optional, defaults to 256) — Dimensionality of the encoder layers and the pooler layer.
intermediate_size (int
, optional, defaults to 1024) — 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 4) — Number of attention heads for each attention layer in the Transformer encoder.
max_position_embeddings (int
, optional, defaults to 77) — 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).
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.
dropout (float
, optional, defaults to 0.0) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
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.0) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).
Example:
Copied
( hidden_size = 384intermediate_size = 1536depths = [6, 3, 3]num_hidden_layers = 12num_group_tokens = [64, 8, 0]num_output_groups = [64, 8, 8]num_attention_heads = 6image_size = 224patch_size = 16num_channels = 3hidden_act = 'gelu'layer_norm_eps = 1e-05dropout = 0.0attention_dropout = 0.0initializer_range = 0.02initializer_factor = 1.0assign_eps = 1.0assign_mlp_ratio = [0.5, 4]**kwargs )
Parameters
hidden_size (int
, optional, defaults to 384) — Dimensionality of the encoder layers and the pooler layer.
intermediate_size (int
, optional, defaults to 1536) — Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.
depths (List[int]
, optional, defaults to [6, 3, 3]) — The number of layers in each encoder block.
num_group_tokens (List[int]
, optional, defaults to [64, 8, 0]) — The number of group tokens for each stage.
num_output_groups (List[int]
, optional, defaults to [64, 8, 8]) — The number of output groups for each stage, 0 means no group.
num_attention_heads (int
, optional, defaults to 6) — 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 16) — The size (resolution) of each patch.
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"
`"quick_gelu"
are supported.
layer_norm_eps (float
, optional, defaults to 1e-5) — The epsilon used by the layer normalization layers.
dropout (float
, optional, defaults to 0.0) — The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
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.0) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).
Example:
Copied
( config: GroupViTConfig )
Parameters
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] = Nonereturn_loss: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneoutput_segmentation: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.groupvit.modeling_groupvit.GroupViTModelOutput
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.groupvit.modeling_groupvit.GroupViTModelOutput
or tuple(torch.FloatTensor)
A transformers.models.groupvit.modeling_groupvit.GroupViTModelOutput
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.groupvit.configuration_groupvit.GroupViTConfig'>
) 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.
segmentation_logits (torch.FloatTensor
of shape (batch_size, config.num_labels, logits_height, logits_width)
) — Classification scores for each pixel.
The logits returned do not necessarily have the same size as the pixel_values
passed as inputs. This is to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the original image size as post-processing. You should always check your logits shape and resize as needed.
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] = 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: GroupViTTextConfig )
forward
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
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
( config: GroupViTVisionConfig )
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
( *args**kwargs )
Parameters
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using tf.keras.Model.fit
method which currently requires having all the tensors in the first argument of the model call function: model(inputs)
.
If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids
only and nothing else: model(input_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: model([input_ids, attention_mask])
or model([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring: model({"input_ids": input_ids, "token_type_ids": token_type_ids})
call
( input_ids: TFModelInputType | None = Nonepixel_values: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Noneposition_ids: np.ndarray | tf.Tensor | None = Nonereturn_loss: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Noneoutput_segmentation: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → transformers.models.groupvit.modeling_tf_groupvit.TFGroupViTModelOutput
or tuple(tf.Tensor)
Parameters
input_ids (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, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (np.ndarray
or tf.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 (np.ndarray
or tf.Tensor
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
training (bool
, optional, defaults to `False“) — Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
Returns
transformers.models.groupvit.modeling_tf_groupvit.TFGroupViTModelOutput
or tuple(tf.Tensor)
A transformers.models.groupvit.modeling_tf_groupvit.TFGroupViTModelOutput
or a tuple of tf.Tensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.groupvit.configuration_groupvit.GroupViTConfig'>
) and inputs.
loss (tf.Tensor
of shape (1,)
, optional, returned when return_loss
is True
) — Contrastive loss for image-text similarity.
logits_per_image (tf.Tensor
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 (tf.Tensor
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.
segmentation_logits (tf.Tensor
of shape (batch_size, config.num_labels, logits_height, logits_width)
) — Classification scores for each pixel.
The logits returned do not necessarily have the same size as the pixel_values
passed as inputs. This is to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the original image size as post-processing. You should always check your logits shape and resize as needed.
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: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Noneposition_ids: np.ndarray | tf.Tensor | None = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → text_features (tf.Tensor
of shape (batch_size, output_dim
)
Parameters
input_ids (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, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (np.ndarray
or tf.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 (np.ndarray
or tf.Tensor
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
training (bool
, optional, defaults to `False“) — Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
Returns
text_features (tf.Tensor
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: TFModelInputType | None = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → image_features (tf.Tensor
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
training (bool
, optional, defaults to `False“) — Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
Returns
image_features (tf.Tensor
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
( *args**kwargs )
call
Parameters
input_ids (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, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (np.ndarray
or tf.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 (np.ndarray
or tf.Tensor
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
training (bool
, optional, defaults to `False“) — Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
Returns
last_hidden_state (tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the model.
pooler_output (tf.Tensor
of shape (batch_size, hidden_size)
) — Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.
This output is usually not a good summary of the semantic content of the input, you’re often better with averaging or pooling the sequence of hidden-states for the whole input sequence.
hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for the output of the embeddings + 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 initial embedding outputs.
attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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
( *args**kwargs )
call
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
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. This argument can be used only in eager mode, in graph mode the value in the config will be used instead.
training (bool
, optional, defaults to `False“) — Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
Returns
last_hidden_state (tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the model.
pooler_output (tf.Tensor
of shape (batch_size, hidden_size)
) — Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.
This output is usually not a good summary of the semantic content of the input, you’re often better with averaging or pooling the sequence of hidden-states for the whole input sequence.
hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for the output of the embeddings + 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 initial embedding outputs.
attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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
text_config (dict
, optional) — Dictionary of configuration options used to initialize .
vision_config (dict
, optional) — Dictionary of configuration options used to initialize .
is the configuration class to store the configuration of a . It is used to instantiate a GroupViT model according to the specified arguments, defining the text model and vision model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the GroupViT architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
( text_config: GroupViTTextConfigvision_config: GroupViTVisionConfig**kwargs ) →
Instantiate a (or a derived class) from groupvit text model configuration and groupvit vision model configuration.
vocab_size (int
, optional, defaults to 49408) — Vocabulary size of the GroupViT text model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling .
This is the configuration class to store the configuration of a . It is used to instantiate an GroupViT 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 GroupViT 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 GroupViT 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 GroupViT architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
config () — 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 method to load the model weights.
This model is a PyTorch subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Indices can be obtained using . See and for details.
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. 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.
( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and 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.groupvit.configuration_groupvit.GroupViTTextConfig'>
) and inputs.
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.groupvit.configuration_groupvit.GroupViTVisionConfig'>
) and inputs.
The forward method, overrides the __call__
special method.
config () — 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 method to load the model weights.
This model inherits from . 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 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.
Indices can be obtained using . See and for details.
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 . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True.
text_embeds (tf.Tensor
of shape (batch_size, output_dim
) — The text embeddings obtained by applying the projection layer to the pooled output of .
image_embeds (tf.Tensor
of shape (batch_size, output_dim
) — The image embeddings obtained by applying the projection layer to the pooled output of .
text_model_output (TFBaseModelOutputWithPooling
) — The output of the .
vision_model_output (TFBaseModelOutputWithPooling
) — 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. This argument can be used in eager mode, in graph mode the value will always be set to True.
The text embeddings obtained by applying the projection layer to the pooled output of .
The forward method, overrides the __call__
special method.
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 . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True.
The image embeddings obtained by applying the projection layer to the pooled output of .
The forward method, overrides the __call__
special method.
( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Noneposition_ids: np.ndarray | tf.Tensor | None = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → or tuple(tf.Tensor)
Indices can be obtained using . See and for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True.
or tuple(tf.Tensor)
A or a tuple of tf.Tensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.groupvit.configuration_groupvit.GroupViTTextConfig'>
) and inputs.
The forward method, overrides the __call__
special method.
( pixel_values: TFModelInputType | None = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → or tuple(tf.Tensor)
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 . See for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True.
or tuple(tf.Tensor)
A or a tuple of tf.Tensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.groupvit.configuration_groupvit.GroupViTVisionConfig'>
) and inputs.
The forward method, overrides the __call__
special method.