Registry / ai-ml / open-clip-torch

open-clip-torch

JSON →
library3.3.0pypypi✓ verified 29d ago

OpenCLIP is an open-source implementation of OpenAI's Contrastive Language-Image Pre-training (CLIP) and related models. It enables training CLIP models at scale, leveraging state-of-the-art pretrained weights, and performing zero-shot image classification and retrieval. The current version is 3.3.0, with active development and regular releases.

pip install open_clip_torch
INSTALL
IMPORT
SIG · OPEN-CLIP-TORCH
O
open-clip-torch
ai-mlpythonv3.3.0
Install
59.0s avg
Import
19072ms
Disk
7680MB
Pass rate
3/ 10
Env Coverage3 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v3.3.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
1/4 runs
3/4 runs
py 3.11
1/4 runs
✓ 63.68s
py 3.12
1/4 runs
✓ 59.75s
py 3.13
1/4 runs
✓ 53.5s
py 3.9
1/4 runs
1/4 runs
7680MB installed
● package 7680MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

open_clip
✓ import open_clip
create_model_and_transforms
✓ model, _, preprocess = open_clip.create_model_and_transforms(...)
get_tokenizer
✓ tokenizer = open_clip.get_tokenizer(...)
✗ from open_clip import tokenizer
While 'from open_clip import tokenizer' works, the recommended pattern is `open_clip.get_tokenizer()` to retrieve the correct tokenizer instance for a given model.

This quickstart demonstrates how to load a pre-trained OpenCLIP model, preprocess a dummy image and text, then compute the zero-shot similarity probabilities between the image and the given text labels. It includes loading the model, tokenizer, and performing inference with feature normalization.

