---
local: visiontextdualencoder
sections:
- local: overview
  title: Overview
- local: transformers.VisionTextDualEncoderConfig
  title: VisionTextDualEncoderConfig
- local: transformers.VisionTextDualEncoderProcessor
  title: VisionTextDualEncoderProcessor
- local: transformers.VisionTextDualEncoderModel
  title: VisionTextDualEncoderModel
- local: transformers.FlaxVisionTextDualEncoderModel
  title: FlaxVisionTextDualEncoderModel
title: VisionTextDualEncoder
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2021 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="visiontextdualencoder">VisionTextDualEncoder</h1>

<h2 id="overview">Overview</h2>

The [VisionTextDualEncoderModel](/docs/transformers/pr_15592/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](vit), [BEiT](beit), [DeiT](deit)) and any pretrained text autoencoding model as the text encoder (*e.g.* [RoBERTa](roberta), [BERT](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 improvment on
new zero-shot vision tasks such as image classification or retrieval.

<h2 id="transformers.VisionTextDualEncoderConfig">VisionTextDualEncoderConfig</h2>

<div class="docstring">

<docstring><name>class transformers.VisionTextDualEncoderConfig</name><anchor>transformers.VisionTextDualEncoderConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L28</source><parameters>[{"name": "projection_dim", "val": " = 512"}, {"name": "logit_scale_init_value", "val": " = 2.6592"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **text_config_dict** (`dict`) --
  Dictionary of configuration options that defines text model config.
- **vision_config_dict** (`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.</paramsdesc><paramgroups>0</paramgroups></docstring>

[VisionTextDualEncoderConfig](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig) is the configuration class to store the configuration of a
[VisionTextDualEncoderModel](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel). It is used to instantiate [VisionTextDualEncoderModel](/docs/transformers/pr_15592/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](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.



Examples:

```python
>>> 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
>>> 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("my-model")

>>> # 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)
```


<div class="docstring">
<docstring><name>from\_vision\_text\_configs</name><anchor>transformers.VisionTextDualEncoderConfig.from_vision_text_configs</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L105</source><parameters>[{"name": "vision_config", "val": ": PretrainedConfig"}, {"name": "text_config", "val": ": PretrainedConfig"}, {"name": "**kwargs", "val": ""}]</parameters><rettype>[VisionTextDualEncoderConfig](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig)</rettype><retdesc>An instance of a configuration object</retdesc></docstring>

Instantiate a [VisionTextDualEncoderConfig](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderConfig) (or a derived class) from text model configuration and vision
model configuration.






</div>
<div class="docstring">
<docstring><name>to\_dict</name><anchor>transformers.VisionTextDualEncoderConfig.to_dict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L117</source><parameters>[]</parameters><rettype>`Dict[str, any]`</rettype><retdesc>Dictionary of all the attributes that make up this configuration instance,</retdesc></docstring>

Serializes this instance to a Python dictionary. Override the default [to_dict()](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig.to_dict).






</div></div>

<h2 id="transformers.VisionTextDualEncoderProcessor">VisionTextDualEncoderProcessor</h2>

<div class="docstring">

<docstring><name>class transformers.VisionTextDualEncoderProcessor</name><anchor>transformers.VisionTextDualEncoderProcessor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L23</source><parameters>[{"name": "feature_extractor", "val": ""}, {"name": "tokenizer", "val": ""}]</parameters><paramsdesc>- **feature_extractor** ([AutoFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/auto#transformers.AutoFeatureExtractor)) --
  The feature extractor is a required input.
- **tokenizer** ([PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer)) --
  The tokenizer is a required input.</paramsdesc><paramgroups>0</paramgroups></docstring>

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

[VisionTextDualEncoderProcessor](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderProcessor) offers all the functionalities of [AutoFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/auto#transformers.AutoFeatureExtractor) and
[AutoTokenizer](/docs/transformers/pr_15592/en/model_doc/auto#transformers.AutoTokenizer). See the `__call__()`and
[decode()](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderProcessor.decode) for more information.





<div class="docstring">
<docstring><name>batch\_decode</name><anchor>transformers.VisionTextDualEncoderProcessor.batch_decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L98</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to VisionTextDualEncoderTokenizer's
[batch_decode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode). Please refer to the docstring of this method for more information.


</div>
<div class="docstring">
<docstring><name>decode</name><anchor>transformers.VisionTextDualEncoderProcessor.decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py#L105</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to VisionTextDualEncoderTokenizer's [decode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.decode).
Please refer to the docstring of this method for more information.


</div></div>

<h2 id="transformers.VisionTextDualEncoderModel">VisionTextDualEncoderModel</h2>

<div class="docstring">

<docstring><name>class transformers.VisionTextDualEncoderModel</name><anchor>transformers.VisionTextDualEncoderModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py#L163</source><parameters>[{"name": "config", "val": ": typing.Optional[transformers.models.vision_text_dual_encoder.configuration_vision_text_dual_encoder.VisionTextDualEncoderConfig] = None"}, {"name": "vision_model", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "text_model", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}]</parameters><paramsdesc>- **config** ([VisionEncoderDecoderConfig](/docs/transformers/pr_15592/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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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()`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](/docs/transformers/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.VisionTextDualEncoderModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py#L295</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "pixel_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "return_loss", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **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 [CLIPTokenizer](/docs/transformers/pr_15592/en/model_doc/clip#transformers.CLIPTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../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?](../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?](../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
  a feature extractor (e.g. if you use ViT as the encoder, you should use [ViTFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/vit#transformers.ViTFeatureExtractor)). See
  [ViTFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/vit#transformers.ViTFeatureExtractor.__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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.clip.modeling_clip.CLIPOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>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](/docs/transformers/pr_15592/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](/docs/transformers/pr_15592/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](/docs/transformers/pr_15592/en/model_doc/clip#transformers.CLIPVisionModel).
- **text_model_output(`BaseModelOutputWithPooling`):**
  The output of the [CLIPTextModel](/docs/transformers/pr_15592/en/model_doc/clip#transformers.CLIPTextModel).
- **vision_model_output(`BaseModelOutputWithPooling`):**
  The output of the [CLIPVisionModel](/docs/transformers/pr_15592/en/model_doc/clip#transformers.CLIPVisionModel).</retdesc></docstring>
The [VisionTextDualEncoderModel](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.VisionTextDualEncoderModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Examples:

```python
>>> from PIL import Image
>>> import requests
>>> from transformers import (
...     VisionTextDualEncoderModel,
...     VisionTextDualEncoderProcessor,
...     ViTFeatureExtractor,
...     BertTokenizer,
... )

>>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
>>> feature_extractor = ViTFeatureExtractor.from_pretrained("google/vit-base-patch16-224")
>>> processor = VisionTextDualEncoderProcessor(feature_extractor, 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
```

</div></div>

<h2 id="transformers.FlaxVisionTextDualEncoderModel">FlaxVisionTextDualEncoderModel</h2>

<div class="docstring">

<docstring><name>class transformers.FlaxVisionTextDualEncoderModel</name><anchor>transformers.FlaxVisionTextDualEncoderModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py#L219</source><parameters>[{"name": "config", "val": ": VisionTextDualEncoderConfig"}, {"name": "input_shape", "val": ": typing.Optional[typing.Tuple] = None"}, {"name": "seed", "val": ": int = 0"}, {"name": "dtype", "val": ": dtype = <class 'jax._src.numpy.lax_numpy.float32'>"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([VisionTextDualEncoderConfig](/docs/transformers/pr_15592/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()](/docs/transformers/pr_15592/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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_fp16) and
  [to_bf16()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_bf16).</paramsdesc><paramgroups>0</paramgroups></docstring>

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()`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](/docs/transformers/pr_15592/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)





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.FlaxVisionTextDualEncoderModel.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py#L251</source><parameters>[{"name": "input_ids", "val": ""}, {"name": "pixel_values", "val": ""}, {"name": "attention_mask", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "params", "val": ": dict = None"}, {"name": "dropout_rng", "val": ": PRNGKey = None"}, {"name": "train", "val": ": bool = False"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **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 [PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../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?](../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?](../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
  a feature extractor (e.g. if you use ViT as the encoder, you should use [ViTFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/vit#transformers.ViTFeatureExtractor)). See
  [ViTFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/vit#transformers.ViTFeatureExtractor.__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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.clip.modeling_flax_clip.FlaxCLIPOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>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](/docs/transformers/pr_15592/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](/docs/transformers/pr_15592/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](/docs/transformers/pr_15592/en/model_doc/clip#transformers.FlaxCLIPVisionModel).
- **text_model_output(`FlaxBaseModelOutputWithPooling`):**
  The output of the [FlaxCLIPTextModel](/docs/transformers/pr_15592/en/model_doc/clip#transformers.FlaxCLIPTextModel).
- **vision_model_output(`FlaxBaseModelOutputWithPooling`):**
  The output of the [FlaxCLIPVisionModel](/docs/transformers/pr_15592/en/model_doc/clip#transformers.FlaxCLIPVisionModel).</retdesc></docstring>
The [FlaxVisionTextDualEncoderModel](/docs/transformers/pr_15592/en/model_doc/vision-text-dual-encoder#transformers.FlaxVisionTextDualEncoderModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Examples:

```python
>>> from PIL import Image
>>> import requests
>>> import jax
>>> from transformers import (
...     FlaxVisionTextDualEncoderModel,
...     VisionTextDualEncoderProcessor,
...     ViTFeatureExtractor,
...     BertTokenizer,
... )

>>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
>>> feature_extractor = ViTFeatureExtractor.from_pretrained("google/vit-base-patch16-224")
>>> processor = VisionTextDualEncoderProcessor(feature_extractor, 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
```


</div></div>
