# Hugging FaceでのOpenCLIPの使用方法

[OpenCLIP](https://github.com/mlfoundations/open_clip)は、OpenAIのCLIPのオープンソース実装です。

## Hub での OpenCLIP の探索

[モデルページ](https://huggingface.co/models?library=open_clip&sort=trending)の左側でフィルタリングを行うことで、OpenCLIPモデルを見つけることができます。

Hub にホストされている OpenCLIP モデルには、モデルに関する有用な情報が記載されたモデルカードがあります。OpenCLIP の Hugging Face Hub 統合により、数行のコードで OpenCLIP モデルを読み込むことができます。また、[Inference Endpoints](https://huggingface.co/inference-endpoints) を使用してこれらのモデルをデプロイすることもできます。

## インストール

開始するには、[OpenCLIPのインストールガイド](https://github.com/mlfoundations/open_clip#usage)に従うことができます。また、以下の1行のpipコマンドでインストールすることもできます。

```
$ pip install open_clip_torch
```

## 既存のモデルを使用する

すべてのOpenCLIPモデルは、Hubから簡単に読み込むことができます:

```py
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')
```

読み込みが完了すると、[ゼロショット画像分類](https://huggingface.co/tasks/zero-shot-image-classification)のために画像とテキストをエンコードできます:

```py
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) 
```

各クラスの確率を出力します:

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

特定のOpenCLIPモデルを読み込みたい場合は、モデルカード内の`Use in OpenCLIP`をクリックすると、動作するスニペットが表示されます。

## 追加のリソース

* OpenCLIP [リポジトリ](https://github.com/mlfoundations/open_clip)
* OpenCLIP [ドキュメント](https://github.com/mlfoundations/open_clip/tree/main/docs)
* OpenCLIPの[ハブ上のモデル](https://huggingface.co/models?library=open_clip&sort=trending)