import torch from PIL import Image import open_clip import io import base64 # Create a dummy image (in a real scenario, load from file or URL) dummy_image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" image = Image.open(io.BytesIO(base64.b64decode(dummy_image_data))).convert('RGB') # 1. Load model and preprocessing transforms model, _, preprocess = open_clip.create_model_and_transforms( 'ViT-B-32', pretrained='laion2b_s34b_b79k' ) model.eval() # Set model to evaluation mode # 2. Get tokenizer tokenizer = open_clip.get_tokenizer('ViT-B-32') # 3. Prepare inputs image_input = preprocess(image).unsqueeze(0) # Add batch dimension text_input = tokenizer(["a diagram", "a dog", "a cat"]) # 4. Run inference with torch.no_grad(): # Disable gradient computation for inference image_features = model.encode_image(image_input) text_features = model.encode_text(text_input) # Normalize features image_features /= image_features.norm(dim=-1, keepdim=True) text_features /= text_features.norm(dim=-1, keepdim=True) # Compute similarity scores text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1) print("Label probabilities:", text_probs) # Optional: Interpret results labels = ["a diagram", "a dog", "a cat"] top_prob, top_idx = text_probs[0].max(dim=0) print(f"Predicted: {labels[top_idx]} ({top_prob.item():.1%} confidence)")
Debug
Known issues
gotchaWhen using `timm`-based image encoders (e.g., ConvNeXt, SigLIP, EVA), ensure you have the latest `timm` library installed. Older versions may result in 'Unknown model' errors.
fix
pip install -U timm
affects: <= 3.x.x
breakingThe default activation function for models changed from `QuickGELU` to `torch.nn.GELU` in newer PyTorch versions. For OpenCLIP pretrained weights, using model definitions with a `-quickgelu` postfix (e.g., 'ViT-B-32-quickgelu') is necessary to match the original training and avoid an accuracy drop, especially during fine-tuning.
fix
Specify model definitions with a `-quickgelu` postfix when loading OpenCLIP pretrained weights (e.g., `open_clip.create_model_and_transforms('ViT-B-32-quickgelu', ...)`).
affects: All versions, due to underlying PyTorch/model defaults
gotchaMismatch between installed `torch` and `open-clip-torch` versions can lead to `ModuleNotFoundError` or other runtime issues. Ensure compatible versions are installed, often by following PyTorch's installation instructions for your CUDA version before installing OpenCLIP.
fix
Verify `torch` and `open-clip-torch` compatibility. Downgrade `open_clip_torch` or upgrade `torch` as needed. Consult OpenCLIP's GitHub issues for known compatibility pairs.
affects: All versions
gotchaFor optimal performance and consistency with original CLIP, OpenCLIP is designed to be used within a mixed-precision context (e.g., `torch.autocast('cuda')`) as OpenAI's original models utilized mixed-precision. Without it, there might be slight numerical differences in embeddings or reduced performance on GPU.
fix
Wrap inference calls with `with torch.no_grad(), torch.autocast('cuda'):` for GPU inference.
affects: All versions
gotchaIf you are using models that rely on transformer tokenizers (e.g., certain text encoders), the `transformers` library must be installed separately, as it is an optional dependency for `open-clip-torch`.
fix
pip install transformers
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'open_clip'
This error occurs when the 'open_clip_torch' library is not installed, or is installed incorrectly, or there is an import conflict with another 'clip' package or a local file named 'open_clip.py'.
fix
Ensure the library is correctly installed using `pip install open_clip_torch`. If the issue persists, check for conflicting installations (e.g., `pip uninstall clip open_clip_torch` and then reinstall `open_clip_torch`) or local files named 'open_clip.py' or 'clip.py' that might shadow the installed package.
AttributeError: module 'clip' has no attribute 'load'
This error typically arises when code written for OpenAI's original `clip` library (which uses `clip.load()`) is run, but `open-clip-torch` is installed and imported as `clip`, or vice versa, causing a mismatch in API calls. `open-clip-torch` uses `open_clip.create_model_and_transforms()` for loading models.
fix
If using `open-clip-torch`, change the import to `import open_clip` and update the model loading call to `model, preprocess, _ = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion400m_e32')`. If you intend to use OpenAI's original CLIP, ensure you install it correctly (e.g., `pip install git+https://github.com/openai/CLIP.git`) and uninstall `open_clip_torch` to avoid conflicts.
RuntimeError: Error(s) in loading state_dict for CLIP: Missing key(s) in state_dict:
This error usually indicates that the pre-trained model checkpoint being loaded does not match the architecture definition used in `open_clip.create_model_and_transforms()`. This can happen with incompatible model names, pretrained tags, or when migrating between different model versions or sources.
fix
Verify that the `model_name` and `pretrained` arguments passed to `open_clip.create_model_and_transforms()` exactly correspond to an available and compatible model, which can be listed using `open_clip.list_pretrained()`. Also, ensure that necessary dependencies like `timm` and `transformers` are updated to their latest versions: `pip install --upgrade timm transformers`.
RuntimeError: CUDA error: an illegal memory access was encountered
This is a common PyTorch error related to GPU operations, often stemming from an incompatibility between your PyTorch version, NVIDIA drivers, and CUDA toolkit. It can also be caused by attempting to allocate more GPU memory than available.
fix
Check for compatibility between your installed PyTorch, CUDA, and NVIDIA driver versions. Downgrade or upgrade PyTorch if necessary to match a stable configuration. Reduce batch sizes or model complexity to decrease GPU memory usage. For debugging, set the environment variable `CUDA_LAUNCH_BLOCKING=1` to get more precise stack traces.
Upgrade
Version history
3.3.0latest on PyPI · released Feb 27, 2026
Audit
Dependencies
torchrequiredCore deep learning framework dependency.
torchvisionrequiredRequired for image preprocessing transforms.
timmoptionalUsed for various image encoders (e.g., ConvNeXt, SigLIP, EVA).
transformersoptionalRequired for certain transformer-based tokenizers.
PillowrequiredCommonly used for image loading and manipulation (e.g., PIL.Image).
huggingface-huboptionalUsed for loading models from Hugging Face Hub.
Agent activity
20 hits · last 30 days
node
18
OpenAI (training)
1
Resources
open-clip-torch — pip install open-clip-torch · libregistry