# OWL-ViT

## OWL-ViT

### Overview

The OWL-ViT (short for Vision Transformer for Open-World Localization) was proposed in [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby. OWL-ViT is an open-vocabulary object detection network trained on a variety of (image, text) pairs. It can be used to query an image with one or multiple text queries to search for and detect target objects described in text.

The abstract from the paper is the following:

*Combining simple architectures with large-scale pre-training has led to massive improvements in image classification. For object detection, pre-training and scaling approaches are less well established, especially in the long-tailed and open-vocabulary setting, where training data is relatively scarce. In this paper, we propose a strong recipe for transferring image-text models to open-vocabulary object detection. We use a standard Vision Transformer architecture with minimal modifications, contrastive image-text pre-training, and end-to-end detection fine-tuning. Our analysis of the scaling properties of this setup shows that increasing image-level pre-training and model size yield consistent improvements on the downstream detection task. We provide the adaptation strategies and regularizations needed to attain very strong performance on zero-shot text-conditioned and one-shot image-conditioned object detection. Code and models are available on GitHub.*

### Usage

OWL-ViT is a zero-shot text-conditioned object detection model. OWL-ViT uses [CLIP](https://huggingface.co/docs/transformers/model_doc/clip) as its multi-modal backbone, with a ViT-like Transformer to get visual features and a causal language model to get the text features. To use CLIP for detection, OWL-ViT removes the final token pooling layer of the vision model and attaches a lightweight classification and box head to each transformer output token. Open-vocabulary classification is enabled by replacing the fixed classification layer weights with the class-name embeddings obtained from the text model. The authors first train CLIP from scratch and fine-tune it end-to-end with the classification and box heads on standard detection datasets using a bipartite matching loss. One or multiple text queries per image can be used to perform zero-shot text-conditioned object detection.

[OwlViTImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor) can be used to resize (or rescale) and normalize images for the model and [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTokenizer) is used to encode the text. [OwlViTProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTProcessor) wraps [OwlViTImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor) and [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTokenizer) into a single instance to both encode the text and prepare the images. The following example shows how to perform object detection using [OwlViTProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTProcessor) and [OwlViTForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection).

Copied

```
>>> import requests
>>> from PIL import Image
>>> import torch

>>> from transformers import OwlViTProcessor, OwlViTForObjectDetection

>>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> texts = [["a photo of a cat", "a photo of a dog"]]
>>> inputs = processor(text=texts, images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.Tensor([image.size[::-1]])
>>> # Convert outputs (bounding boxes and class logits) to COCO API
>>> results = processor.post_process_object_detection(outputs=outputs, target_sizes=target_sizes, threshold=0.1)
>>> i = 0  # Retrieve predictions for the first image for the corresponding text queries
>>> text = texts[i]
>>> boxes, scores, labels = results[i]["boxes"], results[i]["scores"], results[i]["labels"]
>>> for box, score, label in zip(boxes, scores, labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text[label]} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]
```

This model was contributed by [adirik](https://huggingface.co/adirik). The original code can be found [here](https://github.com/google-research/scenic/tree/main/scenic/projects/owl_vit).

### OwlViTConfig

#### class transformers.OwlViTConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/configuration_owlvit.py#L251)

( text\_config = Nonevision\_config = Noneprojection\_dim = 512logit\_scale\_init\_value = 2.6592return\_dict = True\*\*kwargs )

Parameters

* **text\_config** (`dict`, *optional*) — Dictionary of configuration options used to initialize [OwlViTTextConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextConfig).
* **vision\_config** (`dict`, *optional*) — Dictionary of configuration options used to initialize [OwlViTVisionConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionConfig).
* **projection\_dim** (`int`, *optional*, defaults to 512) — Dimensionality of text and vision projection layers.
* **logit\_scale\_init\_value** (`float`, *optional*, defaults to 2.6592) — The inital value of the *logit\_scale* parameter. Default is used as per the original OWL-ViT implementation.
* **kwargs** (*optional*) — Dictionary of keyword arguments.

[OwlViTConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTConfig) is the configuration class to store the configuration of an [OwlViTModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTModel). It is used to instantiate an OWL-ViT model according to the specified arguments, defining the text model and vision model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the OWL-ViT [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.

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.

**from\_text\_vision\_configs**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/configuration_owlvit.py#L318)

( text\_config: typing.Dictvision\_config: typing.Dict\*\*kwargs ) → [OwlViTConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTConfig)

Returns

[OwlViTConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTConfig)

An instance of a configuration object

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

### OwlViTTextConfig

#### class transformers.OwlViTTextConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/configuration_owlvit.py#L40)

( vocab\_size = 49408hidden\_size = 512intermediate\_size = 2048num\_hidden\_layers = 12num\_attention\_heads = 8max\_position\_embeddings = 16hidden\_act = 'quick\_gelu'layer\_norm\_eps = 1e-05attention\_dropout = 0.0initializer\_range = 0.02initializer\_factor = 1.0pad\_token\_id = 0bos\_token\_id = 49406eos\_token\_id = 49407\*\*kwargs )

Parameters

* **vocab\_size** (`int`, *optional*, defaults to 49408) — Vocabulary size of the OWL-ViT text model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **hidden\_size** (`int`, *optional*, defaults to 512) — Dimensionality of the encoder layers and the pooler layer.
* **intermediate\_size** (`int`, *optional*, defaults to 2048) — 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 8) — Number of attention heads for each attention layer in the Transformer encoder.
* **max\_position\_embeddings** (`int`, *optional*, defaults to 16) — The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
* **hidden\_act** (`str` or `function`, *optional*, defaults to `"quick_gelu"`) — The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` \``"quick_gelu"` are supported.
* **layer\_norm\_eps** (`float`, *optional*, defaults to 1e-5) — The epsilon used by the layer normalization layers.
* **attention\_dropout** (`float`, *optional*, defaults to 0.0) — The dropout ratio for the attention probabilities.
* **initializer\_range** (`float`, *optional*, defaults to 0.02) — The standard deviation of the truncated\_normal\_initializer for initializing all weight matrices.
* **initializer\_factor** (`float`, *optional*, defaults to 1) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).

This is the configuration class to store the configuration of an [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel). It is used to instantiate an OwlViT text 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 OwlViT [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.

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.

Example:

Copied

```
>>> from transformers import OwlViTTextConfig, OwlViTTextModel

>>> # Initializing a OwlViTTextModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTTextConfig()

>>> # Initializing a OwlViTTextConfig from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

### OwlViTVisionConfig

#### class transformers.OwlViTVisionConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/configuration_owlvit.py#L146)

( hidden\_size = 768intermediate\_size = 3072num\_hidden\_layers = 12num\_attention\_heads = 12num\_channels = 3image\_size = 768patch\_size = 32hidden\_act = 'quick\_gelu'layer\_norm\_eps = 1e-05attention\_dropout = 0.0initializer\_range = 0.02initializer\_factor = 1.0\*\*kwargs )

Parameters

* **hidden\_size** (`int`, *optional*, defaults to 768) — Dimensionality of the encoder layers and the pooler layer.
* **intermediate\_size** (`int`, *optional*, defaults to 3072) — Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.
* **num\_hidden\_layers** (`int`, *optional*, defaults to 12) — Number of hidden layers in the Transformer encoder.
* **num\_attention\_heads** (`int`, *optional*, defaults to 12) — Number of attention heads for each attention layer in the Transformer encoder.
* **num\_channels** (`int`, *optional*, defaults to 3) — Number of channels in the input images.
* **image\_size** (`int`, *optional*, defaults to 768) — The size (resolution) of each image.
* **patch\_size** (`int`, *optional*, defaults to 32) — The size (resolution) of each patch.
* **hidden\_act** (`str` or `function`, *optional*, defaults to `"quick_gelu"`) — The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` \``"quick_gelu"` are supported.
* **layer\_norm\_eps** (`float`, *optional*, defaults to 1e-5) — The epsilon used by the layer normalization layers.
* **attention\_dropout** (`float`, *optional*, defaults to 0.0) — The dropout ratio for the attention probabilities.
* **initializer\_range** (`float`, *optional*, defaults to 0.02) — The standard deviation of the truncated\_normal\_initializer for initializing all weight matrices.
* **initializer\_factor** (\`float“, *optional*, defaults to 1) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).

This is the configuration class to store the configuration of an [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel). It is used to instantiate an OWL-ViT image 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 OWL-ViT [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.

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.

Example:

Copied

```
>>> from transformers import OwlViTVisionConfig, OwlViTVisionModel

>>> # Initializing a OwlViTVisionModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTVisionConfig()

>>> # Initializing a OwlViTVisionModel model from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTVisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

### OwlViTImageProcessor

#### class transformers.OwlViTImageProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/image_processing_owlvit.py#L91)

( do\_resize = Truesize = Noneresample = \<Resampling.BICUBIC: 3>do\_center\_crop = Falsecrop\_size = Nonedo\_rescale = Truerescale\_factor = 0.00392156862745098do\_normalize = Trueimage\_mean = Noneimage\_std = None\*\*kwargs )

Parameters

* **do\_resize** (`bool`, *optional*, defaults to `True`) — Whether to resize the shorter edge of the input to a certain `size`.
* **size** (`Dict[str, int]`, *optional*, defaults to {“height” — 768, “width”: 768}): The size to use for resizing the image. Only has an effect if `do_resize` is set to `True`. If `size` is a sequence like (h, w), output size will be matched to this. If `size` is an int, then image will be resized to (size, size).
* **resample** (`int`, *optional*, defaults to `PIL.Image.Resampling.BICUBIC`) — An optional resampling filter. This can be one of `PIL.Image.Resampling.NEAREST`, `PIL.Image.Resampling.BOX`, `PIL.Image.Resampling.BILINEAR`, `PIL.Image.Resampling.HAMMING`, `PIL.Image.Resampling.BICUBIC` or `PIL.Image.Resampling.LANCZOS`. Only has an effect if `do_resize` is set to `True`.
* **do\_center\_crop** (`bool`, *optional*, defaults to `False`) — Whether to crop the input at the center. If the input size is smaller than `crop_size` along any edge, the image is padded with 0’s and then center cropped.
* **crop\_size** (`int`, *optional*, defaults to {“height” — 768, “width”: 768}): The size to use for center cropping the image. Only has an effect if `do_center_crop` is set to `True`.
* **do\_rescale** (`bool`, *optional*, defaults to `True`) — Whether to rescale the input by a certain factor.
* **rescale\_factor** (`float`, *optional*, defaults to `1/255`) — The factor to use for rescaling the image. Only has an effect if `do_rescale` is set to `True`.
* **do\_normalize** (`bool`, *optional*, defaults to `True`) — Whether or not to normalize the input with `image_mean` and `image_std`. Desired output size when applying center-cropping. Only has an effect if `do_center_crop` is set to `True`.
* **image\_mean** (`List[int]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`) — The sequence of means for each channel, to be used when normalizing images.
* **image\_std** (`List[int]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`) — The sequence of standard deviations for each channel, to be used when normalizing images.

Constructs an OWL-ViT image processor.

This image processor inherits from [ImageProcessingMixin](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/image_processor#transformers.ImageProcessingMixin) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

**preprocess**

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

( images: typing.Union\[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List\[ForwardRef('PIL.Image.Image')], typing.List\[numpy.ndarray], typing.List\[ForwardRef('torch.Tensor')]]do\_resize: typing.Optional\[bool] = Nonesize: typing.Union\[typing.Dict\[str, int], NoneType] = Noneresample: Resampling = Nonedo\_center\_crop: typing.Optional\[bool] = Nonecrop\_size: typing.Union\[typing.Dict\[str, int], NoneType] = Nonedo\_rescale: typing.Optional\[bool] = Nonerescale\_factor: typing.Optional\[float] = Nonedo\_normalize: typing.Optional\[bool] = Noneimage\_mean: typing.Union\[float, typing.List\[float], NoneType] = Noneimage\_std: typing.Union\[float, typing.List\[float], NoneType] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType] = Nonedata\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension] = \<ChannelDimension.FIRST: 'channels\_first'>input\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = None\*\*kwargs )

Parameters

* **images** (`ImageInput`) — The image or batch of images to be prepared. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
* **do\_resize** (`bool`, *optional*, defaults to `self.do_resize`) — Whether or not to resize the input. If `True`, will resize the input to the size specified by `size`.
* **size** (`Dict[str, int]`, *optional*, defaults to `self.size`) — The size to resize the input to. Only has an effect if `do_resize` is set to `True`.
* **resample** (`PILImageResampling`, *optional*, defaults to `self.resample`) — The resampling filter to use when resizing the input. Only has an effect if `do_resize` is set to `True`.
* **do\_center\_crop** (`bool`, *optional*, defaults to `self.do_center_crop`) — Whether or not to center crop the input. If `True`, will center crop the input to the size specified by `crop_size`.
* **crop\_size** (`Dict[str, int]`, *optional*, defaults to `self.crop_size`) — The size to center crop the input to. Only has an effect if `do_center_crop` is set to `True`.
* **do\_rescale** (`bool`, *optional*, defaults to `self.do_rescale`) — Whether or not to rescale the input. If `True`, will rescale the input by dividing it by `rescale_factor`.
* **rescale\_factor** (`float`, *optional*, defaults to `self.rescale_factor`) — The factor to rescale the input by. Only has an effect if `do_rescale` is set to `True`.
* **do\_normalize** (`bool`, *optional*, defaults to `self.do_normalize`) — Whether or not to normalize the input. If `True`, will normalize the input by subtracting `image_mean` and dividing by `image_std`.
* **image\_mean** (`Union[float, List[float]]`, *optional*, defaults to `self.image_mean`) — The mean to subtract from the input when normalizing. Only has an effect if `do_normalize` is set to `True`.
* **image\_std** (`Union[float, List[float]]`, *optional*, defaults to `self.image_std`) — The standard deviation to divide the input by when normalizing. Only has an effect if `do_normalize` is set to `True`.
* **return\_tensors** (`str` or `TensorType`, *optional*) — The type of tensors to return. Can be one of:
  * Unset: Return a list of `np.ndarray`.
  * `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  * `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  * `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  * `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
* **data\_format** (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`) — The channel dimension format for the output image. Can be one of:
  * `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `ChannelDimension.LAST`: image in (height, width, num\_channels) format.
  * Unset: defaults to the channel dimension format of the input image.
* **input\_data\_format** (`ChannelDimension` or `str`, *optional*) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
  * `"channels_first"` or `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num\_channels) format.
  * `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

Prepares an image or batch of images for the model.

**post\_process\_object\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/image_processing_owlvit.py#L458)

( outputsthreshold: float = 0.1target\_sizes: typing.Union\[transformers.utils.generic.TensorType, typing.List\[typing.Tuple]] = None ) → `List[Dict]`

Parameters

* **outputs** (`OwlViTObjectDetectionOutput`) — Raw outputs of the model.
* **threshold** (`float`, *optional*) — Score threshold to keep object detection predictions.
* **target\_sizes** (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*) — Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size `(height, width)` of each image in the batch. If unset, predictions will not be resized.

Returns

`List[Dict]`

A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model.

Converts the raw output of [OwlViTForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection) into final bounding boxes in (top\_left\_x, top\_left\_y, bottom\_right\_x, bottom\_right\_y) format.

**post\_process\_image\_guided\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/image_processing_owlvit.py#L514)

( outputsthreshold = 0.0nms\_threshold = 0.3target\_sizes = None ) → `List[Dict]`

Parameters

* **outputs** (`OwlViTImageGuidedObjectDetectionOutput`) — Raw outputs of the model.
* **threshold** (`float`, *optional*, defaults to 0.0) — Minimum confidence threshold to use to filter out predicted boxes.
* **nms\_threshold** (`float`, *optional*, defaults to 0.3) — IoU threshold for non-maximum suppression of overlapping boxes.
* **target\_sizes** (`torch.Tensor`, *optional*) — Tensor of shape (batch\_size, 2) where each entry is the (height, width) of the corresponding image in the batch. If set, predicted normalized bounding boxes are rescaled to the target sizes. If left to None, predictions will not be unnormalized.

Returns

`List[Dict]`

A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model. All labels are set to None as `OwlViTForObjectDetection.image_guided_detection` perform one-shot object detection.

Converts the output of [OwlViTForObjectDetection.image\_guided\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection.image_guided_detection) into the format expected by the COCO api.

### OwlViTFeatureExtractor

#### class transformers.OwlViTFeatureExtractor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/feature_extraction_owlvit.py#L26)

( \*args\*\*kwargs )

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

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/image_processing_utils.py#L544)

( images\*\*kwargs )

Preprocess an image or a batch of images.

**post\_process**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/image_processing_owlvit.py#L412)

( outputstarget\_sizes ) → `List[Dict]`

Parameters

* **outputs** (`OwlViTObjectDetectionOutput`) — Raw outputs of the model.
* **target\_sizes** (`torch.Tensor` of shape `(batch_size, 2)`) — Tensor containing the size (h, w) of each image of the batch. For evaluation, this must be the original image size (before any data augmentation). For visualization, this should be the image size after data augment, but before padding.

Returns

`List[Dict]`

A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model.

Converts the raw output of [OwlViTForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection) into final bounding boxes in (top\_left\_x, top\_left\_y, bottom\_right\_x, bottom\_right\_y) format.

**post\_process\_image\_guided\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/image_processing_owlvit.py#L514)

( outputsthreshold = 0.0nms\_threshold = 0.3target\_sizes = None ) → `List[Dict]`

Parameters

* **outputs** (`OwlViTImageGuidedObjectDetectionOutput`) — Raw outputs of the model.
* **threshold** (`float`, *optional*, defaults to 0.0) — Minimum confidence threshold to use to filter out predicted boxes.
* **nms\_threshold** (`float`, *optional*, defaults to 0.3) — IoU threshold for non-maximum suppression of overlapping boxes.
* **target\_sizes** (`torch.Tensor`, *optional*) — Tensor of shape (batch\_size, 2) where each entry is the (height, width) of the corresponding image in the batch. If set, predicted normalized bounding boxes are rescaled to the target sizes. If left to None, predictions will not be unnormalized.

Returns

`List[Dict]`

A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model. All labels are set to None as `OwlViTForObjectDetection.image_guided_detection` perform one-shot object detection.

Converts the output of [OwlViTForObjectDetection.image\_guided\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection.image_guided_detection) into the format expected by the COCO api.

### OwlViTProcessor

#### class transformers.OwlViTProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/processing_owlvit.py#L29)

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

Parameters

* **image\_processor** ([OwlViTImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor)) — The image processor is a required input.
* **tokenizer** (\[`CLIPTokenizer`, `CLIPTokenizerFast`]) — The tokenizer is a required input.

Constructs an OWL-ViT processor which wraps [OwlViTImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor) and [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTokenizer)/[CLIPTokenizerFast](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/clip#transformers.CLIPTokenizerFast) into a single processor that interits both the image processor and tokenizer functionalities. See the `__call__()` and [decode()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTProcessor.decode) for more information.

**batch\_decode**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/processing_owlvit.py#L196)

( \*args\*\*kwargs )

This method forwards all its arguments to CLIPTokenizerFast’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/owlvit/processing_owlvit.py#L203)

( \*args\*\*kwargs )

This method forwards all its arguments to CLIPTokenizerFast’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.

**post\_process**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/processing_owlvit.py#L175)

( \*args\*\*kwargs )

This method forwards all its arguments to [OwlViTImageProcessor.post\_process()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTFeatureExtractor.post_process). Please refer to the docstring of this method for more information.

**post\_process\_image\_guided\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/processing_owlvit.py#L189)

( \*args\*\*kwargs )

This method forwards all its arguments to `OwlViTImageProcessor.post_process_one_shot_object_detection`. Please refer to the docstring of this method for more information.

**post\_process\_object\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/processing_owlvit.py#L182)

( \*args\*\*kwargs )

This method forwards all its arguments to [OwlViTImageProcessor.post\_process\_object\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor.post_process_object_detection). Please refer to the docstring of this method for more information.

### OwlViTModel

#### class transformers.OwlViTModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1038)

( config: OwlViTConfig )

Parameters

* **This** model is 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. — config ([OwlViTConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTConfig)): 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.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1153)

( input\_ids: typing.Optional\[torch.LongTensor] = Nonepixel\_values: typing.Optional\[torch.FloatTensor] = Noneattention\_mask: typing.Optional\[torch.Tensor] = Nonereturn\_loss: typing.Optional\[bool] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_base\_image\_embeds: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.owlvit.modeling_owlvit.OwlViTOutput` 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 [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)
* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values.
* **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.owlvit.modeling_owlvit.OwlViTOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.owlvit.modeling_owlvit.OwlViTOutput` 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.owlvit.configuration_owlvit.OwlViTConfig'>`) 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 * num_max_text_queries, output_dim`) — The text embeddings obtained by applying the projection layer to the pooled output of [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **image\_embeds** (`torch.FloatTensor` of shape `(batch_size, output_dim`) — The image embeddings obtained by applying the projection layer to the pooled output of [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel).
* **text\_model\_output** (Tuple`BaseModelOutputWithPooling`) — The output of the [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **vision\_model\_output** (`BaseModelOutputWithPooling`) — The output of the [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel).

The [OwlViTModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTModel) 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 AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(text=[["a photo of a cat", "a photo of a dog"]], images=image, return_tensors="pt")
>>> 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
```

**get\_text\_features**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1073)

( input\_ids: typing.Optional\[torch.Tensor] = Noneattention\_mask: typing.Optional\[torch.Tensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → text\_features (`torch.FloatTensor` of shape `(batch_size, output_dim`)

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`) — Indices of input sequence tokens in the vocabulary. 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, num_max_text_queries, 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)
* **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

text\_features (`torch.FloatTensor` of shape `(batch_size, output_dim`)

The text embeddings obtained by applying the projection layer to the pooled output of [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).

The [OwlViTModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTModel) 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 transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> text_features = model.get_text_features(**inputs)
```

**get\_image\_features**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1108)

( pixel\_values: typing.Optional\[torch.FloatTensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → image\_features (`torch.FloatTensor` of shape `(batch_size, output_dim`)

Parameters

* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values.
* **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

image\_features (`torch.FloatTensor` of shape `(batch_size, output_dim`)

The image embeddings obtained by applying the projection layer to the pooled output of [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel).

The [OwlViTModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTModel) 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 AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> image_features = model.get_image_features(**inputs)
```

### OwlViTTextModel

#### class transformers.OwlViTTextModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L877)

( config: OwlViTTextConfig )

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L892)

( input\_ids: Tensorattention\_mask: typing.Optional\[torch.Tensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → [transformers.modeling\_outputs.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`) — Indices of input sequence tokens in the vocabulary. 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, num_max_text_queries, 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)
* **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.modeling\_outputs.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`

A [transformers.modeling\_outputs.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 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.owlvit.configuration_owlvit.OwlViTTextConfig'>`) 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 [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel) 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 transformers import AutoProcessor, OwlViTTextModel

>>> model = OwlViTTextModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
```

### OwlViTVisionModel

#### class transformers.OwlViTVisionModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L987)

( config: OwlViTVisionConfig )

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1000)

( 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.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values.
* **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.modeling\_outputs.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`

A [transformers.modeling\_outputs.BaseModelOutputWithPooling](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 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.owlvit.configuration_owlvit.OwlViTVisionConfig'>`) 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 [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel) 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 AutoProcessor, OwlViTVisionModel

>>> model = OwlViTVisionModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled CLS states
```

### OwlViTForObjectDetection

#### class transformers.OwlViTForObjectDetection

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1320)

( config: OwlViTConfig )

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1622)

( input\_ids: Tensorpixel\_values: FloatTensorattention\_mask: typing.Optional\[torch.Tensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutput` or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values.
* **input\_ids** (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`, *optional*) — Indices of input sequence tokens in the vocabulary. 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, num_max_text_queries, 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)
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the last hidden state. See `text_model_last_hidden_state` and `vision_model_last_hidden_state` 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.owlvit.modeling_owlvit.OwlViTObjectDetectionOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutput` 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.owlvit.configuration_owlvit.OwlViTConfig'>`) and inputs.

* **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)) — Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized scale-invariant IoU loss.
* **loss\_dict** (`Dict`, *optional*) — A dictionary containing the individual losses. Useful for logging.
* **logits** (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`) — Classification logits (including no-object) for all queries.
* **pred\_boxes** (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`) — Normalized boxes coordinates for all queries, represented as (center\_x, center\_y, width, height). These values are normalized in \[0, 1], relative to the size of each individual image in the batch (disregarding possible padding). You can use [post\_process\_object\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor.post_process_object_detection) to retrieve the unnormalized bounding boxes.
* **text\_embeds** (`torch.FloatTensor` of shape `(batch_size, num_max_text_queries, output_dim`) — The text embeddings obtained by applying the projection layer to the pooled output of [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **image\_embeds** (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`) — Pooled output of [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel). OWL-ViT represents images as a set of image patches and computes image embeddings for each patch.
* **class\_embeds** (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`) — Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total number of patches is (image\_size / patch\_size)\*\*2.
* **text\_model\_output** (Tuple`BaseModelOutputWithPooling`) — The output of the [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **vision\_model\_output** (`BaseModelOutputWithPooling`) — The output of the [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel).

The [OwlViTForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection) 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

```
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import AutoProcessor, OwlViTForObjectDetection

>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> texts = [["a photo of a cat", "a photo of a dog"]]
>>> inputs = processor(text=texts, images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.Tensor([image.size[::-1]])
>>> # Convert outputs (bounding boxes and class logits) to final bounding boxes and scores
>>> results = processor.post_process_object_detection(
...     outputs=outputs, threshold=0.1, target_sizes=target_sizes
... )

>>> i = 0  # Retrieve predictions for the first image for the corresponding text queries
>>> text = texts[i]
>>> boxes, scores, labels = results[i]["boxes"], results[i]["scores"], results[i]["labels"]

>>> for box, score, label in zip(boxes, scores, labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text[label]} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]
```

**image\_guided\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/owlvit/modeling_owlvit.py#L1527)

( pixel\_values: FloatTensorquery\_pixel\_values: typing.Optional\[torch.FloatTensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutput` or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values.
* **query\_pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values of query image(s) to be detected. Pass in one query image per target image.
* **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.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutput` 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.owlvit.configuration_owlvit.OwlViTConfig'>`) and inputs.

* **logits** (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`) — Classification logits (including no-object) for all queries.
* **target\_pred\_boxes** (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`) — Normalized boxes coordinates for all queries, represented as (center\_x, center\_y, width, height). These values are normalized in \[0, 1], relative to the size of each individual target image in the batch (disregarding possible padding). You can use [post\_process\_object\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor.post_process_object_detection) to retrieve the unnormalized bounding boxes.
* **query\_pred\_boxes** (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`) — Normalized boxes coordinates for all queries, represented as (center\_x, center\_y, width, height). These values are normalized in \[0, 1], relative to the size of each individual query image in the batch (disregarding possible padding). You can use [post\_process\_object\_detection()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTImageProcessor.post_process_object_detection) to retrieve the unnormalized bounding boxes.
* **image\_embeds** (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`) — Pooled output of [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel). OWL-ViT represents images as a set of image patches and computes image embeddings for each patch.
* **query\_image\_embeds** (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`) — Pooled output of [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel). OWL-ViT represents images as a set of image patches and computes image embeddings for each patch.
* **class\_embeds** (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`) — Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total number of patches is (image\_size / patch\_size)\*\*2.
* **text\_model\_output** (Tuple`BaseModelOutputWithPooling`) — The output of the [OwlViTTextModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTTextModel).
* **vision\_model\_output** (`BaseModelOutputWithPooling`) — The output of the [OwlViTVisionModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTVisionModel).

The [OwlViTForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/owlvit#transformers.OwlViTForObjectDetection) 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

```
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import AutoProcessor, OwlViTForObjectDetection

>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch16")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
>>> query_image = Image.open(requests.get(query_url, stream=True).raw)
>>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model.image_guided_detection(**inputs)
>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.Tensor([image.size[::-1]])
>>> # Convert outputs (bounding boxes and class logits) to COCO API
>>> results = processor.post_process_image_guided_detection(
...     outputs=outputs, threshold=0.6, nms_threshold=0.3, target_sizes=target_sizes
... )
>>> i = 0  # Retrieve predictions for the first image
>>> boxes, scores = results[i]["boxes"], results[i]["scores"]
>>> for box, score in zip(boxes, scores):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
Detected similar object with confidence 0.856 at location [10.94, 50.4, 315.8, 471.39]
Detected similar object with confidence 1.0 at location [334.84, 25.33, 636.16, 374.71]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://boinc-ai.gitbook.io/transformers/api/models/multimodal-models/owl-vit.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
