ClipEmbedder¶
Embeds images with a pretrained CLIP image tower. Embeddings are L2-normalized by default, which makes the cosine similarity a plain dot product.
from pyvisim.neural_networks import ClipEmbedder
embedder = ClipEmbedder("ViT-B-32", pretrained="laion2b_s34b_b79k")
embeddings = embedder.embed(images) # (N, 512)
score = embedder.similarity_score(image1, image2) # (1, 1) cosine similarity
Supported models¶
Variant names and pretrained tags follow open_clip. OpenAI-style spellings such as
"ViT-B/32" are accepted as aliases of "ViT-B-32".
Variant |
Embedding dim |
Input size |
Pretrained tags |
|---|---|---|---|
|
1024 |
224x224 |
|
|
1024 |
224x224 |
|
|
512 |
224x224 |
|
|
512 |
224x224 |
|
|
640 |
288x288 |
|
|
640 |
288x288 |
|
|
768 |
384x384 |
|
|
768 |
384x384 |
|
|
1024 |
448x448 |
|
|
1024 |
448x448 |
|
|
512 |
224x224 |
|
|
512 |
224x224 |
|
|
512 |
256x256 |
|
|
512 |
224x224 |
|
|
512 |
224x224 |
|
|
640 |
240x240 |
|
|
768 |
224x224 |
|
|
768 |
224x224 |
|
|
768 |
336x336 |
|
|
768 |
336x336 |
|
|
1024 |
224x224 |
|
|
1024 |
224x224 |
|
|
1024 |
224x224 |
|
|
1024 |
224x224 |
|
|
1024 |
378x378 |
|
|
1024 |
224x224 |
|
|
1280 |
224x224 |
|
|
1280 |
224x224 |
|
|
1280 |
224x224 |
|
|
1280 |
378x378 |
|
The -quickgelu names are open_clip spellings kept for compatibility, not
separate architectures: whether the tower uses the QuickGELU activation of the
original OpenAI models or the exact GELU of newer checkpoints is read off the
checkpoint itself. A variant and its -quickgelu twin therefore build the
same model for every tag they share. The plain name only exists separately
because some of them offer extra tags (for example ViT-B-32 adds the LAION
and DataComp checkpoints).
To print all supported variants and pretrained tags, use these helper functions:
from pyvisim.neural_networks.clip import available_pretrained, available_variants
print(available_variants()) # every supported variant name
print(available_pretrained("ViT-B-32")) # every pretrained tag of one variant
API reference¶
- class pyvisim.neural_networks.ClipEmbedder(variant='ViT-B-32', pretrained='openai', *, device=None, normalize=True, similarity_func='cosine', cache_dir=None, batch_size=16)[source]¶
Bases:
SerializableImageEmbedderEmbeds images with a pretrained CLIP model.
The safetensors checkpoint of the requested
variantandpretrainedtag is downloaded from the Hugging Face Hub on first use and cached (seepyvisim.neural_networks.clip.fetch_checkpoint()); only the image tower is loaded, and it always runs infloat32.embed()returns one embedding per image, L2-normalized whennormalizeis on, so they can be compared directly with a dot product or the cosine similarity metric.Variant names and pretrained tags follow open_clip, e.g.
ClipEmbedder("ViT-B-32", pretrained="laion2b_s34b_b79k"). OpenAI-style variant spellings ("ViT-B/32") are accepted as aliases. Seepyvisim.neural_networks.clip.available_variants()andpyvisim.neural_networks.clip.available_pretrained()for the supported combinations.- Parameters:
variant (str) – CLIP variant name.
pretrained (str) – Pretrained tag naming the weights, e.g.
"openai"for the original OpenAI checkpoint of the variant.device (str | None) – Device to run the model on (
"cpu"or"cuda"). IfNone,"cuda"is used when a CUDA device is available, else"cpu". The model runs infloat32on either device.normalize (bool) – Whether to L2-normalize the returned embeddings.
similarity_func (str) – Name of the built-in similarity metric used to score two embeddings. One of
"cosine","euclidean","l1"or"manhattan".cache_dir (str | Path | None) – Directory of the Hugging Face Hub cache the checkpoint is stored in. If
None, the standard Hub cache (~/.cache/huggingface/hub) is used, so weights already downloaded via open_clip’s Hub downloads are reused.batch_size (int) – Maximum number of images processed in a single batch. Set to
-1to process all images as a single batch.
- Raises:
ValueError – If
variant,pretrainedorsimilarity_funcis not supported, or the checkpoint does not match the architecture.ImportError – If the
nnextra is not installed.huggingface_hub.errors.HfHubHTTPError – If the checkpoint download fails.
References:¶
- [1] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel
Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, and Ilya Sutskever, “Learning Transferable Visual Models From Natural Language Supervision,” in Proc. ICML, PMLR 139, pp. 8748-8763, 2021.
- embed(images, *, dims='HWC', value_range=(0.0, 255.0))¶
Embeds one or more images into a batch of vector representations.
Each image is normalized to a canonical
uint8(H, W, C)array before feature extraction, so NumPy arrays, torch tensors and other array-like inputs are all accepted. When a batch axis is present (viadims), every image in the batch is embedded. The resulting vectors are L2-normalized row by row whennormalizeis True.- Parameters:
images (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | Iterable[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]) – A single
MatLikeimage, a batched array, or an iterable of images. Consider using an iterator for large datasets.dims (str) – Axis-label string, one character per array axis in order:
"H"= height (rows),"W"= width (columns),"C"= channels (e.g. RGB),"B"= batch size. For example,"HWC"is height × width × channels (NumPy/OpenCV single-image layout);"CHW"is channels × height × width (PyTorch single-image layout);"BCHW"is batch × channels × height × width (PyTorch batched layout). Seepyvisim.typing.value_range (tuple[float, float]) – The
(low, high)range the input values live in; converted into the canonical[0, 255]range.
- Returns:
vector representations of the given images, L2-normalized row by row if
normalizeis True.- Raises:
ValueError – If
imagesholds no image.- Return type:
- classmethod from_dict(state, **kwargs)[source]¶
Rebuilds the embedder a state dictionary describes.
Called on
SerializableImageEmbedderitself, it hands the state to thefrom_dictof the class named under"__class__", so a state can be rebuilt without knowing which embedder wrote it.- Parameters:
- Returns:
The reconstructed embedder.
- Raises:
ValueError – If
statenames no concrete embedder class.NotImplementedError – If called on a subclass that does not implement its own
from_dict.
- Return type:
- classmethod load_from_disk(path, **kwargs)¶
Loads an object previously saved with
save_to_disk().Not every part of an object survives serialization: an arbitrary callable such as a torchvision transform has no portable description, so it is left out of the file. Pass such an object back here as a keyword argument.
- Parameters:
kwargs (Any) – Objects the file cannot hold, forwarded to
from_dict().
- Returns:
A ready-to-use instance.
- Raises:
FileNotFoundError – If
pathdoes not exist.ValueError – If the file is not a valid file of this kind or was saved by a different class.
TypeError – If the class does not take one of
kwargs.
- Return type:
_SerializableT
- save_to_disk(path)¶
Saves the serialized state of this object to a file.
- set_batch_size(batch_size)¶
Sets the number of items processed per batch.
- Parameters:
batch_size (int) – Maximum number of images processed in a single batch. Set to
-1to process all images as a single batch.- Raises:
ValueError – If
batch_sizeis neither-1nor a positive integer.- Return type:
None
- similarity_score(images1, images2, *, dims='HWC', value_range=(0.0, 255.0))¶
Compute the similarity scores matrix between two (batches of) images.
- Parameters:
images1 (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | Iterable[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]) – First (batch of) image(s) as
MatLike(NumPy array, torch tensor or array-like).images2 (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | Iterable[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]) – Second (batch of) image(s) as
MatLike.dims (str) – Axis-label string, one character per array axis in order:
"H"= height (rows),"W"= width (columns),"C"= channels (e.g. RGB),"B"= batch size. For example,"HWC"is height × width × channels (NumPy/OpenCV single-image layout);"CHW"is channels × height × width (PyTorch single-image layout);"BCHW"is batch × channels × height × width (PyTorch batched layout). Seepyvisim.typing.value_range (tuple[float, float]) – The
(low, high)range the input values live in; converted into the canonical[0, 255]range.
- Returns:
The similarity score matrix of shape
(len(images1), len(images2)).- Return type:
- to_dict()¶
Serializes this object into a JSON-safe state dictionary.
The mapping holds the output of
_state()plus the format version under"format_version"and the class name under"__class__". Arrays may be embedded as__ndarray__nodes, which the serialization layer stores as binary tensors.- Returns:
A JSON-safe description suitable for
from_dict().- Return type: