Skip to content

Add PyTorch Hub configuration file #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 14, 2022
Merged

Add PyTorch Hub configuration file #259

merged 1 commit into from
Jul 14, 2022

Conversation

johnsutor
Copy link
Contributor

@johnsutor johnsutor commented Jun 28, 2022

This PR aims to add support for PyTorch's hub loading feature. This would make model loading as simple as specifying this git repo to download the CLIP model along with its pre-trained weights. When working with torch.hub.load, the example would change from this

import torch
import clip
from PIL import Image

device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)

image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)
text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)

with torch.no_grad():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

print("Label probs:", probs)  # prints: [[0.9927937  0.00421068 0.00299572]]

to this

import torch
from PIL import Image

device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = torch.hub.load("openai/CLIP", "ViT_B_32", device=device)
tokenize = torch.hub.load("openai/CLIP", "tokenize")

image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)
text = tokenize(["a diagram", "a dog", "a cat"]).to(device)

with torch.no_grad():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

print("Label probs:", probs)  # prints: [[0.9927937  0.00421068 0.00299572]]

@jongwook jongwook merged commit 4d120f3 into openai:main Jul 14, 2022
@jongwook
Copy link
Collaborator

It works! Thanks for the contribution :)

rom1504 pushed a commit to rom1504/CLIP that referenced this pull request Jan 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants