GIT

GIT

Overview

The GIT model was proposed in GIT: A Generative Image-to-text Transformer for Vision and Languagearrow-up-right by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang. GIT is a decoder-only Transformer that leverages CLIParrow-up-right’s vision encoder to condition the model on vision inputs besides text. The model obtains state-of-the-art results on image captioning and visual question answering benchmarks.

The abstract from the paper is the following:

In this paper, we design and train a Generative Image-to-text Transformer, GIT, to unify vision-language tasks such as image/video captioning and question answering. While generative models provide a consistent network architecture between pre-training and fine-tuning, existing work typically contains complex structures (uni/multi-modal encoder/decoder) and depends on external modules such as object detectors/taggers and optical character recognition (OCR). In GIT, we simplify the architecture as one image encoder and one text decoder under a single language modeling task. We also scale up the pre-training data and the model size to boost the model performance. Without bells and whistles, our GIT establishes new state of the arts on 12 challenging benchmarks with a large margin. For instance, our model surpasses the human performance for the first time on TextCaps (138.2 vs. 125.5 in CIDEr). Furthermore, we present a new scheme of generation-based image classification and scene text recognition, achieving decent performance on standard benchmarks.

Tips:

  • GIT is implemented in a very similar way to GPT-2, the only difference being that the model is also conditioned on pixel_values.

  • One can use GitProcessorarrow-up-right to prepare images for the model, and the generate method for autoregressive generation.

GIT architecture. Taken from the original paperarrow-up-right.

This model was contributed by nielsrarrow-up-right. The original code can be found herearrow-up-right.

Resources

A list of official BOINC AI and community (indicated by 🌎) resources to help you get started with GIT.

If you’re interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. The resource should ideally demonstrate something new instead of duplicating an existing resource.

GitVisionConfig

class transformers.GitVisionConfig

<source>arrow-up-right

( hidden_size = 768intermediate_size = 3072num_hidden_layers = 12num_attention_heads = 12num_channels = 3image_size = 224patch_size = 16hidden_act = 'quick_gelu'layer_norm_eps = 1e-05attention_dropout = 0.0initializer_range = 0.02**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 16) β€” 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.

This is the configuration class to store the configuration of a GitVisionModelarrow-up-right. It is used to instantiate a GIT vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the vision encoder of the GIT microsoft/git-basearrow-up-right architecture.

Configuration objects inherit from PretrainedConfigarrow-up-right and can be used to control the model outputs. Read the documentation from PretrainedConfigarrow-up-right for more information.

Example:

Copied

GitVisionModel

class transformers.GitVisionModel

<source>arrow-up-right

( config: GitVisionConfig )

Parameters

  • config (GitConfigarrow-up-right) β€” 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()arrow-up-right method to load the model weights.

The vision model from CLIP, used in GIT, without any head or projection on top.

This model inherits from PreTrainedModelarrow-up-right. 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 PyTorch torch.nn.Modulearrow-up-right subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

<source>arrow-up-right

( pixel_values: typing.Optional[torch.FloatTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) β†’ transformers.modeling_outputs.BaseModelOutputarrow-up-right or tuple(torch.FloatTensor)

Parameters

  • 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 AutoImageProcessorarrow-up-right. See CLIPImageProcessor.call()arrow-up-right for details.

  • 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 ModelOutputarrow-up-right instead of a plain tuple.

Returns

transformers.modeling_outputs.BaseModelOutputarrow-up-right or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputarrow-up-right 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.git.configuration_git.GitVisionConfig'>) 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.

  • 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 GitVisionModelarrow-up-right forward method, overrides the __call__ special method.

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

Examples:

Copied

GitConfig

class transformers.GitConfig

<source>arrow-up-right

( vision_config = Nonevocab_size = 30522hidden_size = 768num_hidden_layers = 6num_attention_heads = 12intermediate_size = 3072hidden_act = 'gelu'hidden_dropout_prob = 0.1attention_probs_dropout_prob = 0.1max_position_embeddings = 1024initializer_range = 0.02layer_norm_eps = 1e-12pad_token_id = 0position_embedding_type = 'absolute'use_cache = Truetie_word_embeddings = Falsebos_token_id = 101eos_token_id = 102num_image_with_embedding = None**kwargs )

Parameters

  • vision_config (dict, optional) β€” Dictionary of configuration options used to initialize GitVisionConfigarrow-up-right.

  • vocab_size (int, optional, defaults to 30522) β€” Vocabulary size of the GIT model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling GitModelarrow-up-right.

  • hidden_size (int, optional, defaults to 768) β€” Dimensionality of the encoder layers and the pooler layer.

  • num_hidden_layers (int, optional, defaults to 6) β€” Number of hidden layers in the Transformer encoder.

  • num_attention_heads (int, optional, defaults to 12) β€” Number of attention heads for each attention layer in the Transformer encoder.

  • intermediate_size (int, optional, defaults to 3072) β€” Dimensionality of the β€œintermediate” (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 1024) β€” 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-12) β€” The epsilon used by the layer normalization layers.

  • 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.)arrow-up-right. For more information on "relative_key_query", please refer to Method 4 in Improve Transformer Models with Better Relative Position Embeddings (Huang et al.)arrow-up-right.

  • use_cache (bool, optional, defaults to True) β€” Whether or not the model should return the last key/values attentions (not used by all models).

  • num_image_with_embedding (int, optional) β€” The number of temporal embeddings to add, in case the model is used for video captioning/VQA.

This is the configuration class to store the configuration of a GitModelarrow-up-right. It is used to instantiate a GIT 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 GIT microsoft/git-basearrow-up-right architecture.

Configuration objects inherit from PretrainedConfigarrow-up-right and can be used to control the model outputs. Read the documentation from PretrainedConfigarrow-up-right for more information.

Examples:

Copied

GitProcessor

class transformers.GitProcessor

<source>arrow-up-right

( image_processortokenizer )

Parameters

Constructs a GIT processor which wraps a CLIP image processor and a BERT tokenizer into a single processor.

GitProcessorarrow-up-right offers all the functionalities of CLIPImageProcessorarrow-up-right and BertTokenizerFastarrow-up-right. See the call()arrow-up-right and decode() for more information.

__call__

<source>arrow-up-right

( text = Noneimages = Nonereturn_tensors = None**kwargs ) β†’ BatchEncodingarrow-up-right

Parameters

  • text (str, List[str], List[List[str]]) β€” The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set is_split_into_words=True (to lift the ambiguity with a batch of sequences).

  • images (PIL.Image.Image, np.ndarray, torch.Tensor, List[PIL.Image.Image], List[np.ndarray], List[torch.Tensor]) β€” The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a number of channels, H and W are image height and width.

  • return_tensors (str or TensorTypearrow-up-right, optional) β€” If set, will return tensors of a particular framework. Acceptable values are:

    • 'tf': Return TensorFlow tf.constant objects.

    • 'pt': Return PyTorch torch.Tensor objects.

    • 'np': Return NumPy np.ndarray objects.

    • 'jax': Return JAX jnp.ndarray objects.

Returns

BatchEncodingarrow-up-right

A BatchEncodingarrow-up-right with the following fields:

  • input_ids β€” List of token ids to be fed to a model. Returned when text is not None.

  • attention_mask β€” List of indices specifying which tokens should be attended to by the model (when return_attention_mask=True or if β€œattention_mask” is in self.model_input_names and if text is not None).

  • pixel_values β€” Pixel values to be fed to a model. Returned when images is not None.

Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the text and kwargs arguments to BertTokenizerFast’s call()arrow-up-right if text is not None to encode the text. To prepare the image(s), this method forwards the images and kwrags arguments to CLIPImageProcessor’s call()arrow-up-right if images is not None. Please refer to the doctsring of the above two methods for more information.

GitModel

class transformers.GitModel

<source>arrow-up-right

( config )

Parameters

  • config (GitConfigarrow-up-right) β€” 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()arrow-up-right method to load the model weights.

The bare GIT Model transformer consisting of a CLIP image encoder and text decoder outputting raw hidden-states without any specific head on top.

This model inherits from PreTrainedModelarrow-up-right. 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 PyTorch torch.nn.Modulearrow-up-right subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

<source>arrow-up-right

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepast_key_values: typing.Optional[typing.List[torch.FloatTensor]] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) β†’ transformers.modeling_outputs.BaseModelOutputWithPoolingarrow-up-right or tuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) β€” Indices of input sequence tokens in the vocabulary.

    Indices can be obtained using AutoTokenizerarrow-up-right. See PreTrainedTokenizer.encode()arrow-up-right and PreTrainedTokenizer.call()arrow-up-right for details.

    What are input IDs?arrow-up-right

  • attention_mask (torch.FloatTensor 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.

    What are attention masks?arrow-up-right

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

    What are position IDs?arrow-up-right

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) β€” Pixel values. Pixel values can be obtained using AutoImageProcessorarrow-up-right. See CLIPImageProcessor.call()arrow-up-right for details.

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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) β€” Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • 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 ModelOutputarrow-up-right instead of a plain tuple.

  • past_key_values (tuple(tuple(torch.FloatTensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) β€” Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length).

  • use_cache (bool, optional) β€” If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

Returns

transformers.modeling_outputs.BaseModelOutputWithPoolingarrow-up-right or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPoolingarrow-up-right 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 (GitConfigarrow-up-right) 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 GitModelarrow-up-right forward method, overrides the __call__ special method.

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

Examples:

Copied

GitForCausalLM

class transformers.GitForCausalLM

<source>arrow-up-right

( config )

Parameters

  • config (GitConfigarrow-up-right) β€” 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()arrow-up-right method to load the model weights.

GIT Model with a language modeling head on top for autoregressive language modeling.

This model inherits from PreTrainedModelarrow-up-right. 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 PyTorch torch.nn.Modulearrow-up-right subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

<source>arrow-up-right

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Nonepast_key_values: typing.Optional[typing.List[torch.Tensor]] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) β†’ transformers.modeling_outputs.CausalLMOutputWithPastarrow-up-right or tuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) β€” Indices of input sequence tokens in the vocabulary.

    Indices can be obtained using AutoTokenizerarrow-up-right. See PreTrainedTokenizer.encode()arrow-up-right and PreTrainedTokenizer.call()arrow-up-right for details.

    What are input IDs?arrow-up-right

  • attention_mask (torch.FloatTensor 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.

    What are attention masks?arrow-up-right

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

    What are position IDs?arrow-up-right

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) β€” Pixel values. Pixel values can be obtained using AutoImageProcessorarrow-up-right. See CLIPImageProcessor.call()arrow-up-right for details.

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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) β€” Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • 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 ModelOutputarrow-up-right instead of a plain tuple.

  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) β€” Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in [-100, 0, ..., config.vocab_size] (see input_ids docstring) Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels n [0, ..., config.vocab_size]

  • past_key_values (tuple(tuple(torch.FloatTensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) β€” Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length).

  • use_cache (bool, optional) β€” If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

Returns

transformers.modeling_outputs.CausalLMOutputWithPastarrow-up-right or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutputWithPastarrow-up-right 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 (GitConfigarrow-up-right) and inputs.

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) β€” Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) β€” Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) β€” Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head))

    Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

  • 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 GitForCausalLMarrow-up-right 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:

Image captioning example:

Copied

Visual question answering (VQA) example:

Copied

Video captioning example:

Copied

Last updated