Hugging Face에서 OpenCLIP 사용하기

Hugging Face에서 OpenCLIP 사용하기

OpenCLIP은 OpenAI의 CLIP을 오픈소스로 구현한 것이에요.

출처: 문서

본문

Hub에서 OpenCLIP 탐색하기

모델 페이지 왼쪽의 필터로 OpenCLIP 모델을 찾을 수 있어요.

Hub에 호스팅된 OpenCLIP 모델에는 모델에 대한 유용한 정보를 담은 모델 카드가 있어요. OpenCLIP Hugging Face Hub 통합 덕분에, 몇 줄의 코드로 OpenCLIP 모델을 로드할 수 있어요. Inference Endpoints로 이런 모델을 배포할 수도 있어요.

설치

OpenCLIP 설치 가이드를 따라 시작할 수 있어요. 또는 다음의 한 줄 pip 설치를 사용할 수도 있어요.

$ pip install open_clip_torch

기존 모델 사용하기

모든 OpenCLIP 모델은 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')

로드한 뒤에는 이미지와 텍스트를 인코딩해 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) 

각 가능한 클래스의 확률을 출력해요.

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

특정 OpenCLIP 모델을 로드하고 싶다면 모델 카드에서 Use in OpenCLIP을 클릭하면 바로 동작하는 스니펫을 얻을 수 있어요.

추가 리소스

더 알아보기 (Learn more)

hf-hub: 접두사를 붙이면 Hub의 OpenCLIP 모델을 몇 줄로 로드해 바로 zero-shot 분류에 쓸 수 있어요. 모델 카드의 Use in OpenCLIP 버튼은 실제 동작하는 코드 스니펫을 제공해 주니 꼭 활용해 보세요.