# Vision Text Dual Encoder

## VisionTextDualEncoder

### Overview

The [VisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel) can be used to initialize a vision-text dual encoder model with any pretrained vision autoencoding model as the vision encoder (*e.g.* [ViT](https://huggingface.co/docs/transformers/model_doc/vit), [BEiT](https://huggingface.co/docs/transformers/model_doc/beit), [DeiT](https://huggingface.co/docs/transformers/model_doc/deit)) and any pretrained text autoencoding model as the text encoder (*e.g.* [RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta), [BERT](https://huggingface.co/docs/transformers/model_doc/bert)). Two projection layers are added on top of both the vision and text encoder to project the output embeddings to a shared latent space. The projection layers are randomly initialized so the model should be fine-tuned on a downstream task. This model can be used to align the vision-text embeddings using CLIP like contrastive image-text training and then can be used for zero-shot vision tasks such image-classification or retrieval.

In [LiT: Zero-Shot Transfer with Locked-image Text Tuning](https://arxiv.org/abs/2111.07991) it is shown how leveraging pre-trained (locked/frozen) image and text model for contrastive learning yields significant improvement on new zero-shot vision tasks such as image classification or retrieval.

### VisionTextDualEncoderConfig

#### class transformers.VisionTextDualEncoderConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L27)

( projection\_dim = 512logit\_scale\_init\_value = 2.6592\*\*kwargs )

Parameters

* **text\_config** (`dict`) — Dictionary of configuration options that defines text model config.
* **vision\_config** (`dict`) — Dictionary of configuration options that defines vison model config.
* **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.

[VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig) is the configuration class to store the configuration of a [VisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel). It is used to instantiate [VisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel) model according to the specified arguments, defining the text model and vision model configs.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Examples:

Copied

```
>>> from transformers import ViTConfig, BertConfig, VisionTextDualEncoderConfig, VisionTextDualEncoderModel

>>> # Initializing a BERT and ViT configuration
>>> config_vision = ViTConfig()
>>> config_text = BertConfig()

>>> config = VisionTextDualEncoderConfig.from_vision_text_configs(config_vision, config_text, projection_dim=512)

>>> # Initializing a BERT and ViT model (with random weights)
>>> model = VisionTextDualEncoderModel(config=config)

>>> # Accessing the model configuration
>>> config_vision = model.config.vision_config
>>> config_text = model.config.text_config

>>> # Saving the model, including its configuration
>>> model.save_pretrained("vit-bert")

>>> # loading model and config from pretrained folder
>>> vision_text_config = VisionTextDualEncoderConfig.from_pretrained("vit-bert")
>>> model = VisionTextDualEncoderModel.from_pretrained("vit-bert", config=vision_text_config)
```

**from\_vision\_text\_configs**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L104)

( vision\_config: PretrainedConfigtext\_config: PretrainedConfig\*\*kwargs ) → [VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)

Returns

[VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)

An instance of a configuration object

Instantiate a [VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig) (or a derived class) from text model configuration and vision model configuration.

### VisionTextDualEncoderProcessor

#### class transformers.VisionTextDualEncoderProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L25)

( image\_processor = Nonetokenizer = None\*\*kwargs )

Parameters

* **image\_processor** ([AutoImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor)) — The image processor is a required input.
* **tokenizer** ([PreTrainedTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/tokenizer#transformers.PreTrainedTokenizer)) — The tokenizer is a required input.

Constructs a VisionTextDualEncoder processor which wraps an image processor and a tokenizer into a single processor.

[VisionTextDualEncoderProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderProcessor) offers all the functionalities of [AutoImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor) and [AutoTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoTokenizer). See the `__call__()` and [decode()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderProcessor.decode) for more information.

**batch\_decode**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L116)

( \*args\*\*kwargs )

This method forwards all its arguments to VisionTextDualEncoderTokenizer’s [batch\_decode()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/speecht5#transformers.SpeechT5Tokenizer.batch_decode). Please refer to the docstring of this method for more information.

**decode**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L123)

( \*args\*\*kwargs )

This method forwards all its arguments to VisionTextDualEncoderTokenizer’s [decode()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/speecht5#transformers.SpeechT5Tokenizer.decode). Please refer to the docstring of this method for more information.

### VisionTextDualEncoderModel

#### class transformers.VisionTextDualEncoderModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py#L162)

( config: typing.Optional\[transformers.models.vision\_text\_dual\_encoder.configuration\_vision\_text\_dual\_encoder.VisionTextDualEncoderConfig] = Nonevision\_model: typing.Optional\[transformers.modeling\_utils.PreTrainedModel] = Nonetext\_model: typing.Optional\[transformers.modeling\_utils.PreTrainedModel] = None )

Parameters

* **config** ([VisionEncoderDecoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-encoder-decoder#transformers.VisionEncoderDecoderConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

This class can be used to initialize a vision-text dual encoder model with any pretrained vision autoencoding model as the vision encoder and any pretrained text model as the text encoder. The vision and text encoders are loaded via the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.FlaxAutoModelForVision2Seq.from_pretrained) method. The projection layers are automatically added to the model and should be fine-tuned on a downstream task, like contrastive image-text modeling.

In [LiT: Zero-Shot Transfer with Locked-image Text Tuning](https://arxiv.org/abs/2111.07991) it is shown how leveraging pre-trained (locked/frozen) image and text model for contrastive learning yields significant improvment on new zero-shot vision tasks such as image classification or retrieval.

After such a Vision-Text-Dual-Encoder model has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples for more information).

This model inherits from [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel). 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.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py#L293)

( 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] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.clip.modeling_clip.CLIPOutput` 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.

  Indices can be obtained using [AutoTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast.encode) and [PreTrainedTokenizer.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vits#transformers.VitsTokenizer.__call__) for details.

  [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **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**.

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **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?](https://huggingface.co/docs/transformers/glossary#position-ids)
* **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 an image processor (e.g. if you use ViT as the encoder, you should use [AutoImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor)). See [ViTImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for details.
* **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.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

Returns

`transformers.models.clip.modeling_clip.CLIPOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.clip.modeling_clip.CLIPOutput` 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 ([VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)) 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.
* **text\_embeds(`torch.FloatTensor`** of shape `(batch_size, output_dim`) — The text embeddings obtained by applying the projection layer to the pooled output of [CLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTextModel).
* **image\_embeds(`torch.FloatTensor`** of shape `(batch_size, output_dim`) — The image embeddings obtained by applying the projection layer to the pooled output of [CLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPVisionModel).
* **text\_model\_output(`BaseModelOutputWithPooling`):** The output of the [CLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTextModel).
* **vision\_model\_output(`BaseModelOutputWithPooling`):** The output of the [CLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPVisionModel).

The [VisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel) forward method, overrides the `__call__` special method.

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

Examples:

Copied

```
>>> from PIL import Image
>>> import requests
>>> from transformers import (
...     VisionTextDualEncoderModel,
...     VisionTextDualEncoderProcessor,
...     AutoImageProcessor,
...     AutoTokenizer,
... )

>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> processor = VisionTextDualEncoderProcessor(image_processor, tokenizer)
>>> model = VisionTextDualEncoderModel.from_vision_text_pretrained(
...     "google/vit-base-patch16-224", "bert-base-uncased"
... )

>>> # contrastive training
>>> urls = [
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     "https://farm3.staticflickr.com/2674/5850229113_4fe05d5265_z.jpg",
... ]
>>> images = [Image.open(requests.get(url, stream=True).raw) for url in urls]
>>> inputs = processor(
...     text=["a photo of a cat", "a photo of a dog"], images=images, return_tensors="pt", padding=True
... )
>>> outputs = model(
...     input_ids=inputs.input_ids,
...     attention_mask=inputs.attention_mask,
...     pixel_values=inputs.pixel_values,
...     return_loss=True,
... )
>>> loss, logits_per_image = outputs.loss, outputs.logits_per_image  # this is the image-text similarity score

>>> # save and load from pretrained
>>> model.save_pretrained("vit-bert")
>>> model = VisionTextDualEncoderModel.from_pretrained("vit-bert")

>>> # inference
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
```

### FlaxVisionTextDualEncoderModel

#### class transformers.FlaxVisionTextDualEncoderModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py#L219)

( config: VisionTextDualEncoderConfiginput\_shape: typing.Optional\[typing.Tuple] = Noneseed: int = 0dtype: dtype = \<class 'jax.numpy.float32'>\_do\_init: bool = True\*\*kwargs )

Parameters

* **config** ([VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)) — 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()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.FlaxPreTrainedModel.from_pretrained) method to load the model weights.
* **dtype** (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`) — The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and `jax.numpy.bfloat16` (on TPUs).

  This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given `dtype`.

  **Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters.**

  If you wish to change the dtype of the model parameters, see [to\_fp16()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.FlaxPreTrainedModel.to_fp16) and [to\_bf16()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.FlaxPreTrainedModel.to_bf16).

This class can be used to initialize a vision-text dual encoder model with any pretrained vision autoencoding model as the vision encoder and any pretrained text model as the text encoder. The vision and text encoders are loaded via the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.FlaxAutoModelForVision2Seq.from_pretrained) method. The projection layers are automatically added to the model and should be fine-tuned on a downstream task, like contrastive image-text modeling.

In [LiT: Zero-Shot Transfer with Locked-image Text Tuning](https://arxiv.org/abs/2111.07991) it is shown how leveraging pre-trained (locked/frozen) image and text model for contrastive learning yields significant improvment on new zero-shot vision tasks such as image classification or retrieval.

After such a Vision-Text-Dual-Encoder model has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples for more information).

This model inherits from [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel). 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 Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and behavior.

Finally, this model supports inherent JAX features such as:

* [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
* [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
* [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
* [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py#L269)

( input\_idspixel\_valuesattention\_mask = Noneposition\_ids = Nonetoken\_type\_ids = Noneparams: dict = Nonedropout\_rng: PRNGKey = Nonetrain: bool = Falseoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.clip.modeling_flax_clip.FlaxCLIPOutput` or `tuple(torch.FloatTensor)`

Parameters

* **input\_ids** (`numpy.ndarray` of shape `(batch_size, sequence_length)`) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

  Indices can be obtained using [AutoTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast.encode) and [PreTrainedTokenizer.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vits#transformers.VitsTokenizer.__call__) for details.

  [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **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**.

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **position\_ids** (`numpy.ndarray` 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?](https://huggingface.co/docs/transformers/glossary#position-ids)
* **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 an image processor (e.g. if you use ViT as the encoder, you should use [AutoImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor)). See [ViTImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) 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 [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

Returns

`transformers.models.clip.modeling_flax_clip.FlaxCLIPOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.clip.modeling_flax_clip.FlaxCLIPOutput` 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 ([VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)) and inputs.

* **logits\_per\_image:(`jnp.ndarray`** 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:(`jnp.ndarray`** 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.
* **text\_embeds(`jnp.ndarray`** of shape `(batch_size, output_dim`) — The text embeddings obtained by applying the projection layer to the pooled output of [FlaxCLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.FlaxCLIPTextModel).
* **image\_embeds(`jnp.ndarray`** of shape `(batch_size, output_dim`) — The image embeddings obtained by applying the projection layer to the pooled output of [FlaxCLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.FlaxCLIPVisionModel).
* **text\_model\_output(`FlaxBaseModelOutputWithPooling`):** The output of the [FlaxCLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.FlaxCLIPTextModel).
* **vision\_model\_output(`FlaxBaseModelOutputWithPooling`):** The output of the [FlaxCLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.FlaxCLIPVisionModel).

The [FlaxVisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.FlaxVisionTextDualEncoderModel) forward method, overrides the `__call__` special method.

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

Examples:

Copied

```
>>> from PIL import Image
>>> import requests
>>> import jax
>>> from transformers import (
...     FlaxVisionTextDualEncoderModel,
...     VisionTextDualEncoderProcessor,
...     AutoImageProcessor,
...     AutoTokenizer,
... )

>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> image_processor = AutoImageProcesor.from_pretrained("google/vit-base-patch16-224")
>>> processor = VisionTextDualEncoderProcessor(image_processor, tokenizer)
>>> model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
...     "google/vit-base-patch16-224", "bert-base-uncased"
... )

>>> # contrastive training
>>> urls = [
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     "https://farm3.staticflickr.com/2674/5850229113_4fe05d5265_z.jpg",
... ]
>>> images = [Image.open(requests.get(url, stream=True).raw) for url in urls]
>>> inputs = processor(
...     text=["a photo of a cat", "a photo of a dog"], images=images, return_tensors="np", padding=True
... )
>>> outputs = model(
...     input_ids=inputs.input_ids,
...     attention_mask=inputs.attention_mask,
...     pixel_values=inputs.pixel_values,
... )
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score

>>> # save and load from pretrained
>>> model.save_pretrained("vit-bert")
>>> model = FlaxVisionTextDualEncoderModel.from_pretrained("vit-bert")

>>> # inference
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = jax.nn.softmax(logits_per_image, axis=1)  # we can take the softmax to get the label probabilities
```

### TFVisionTextDualEncoderModel

#### class transformers.TFVisionTextDualEncoderModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_tf_vision_text_dual_encoder.py#L176)

( \*args\*\*kwargs )

Parameters

* **config** ([VisionEncoderDecoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-encoder-decoder#transformers.VisionEncoderDecoderConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.

This class can be used to initialize a vision-text dual encoder model with any pretrained vision autoencoding model as the vision encoder and any pretrained text model as the text encoder. The vision and text encoders are loaded via the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.FlaxAutoModelForVision2Seq.from_pretrained) method. The projection layers are automatically added to the model and should be fine-tuned on a downstream task, like contrastive image-text modeling.

In [LiT: Zero-Shot Transfer with Locked-image Text Tuning](https://arxiv.org/abs/2111.07991) it is shown how leveraging pre-trained (locked/frozen) image and text model for contrastive learning yields significant improvment on new zero-shot vision tasks such as image classification or retrieval.

After such a Vision-Text-Dual-Encoder model has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples for more information).

This model inherits from [TFPreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.TFPreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a Keras [Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular Keras Model and refer to the TF documentation for all matter related to general usage and behavior.

**call**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/vision_text_dual_encoder/modeling_tf_vision_text_dual_encoder.py#L341)

( input\_ids: tf.Tensor | None = Nonepixel\_values: tf.Tensor | None = Noneattention\_mask: tf.Tensor | None = Noneposition\_ids: tf.Tensor | None = Nonereturn\_loss: Optional\[bool] = Nonetoken\_type\_ids: tf.Tensor | None = Noneoutput\_attentions: Optional\[bool] = Noneoutput\_hidden\_states: Optional\[bool] = Nonereturn\_dict: Optional\[bool] = Nonetraining: bool = False ) → `transformers.models.clip.modeling_tf_clip.TFCLIPOutput` or `tuple(tf.Tensor)`

Parameters

* **input\_ids** (`tf.Tensor` of shape `(batch_size, sequence_length)`) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

  Indices can be obtained using [AutoTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast.encode) and [PreTrainedTokenizer.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vits#transformers.VitsTokenizer.__call__) for details.

  [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`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**.

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **position\_ids** (`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]`.

  [What are position IDs?](https://huggingface.co/docs/transformers/glossary#position-ids)
* **pixel\_values** (`tf.Tensor` 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 an image processor (e.g. if you use ViT as the encoder, you should use [AutoImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor)). See [ViTImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for details.
* **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.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

Returns

`transformers.models.clip.modeling_tf_clip.TFCLIPOutput` or `tuple(tf.Tensor)`

A `transformers.models.clip.modeling_tf_clip.TFCLIPOutput` 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 ([VisionTextDualEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)) 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.
* **text\_embeds(`tf.Tensor`** of shape `(batch_size, output_dim`) — The text embeddings obtained by applying the projection layer to the pooled output of [TFCLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.TFCLIPTextModel).
* **image\_embeds(`tf.Tensor`** of shape `(batch_size, output_dim`) — The image embeddings obtained by applying the projection layer to the pooled output of [TFCLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.TFCLIPVisionModel).
* **text\_model\_output(`~modeling_tf_utils.TFBaseModelOutputWithPooling`):** The output of the [TFCLIPTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.TFCLIPTextModel).
* **vision\_model\_output(`~modeling_tf_utils.TFBaseModelOutputWithPooling`):** The output of the [TFCLIPVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.TFCLIPVisionModel).

The [TFVisionTextDualEncoderModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/vision-text-dual-encoder#transformers.TFVisionTextDualEncoderModel) forward method, overrides the `__call__` special method.

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

Examples:

Copied

```
>>> from PIL import Image
>>> import requests
>>> from transformers import (
...     TFVisionTextDualEncoderModel,
...     VisionTextDualEncoderProcessor,
...     AutoImageProcessor,
...     AutoTokenizer,
... )

>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> processor = VisionTextDualEncoderProcessor(image_processor, tokenizer)
>>> model = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
...     "google/vit-base-patch16-224", "bert-base-uncased"
... )

>>> # contrastive training
>>> urls = [
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     "https://farm3.staticflickr.com/2674/5850229113_4fe05d5265_z.jpg",
... ]
>>> images = [Image.open(requests.get(url, stream=True).raw) for url in urls]
>>> inputs = processor(
...     text=["a photo of a cat", "a photo of a dog"], images=images, return_tensors="np", padding=True
... )
>>> outputs = model(
...     input_ids=inputs.input_ids,
...     attention_mask=inputs.attention_mask,
...     pixel_values=inputs.pixel_values,
...     return_loss=True,
... )
>>> loss, logits_per_image = outputs.loss, outputs.logits_per_image  # this is the image-text similarity score

>>> # save and load from pretrained
>>> model.save_pretrained("vit-bert")
>>> model = TFVisionTextDualEncoderModel.from_pretrained("vit-bert")

>>> # inference
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = tf.nn.softmax(logits_per_image, axis=1)  # we can take the softmax to get the label probabilities
```
