Hub documentation

Sử dụng OpenCLIP trên Hugging Face

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Sử dụng OpenCLIP trên Hugging Face

OpenCLIP là một bản triển khai mã nguồn mở của CLIP từ OpenAI.

Khám phá OpenCLIP trên Hub

Bạn có thể tìm các mô hình OpenCLIP bằng cách lọc ở phía bên trái của trang models.

Các mô hình OpenCLIP được lưu trữ trên Hub có kèm theo model card chứa thông tin hữu ích về các mô hình. Nhờ tích hợp Hugging Face Hub của OpenCLIP, bạn có thể tải các mô hình OpenCLIP chỉ với vài dòng mã. Bạn cũng có thể triển khai các mô hình này bằng Inference Endpoints.

Cài đặt

Để bắt đầu, bạn có thể làm theo hướng dẫn cài đặt OpenCLIP. Bạn cũng có thể sử dụng lệnh cài đặt một dòng sau đây thông qua pip:

$ pip install open_clip_torch

Sử dụng các mô hình có sẵn

Tất cả các mô hình OpenCLIP đều có thể dễ dàng được tải từ Hub:

import open_clip

model, preprocess = open_clip.create_model_from_pretrained('hf-hub:laion/CLIP-ViT-g-14-laion2B-s12B-b42K')
tokenizer = open_clip.get_tokenizer('hf-hub:laion/CLIP-ViT-g-14-laion2B-s12B-b42K')

Sau khi tải xong, bạn có thể mã hóa hình ảnh và văn bản để thực hiện phân loại hình ảnh zero-shot:

import torch
from PIL import Image
import requests

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
image = preprocess(image).unsqueeze(0)
text = tokenizer(["a diagram", "a dog", "a cat"])

with torch.no_grad(), torch.cuda.amp.autocast():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features /= text_features.norm(dim=-1, keepdim=True)

    text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)

print("Label probs:", text_probs) 

Nó xuất ra xác suất của mỗi lớp có thể:

Label probs: tensor([[0.0020, 0.0034, 0.9946]])

Nếu bạn muốn tải một mô hình OpenCLIP cụ thể, bạn có thể nhấp vào Use in OpenCLIP trong thẻ mô hình và sẽ nhận được một đoạn mã hoạt động!

Tài nguyên bổ sung

Update on GitHub