CLIP
いまさら Stable Diffusion Web UI の CLIP について見てみる。
Open AI の CLIP モデル。Salesforce の BLIP が有名。あと Open CLIP。
GitHub - mlfoundations/open_clip: An open source implementation of CLIP.
https://colab.research.google.com/github/mlfoundations/open_clip/blob/ebe135b23161e375892acf72a1ee884e03976ab8/docs/Interacting_with_open_clip.ipynb#scrollTo=HBgCanxi8JKw を見れば使い方がわかる。
次のようなコードで文章と画像の類似度が計算できる。
code:hoge.py
model, _, preprocess = open_clip.create_model_and_transforms('convnext_base_w', pretrained='laion2b_s13b_b82k_augreg')
model.eval()
context_length = model.context_length
vocab_size = model.vocab_size
print("Model parameters:", f"{np.sum(int(np.prod(p.shape)) for p in model.parameters()):,}")
print("Context length:", context_length)
print("Vocab size:", vocab_size)
image_input = torch.tensor(np.stack(images))
text_tokens = tokenizer.tokenize("This is " + desc for desc in texts)
with torch.no_grad():
image_features = model.encode_image(image_input).float()
text_features = model.encode_text(text_tokens).float()
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = text_features.cpu().numpy() @ image_features.cpu().numpy().T
類似度をマトリックスで表現すると次のような画像になる。
https://gyazo.com/7dd14e82a014729bd7376fe954411dcc
文章はトークナイザによって77次元のベクトルに圧縮される。トークナイザが77次元にする理由は CLIP が扱うコンテキスト長が77であるため、77次元を期待しているから。
デモで利用されているモデルはこれ。 https://huggingface.co/laion/CLIP-convnext_base_w-laion2B-s13B-b82K-augreg
q.icon なぜ77次元なのか?
https://www.reddit.com/r/StableDiffusion/comments/wl4cn3/the_maximum_usable_length_of_a_stable_diffusion/ で議論されているが正直、謎。
i.icon リンク先のStable Diffusion の説明はとても勉強になるのであとで読んでおきたい。 https://github.com/Maks-s/sd-akashic
OpenCLIP のトークナイザはいくつか選べるようになっている。デフォルトは SimpleTokenizer
https://github.com/mlfoundations/open_clip/blob/ebe135b23161e375892acf72a1ee884e03976ab8/src/open_clip/tokenizer.py
CLIP の論文を読めばわかるかも。CLIP の実装をみてみると 77 になっている。
https://github.com/openai/CLIP/blob/a1d071733d7111c9c014f024669f959182114e33/clip/clip.py#L205
CLIP にも Colab があった。Google Colab OpenCLIP とかなり似ている。https://colab.research.google.com/github/mlfoundations/open_clip/blob/ebe135b23161e375892acf72a1ee884e03976ab8/docs/Interacting_with_open_clip.ipynb#scrollTo=IBRVTY9lbGm8
q.icon 決められたコンテキスト長があるのに Stable Diffusion Web UI はたくさんのプロンプトを詰め込める。なぜだろうか?
AI に聞いてみた。https://www.perplexity.ai/search/Why-is-77-lPmuvY72Trydlc3RjJKvUw
#Stable_Diffusion #StableDiffusion