Buckets:
CLIP
CLIP is a is a multimodal vision and language model motivated by overcoming the fixed number of object categories when training a computer vision model. CLIP learns about images directly from raw text by jointly training on 400M (image, text) pairs. Pretraining on this scale enables zero-shot transfer to downstream tasks. CLIP uses an image encoder and text encoder to get visual features and text features. Both features are projected to a latent space with the same number of dimensions and their dot product gives a similarity score.
You can find all the original CLIP checkpoints under the OpenAI organization.
Click on the CLIP models in the right sidebar for more examples of how to apply CLIP to different image and language tasks.
The example below demonstrates how to calculate similarity scores between multiple text descriptions and an image with Pipeline or the AutoModel class.
import torch
from transformers import pipeline
clip = pipeline(
task="zero-shot-image-classification",
model="openai/clip-vit-base-patch32",
dtype=torch.bfloat16,
device=0
)
labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]
clip("http://images.cocodataset.org/val2017/000000039769.jpg", candidate_labels=labels)
import requests
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModel
model = AutoModel.from_pretrained("openai/clip-vit-base-patch32", dtype=torch.bfloat16, attn_implementation="sdpa")
processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]
inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)
outputs = model(**inputs)
logits_per_image = outputs.logits_per_image
probs = logits_per_image.softmax(dim=1)
most_likely_idx = probs.argmax(dim=1).item()
most_likely_label = labels[most_likely_idx]
print(f"Most likely label: {most_likely_label} with probability: {probs[0][most_likely_idx].item():.3f}")
Notes
- Use CLIPImageProcessor to resize (or rescale) and normalizes images for the model.
CLIPConfig[[transformers.CLIPConfig]]
class transformers.CLIPConfigtransformers.CLIPConfigdict, optional) --
Dictionary of configuration options used to initialize CLIPTextConfig.
- vision_config (
dict, optional) -- Dictionary of configuration options used to initialize CLIPVisionConfig. - 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 initial value of the logit_scale parameter. Default is used as per the original CLIP implementation. - kwargs (optional) -- Dictionary of keyword arguments.0
CLIPConfig is the configuration class to store the configuration of a CLIPModel. It is used to instantiate a CLIP 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 CLIP openai/clip-vit-base-patch32 architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import CLIPConfig, CLIPModel
>>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
>>> configuration = CLIPConfig()
>>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
>>> model = CLIPModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
>>> from transformers import CLIPTextConfig, CLIPVisionConfig
>>> # Initializing a CLIPText and CLIPVision configuration
>>> config_text = CLIPTextConfig()
>>> config_vision = CLIPVisionConfig()
>>> config = CLIPConfig(text_config=config_text, vision_config=config_vision)
CLIPTextConfig[[transformers.CLIPTextConfig]]
class transformers.CLIPTextConfigtransformers.CLIPTextConfigint, optional, defaults to 49408) --
Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
the inputs_ids passed when calling CLIPModel.
- 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. - projection_dim (
int, optional, defaults to 512) -- Dimensionality of text and vision projection layers. - 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 77) -- The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). - hidden_act (
strorfunction, 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-05) -- 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.0) -- A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing). - pad_token_id (
int, optional, defaults to 1) -- Padding token id. - bos_token_id (
int, optional, defaults to 49406) -- Beginning of stream token id. - eos_token_id (
int, optional, defaults to 49407) -- End of stream token id.0
This is the configuration class to store the configuration of a CLIPTextModel. It is used to instantiate a CLIP 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 text encoder of the CLIP openai/clip-vit-base-patch32 architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import CLIPTextConfig, CLIPTextModel
>>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
>>> configuration = CLIPTextConfig()
>>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
>>> model = CLIPTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
CLIPVisionConfig[[transformers.CLIPVisionConfig]]
class transformers.CLIPVisionConfigtransformers.CLIPVisionConfigint, 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. - projection_dim (
int, optional, defaults to 512) -- Dimensionality of text and vision projection layers. - 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) -- The number of input channels. - image_size (
int, optional, defaults to 224) -- The size (resolution) of each image. - patch_size (
int, optional, defaults to 32) -- The size (resolution) of each patch. - hidden_act (
strorfunction, 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-05) -- 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.0) -- A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).0
This is the configuration class to store the configuration of a CLIPVisionModel. It is used to instantiate a CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP openai/clip-vit-base-patch32 architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import CLIPVisionConfig, CLIPVisionModel
>>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
>>> configuration = CLIPVisionConfig()
>>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
>>> model = CLIPVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
CLIPTokenizer[[transformers.CLIPTokenizer]]
class transformers.CLIPTokenizertransformers.CLIPTokenizerstr) --
Path to the vocabulary file.
- merges_file (
str) -- Path to the merges file. - errors (
str, optional, defaults to"replace") -- Paradigm to follow when decoding bytes to UTF-8. See bytes.decode for more information. - unk_token (
str, optional, defaults to"<|endoftext|>") -- The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. - bos_token (
str, optional, defaults to"<|startoftext|>") -- The beginning of sequence token. - eos_token (
str, optional, defaults to"<|endoftext|>") -- The end of sequence token. - pad_token (
str, optional, defaults to"<|endoftext|>") -- The token used for padding, for example when batching sequences of different lengths.0
Construct a CLIP tokenizer. Based on byte-level Byte-Pair-Encoding.
This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
build_inputs_with_special_tokenstransformers.CLIPTokenizer.build_inputs_with_special_tokenslist[int]) --
List of IDs to which the special tokens will be added.
- token_ids_1 (
list[int], optional) -- Optional second list of IDs for sequence pairs.0list[int]List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A CLIP sequence has the following format:
- single sequence:
<|startoftext|> X <|endoftext|>
Pairs of sequences are not the expected use case, but they will be handled without a separator.
get_special_tokens_masktransformers.CLIPTokenizer.get_special_tokens_masklist[int]) --
List of IDs.
- token_ids_1 (
list[int], optional) -- Optional second list of IDs for sequence pairs. - already_has_special_tokens (
bool, optional, defaults toFalse) -- Whether or not the token list is already formatted with special tokens for the model.0list[int]A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer prepare_for_model method.
create_token_type_ids_from_sequencestransformers.CLIPTokenizer.create_token_type_ids_from_sequenceslist[int]) --
List of IDs.
- token_ids_1 (
list[int], optional) -- Optional second list of IDs for sequence pairs.0list[int]List of zeros.
Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of zeros is returned.
save_vocabularytransformers.CLIPTokenizer.save_vocabulary
CLIPTokenizerFast[[transformers.CLIPTokenizerFast]]
class transformers.CLIPTokenizerFasttransformers.CLIPTokenizerFaststr, optional) --
Path to the vocabulary file.
- merges_file (
str, optional) -- Path to the merges file. - tokenizer_file (
str, optional) -- The path to a tokenizer file to use instead of the vocab file. - unk_token (
str, optional, defaults to"<|endoftext|>") -- The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. - bos_token (
str, optional, defaults to"<|startoftext|>") -- The beginning of sequence token. - eos_token (
str, optional, defaults to"<|endoftext|>") -- The end of sequence token. - pad_token (
str, optional, defaults to"<|endoftext|>") -- The token used for padding, for example when batching sequences of different lengths.0
Construct a "fast" CLIP tokenizer (backed by HuggingFace's tokenizers library). Based on byte-level Byte-Pair-Encoding.
This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
build_inputs_with_special_tokenstransformers.CLIPTokenizerFast.build_inputs_with_special_tokenslist[int]) --
List of IDs to which the special tokens will be added.
- token_ids_1 (
list[int], optional) -- Optional second list of IDs for sequence pairs.0list[int]List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A CLIP sequence has the following format:
- single sequence:
<|startoftext|> X <|endoftext|>
Pairs of sequences are not the expected use case, but they will be handled without a separator.
create_token_type_ids_from_sequencestransformers.CLIPTokenizerFast.create_token_type_ids_from_sequenceslist[int]) --
List of IDs.
- token_ids_1 (
list[int], optional) -- Optional second list of IDs for sequence pairs.0list[int]List of zeros.
Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of zeros is returned.
CLIPImageProcessor[[transformers.CLIPImageProcessor]]
class transformers.CLIPImageProcessortransformers.CLIPImageProcessorbool, optional, defaults to True) --
Whether to resize the image's (height, width) dimensions to the specified size. Can be overridden by
do_resize in the preprocess method.
- size (
dict[str, int]optional, defaults to{"shortest_edge" -- 224}): Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Can be overridden bysizein thepreprocessmethod. - resample (
PILImageResampling, optional, defaults toResampling.BICUBIC) -- Resampling filter to use if resizing the image. Can be overridden byresamplein thepreprocessmethod. - do_center_crop (
bool, optional, defaults toTrue) -- Whether to center crop the image to the specifiedcrop_size. Can be overridden bydo_center_cropin thepreprocessmethod. - crop_size (
dict[str, int]optional, defaults to 224) -- Size of the output image after applyingcenter_crop. Can be overridden bycrop_sizein thepreprocessmethod. - do_rescale (
bool, optional, defaults toTrue) -- Whether to rescale the image by the specified scalerescale_factor. Can be overridden bydo_rescalein thepreprocessmethod. - rescale_factor (
intorfloat, optional, defaults to1/255) -- Scale factor to use if rescaling the image. Can be overridden byrescale_factorin thepreprocessmethod. - do_normalize (
bool, optional, defaults toTrue) -- Whether to normalize the image. Can be overridden bydo_normalizein thepreprocessmethod. - image_mean (
floatorlist[float], optional, defaults to[0.48145466, 0.4578275, 0.40821073]) -- Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by theimage_meanparameter in thepreprocessmethod. - image_std (
floatorlist[float], optional, defaults to[0.26862954, 0.26130258, 0.27577711]) -- Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by theimage_stdparameter in thepreprocessmethod. Can be overridden by theimage_stdparameter in thepreprocessmethod. - do_convert_rgb (
bool, optional, defaults toTrue) -- Whether to convert the image to RGB.0
Constructs a CLIP image processor.
preprocesstransformers.CLIPImageProcessor.preprocessImageInput) --
Image to preprocess. 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 toself.do_resize) -- Whether to resize the image. - size (
dict[str, int], optional, defaults toself.size) -- Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. - resample (
int, optional, defaults toself.resample) -- Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_center_crop (
bool, optional, defaults toself.do_center_crop) -- Whether to center crop the image. - crop_size (
dict[str, int], optional, defaults toself.crop_size) -- Size of the center crop. Only has an effect ifdo_center_cropis set toTrue. - do_rescale (
bool, optional, defaults toself.do_rescale) -- Whether to rescale the image. - rescale_factor (
float, optional, defaults toself.rescale_factor) -- Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, optional, defaults toself.do_normalize) -- Whether to normalize the image. - image_mean (
floatorlist[float], optional, defaults toself.image_mean) -- Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
floatorlist[float], optional, defaults toself.image_std) -- Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_convert_rgb (
bool, optional, defaults toself.do_convert_rgb) -- Whether to convert the image to RGB. - return_tensors (
strorTensorType, optional) -- The type of tensors to return. Can be one of:- Unset: Return a list of
np.ndarray. TensorType.PYTORCHor'pt': Return a batch of typetorch.Tensor.TensorType.NUMPYor'np': Return a batch of typenp.ndarray.
- Unset: Return a list of
- data_format (
ChannelDimensionorstr, optional, defaults toChannelDimension.FIRST) -- The channel dimension format for the output image. Can be one of:"channels_first"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format.- Unset: Use the channel dimension format of the input image.
- input_data_format (
ChannelDimensionorstr, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.0
Preprocess an image or batch of images.
CLIPImageProcessorFast[[transformers.CLIPImageProcessorFast]]
class transformers.CLIPImageProcessorFasttransformers.CLIPImageProcessorFast
Constructs a fast Clip image processor.
preprocesstransformers.CLIPImageProcessorFast.preprocessUnion[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) --
Image to preprocess. 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_convert_rgb (
bool, optional) -- Whether to convert the image to RGB. - do_resize (
bool, optional) -- Whether to resize the image. - size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- Describes the maximum input dimensions to the model. - crop_size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[PILImageResampling, int, NoneType], None]) -- Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, optional) -- Whether to rescale the image. - rescale_factor (
float, optional) -- Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, optional) -- Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...], NoneType]) -- Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...], NoneType]) -- Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, optional) -- Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, optional) -- Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]) -- OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]) -- 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[str, None], optional) -- The device to process the images on. If unset, the device is inferred from the input images. - return_tensors (
Annotated[Union[str, ~utils.generic.TensorType, NoneType], None]) -- Returns stacked tensors if set to `pt, otherwise returns a list of tensors. - disable_grouping (
bool, optional) -- Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/381570<class 'transformers.image_processing_base.BatchFeature'>- data (dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
CLIPProcessor[[transformers.CLIPProcessor]]
class transformers.CLIPProcessortransformers.CLIPProcessor
- tokenizer (AutoTokenizer, optional) -- The tokenizer is a required input.0
Constructs a CLIP processor which wraps a CLIP image processor and a CLIP tokenizer into a single processor.
CLIPProcessor offers all the functionalities of CLIPImageProcessor and CLIPTokenizerFast. See the call() and decode() for more information.
CLIPModel[[transformers.CLIPModel]]
class transformers.CLIPModeltransformers.CLIPModel
The bare Clip Model outputting raw hidden-states without any specific head on top.
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPModel.forwardtorch.LongTensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) -- The tensors corresponding to the input images. Pixel values can be obtained using CLIPImageProcessor. See CLIPImageProcessor.call() for details (CLIPProcessor uses CLIPImageProcessor for processing images).attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].return_loss (
bool, optional) -- Whether or not to return the contrastive loss.output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.interpolate_pos_encoding (
bool, defaults toFalse) -- Whether to interpolate the pre-trained position encodings.0transformers.models.clip.modeling_clip.CLIPOutputortuple(torch.FloatTensor)Atransformers.models.clip.modeling_clip.CLIPOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenreturn_lossisTrue) -- Contrastive loss for image-text similarity.logits_per_image (
torch.FloatTensorof shape(image_batch_size, text_batch_size)) -- The scaled dot product scores betweenimage_embedsandtext_embeds. This represents the image-text similarity scores.logits_per_text (
torch.FloatTensorof shape(text_batch_size, image_batch_size)) -- The scaled dot product scores betweentext_embedsandimage_embeds. This represents the text-image similarity scores.text_embeds (
torch.FloatTensorof shape(batch_size, output_dim) -- The text embeddings obtained by applying the projection layer to the pooled output of CLIPTextModel.image_embeds (
torch.FloatTensorof shape(batch_size, output_dim) -- The image embeddings obtained by applying the projection layer to the pooled output of CLIPVisionModel.text_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, defaults toNone) -- The output of the CLIPTextModel.vision_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, defaults toNone) -- The output of the CLIPVisionModel. The CLIPModel 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:
>>> import torch
>>> from transformers import AutoProcessor, CLIPModel
>>> from transformers.image_utils import load_image
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)
>>> inputs = processor(
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
... )
>>> with torch.inference_mode():
... 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_featurestransformers.CLIPModel.get_text_featurestorch.Tensor of shape (batch_size, sequence_length)) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].What are position IDs?0text_features (
torch.FloatTensorof shape(batch_size, output_dim)The text embeddings obtained by
applying the projection layer to the pooled output of CLIPTextModel.
Examples:
>>> import torch
>>> from transformers import AutoTokenizer, CLIPModel
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
... text_features = model.get_text_features(**inputs)
get_image_featurestransformers.CLIPModel.get_image_featurestorch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) --
The tensors corresponding to the input images. Pixel values can be obtained using
CLIPImageProcessor. See CLIPImageProcessor.call() for details (CLIPProcessor uses
CLIPImageProcessor for processing images).
- interpolate_pos_encoding (
bool, defaults toFalse) -- Whether to interpolate the pre-trained position encodings.0image_features (torch.FloatTensorof shape(batch_size, output_dim)The image embeddings obtained by applying the projection layer to the pooled output of CLIPVisionModel.
Examples:
>>> import torch
>>> from transformers import AutoProcessor, CLIPModel
>>> from transformers.image_utils import load_image
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
... image_features = model.get_image_features(**inputs)
CLIPTextModel[[transformers.CLIPTextModel]]
class transformers.CLIPTextModeltransformers.CLIPTextModel
The text model from CLIP without any head or projection on top.
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPTextModel.forwardtorch.Tensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.0transformers.modeling_outputs.BaseModelOutputWithPooling ortuple(torch.FloatTensor)A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof 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 whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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 CLIPTextModel 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:
>>> from transformers import AutoTokenizer, CLIPTextModel
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
CLIPTextModelWithProjection[[transformers.CLIPTextModelWithProjection]]
class transformers.CLIPTextModelWithProjectiontransformers.CLIPTextModelWithProjection
The Clip Model with a projection layer on top (a linear layer on top of the pooled output).
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPTextModelWithProjection.forwardtorch.Tensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.0transformers.models.clip.modeling_clip.CLIPTextModelOutputortuple(torch.FloatTensor)Atransformers.models.clip.modeling_clip.CLIPTextModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.text_embeds (
torch.FloatTensorof shape(batch_size, output_dim)optional returned when model is initialized withwith_projection=True) -- The text embeddings obtained by applying the projection layer to the pooler_output.last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional, defaults toNone) -- Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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 CLIPTextModelWithProjection 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:
>>> import torch
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> text_embeds = outputs.text_embeds
CLIPVisionModelWithProjection[[transformers.CLIPVisionModelWithProjection]]
class transformers.CLIPVisionModelWithProjectiontransformers.CLIPVisionModelWithProjection
The Clip Model with a projection layer on top (a linear layer on top of the pooled output).
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPVisionModelWithProjection.forwardtorch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) --
The tensors corresponding to the input images. Pixel values can be obtained using
CLIPImageProcessor. See CLIPImageProcessor.call() for details (CLIPProcessor uses
CLIPImageProcessor for processing images).
output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.interpolate_pos_encoding (
bool, defaults toFalse) -- Whether to interpolate the pre-trained position encodings.0transformers.models.clip.modeling_clip.CLIPVisionModelOutputortuple(torch.FloatTensor)Atransformers.models.clip.modeling_clip.CLIPVisionModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.image_embeds (
torch.FloatTensorof shape(batch_size, output_dim)optional returned when model is initialized withwith_projection=True) -- The image embeddings obtained by applying the projection layer to the pooler_output.last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional, defaults toNone) -- Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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 CLIPVisionModelWithProjection 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:
>>> import torch
>>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
>>> from transformers.image_utils import load_image
>>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> image_embeds = outputs.image_embeds
CLIPVisionModel[[transformers.CLIPVisionModel]]
class transformers.CLIPVisionModeltransformers.CLIPVisionModel
The vision model from CLIP without any head or projection on top.
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPVisionModel.forwardtorch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) --
The tensors corresponding to the input images. Pixel values can be obtained using
CLIPImageProcessor. See CLIPImageProcessor.call() for details (CLIPProcessor uses
CLIPImageProcessor for processing images).
output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.interpolate_pos_encoding (
bool, defaults toFalse) -- Whether to interpolate the pre-trained position encodings.0transformers.modeling_outputs.BaseModelOutputWithPooling ortuple(torch.FloatTensor)A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof 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 whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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 CLIPVisionModel 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.
Example:
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, CLIPVisionModel
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-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
CLIPForImageClassification[[transformers.CLIPForImageClassification]]
class transformers.CLIPForImageClassificationtransformers.CLIPForImageClassification
CLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of the patch tokens) e.g. for ImageNet.
This model inherits from 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.CLIPForImageClassification.forwardtorch.Tensor of shape (batch_size, num_channels, image_size, image_size), optional) --
The tensors corresponding to the input images. Pixel values can be obtained using
CLIPImageProcessor. See CLIPImageProcessor.call() for details (CLIPProcessor uses
CLIPImageProcessor for processing images).
labels (
torch.LongTensorof shape(batch_size,), optional) -- Labels for computing the image classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy).output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.0transformers.modeling_outputs.ImageClassifierOutput ortuple(torch.FloatTensor)A transformers.modeling_outputs.ImageClassifierOutput or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (CLIPConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) -- Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each stage) of shape(batch_size, sequence_length, hidden_size). Hidden-states (also called feature maps) of the model at the output of each stage.attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, patch_size, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The CLIPForImageClassification 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.
Example:
>>> from transformers import AutoImageProcessor, CLIPForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32")
>>> model = CLIPForImageClassification.from_pretrained("openai/clip-vit-base-patch32")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
Xet Storage Details
- Size:
- 88.7 kB
- Xet hash:
- e26dc731a6a661068470bd0554eb50aa3039a8c59861911e039c3a5dc723661e
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.