CLIP score计算

1,211次阅读
没有评论
CLIP score计算

CLIP score是一种用于评估 text2img 或者 img2img,模型生成的图像与原文本(prompt text)或者原图关联度大小的指标。

Parti Prompts(https://huggingface.co/datasets/nateraw/parti-prompts) 是一个包含1600个左右各类prompt的数据集。

使用 clip score 可以用于评估stable diffusion等text2img模型的效果。

1 Taited/clip-score

github :

https://github.com/Taited/clip-score​github.com/Taited/clip-score

预安装库

# install pytorch
pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu116 # Choose a version that suits your GPU
# install CLIP
pip install openai-clip
# Install clip-score from PyPI:
pip install clip-score
# 拉取clip-score
git clone https://github.com/Taited/clip-score

文件准备

使用clip-score进行text2img关联度计算,对生成的图片和text文本有以下要求:

  1. 生成的图片必须是png或者jpg 格式
  2. 每一个prompt单独写在一个纯文本文件内,以 .txt结尾。
  3. 图片和文本文件必须存放在两个目录内。
  4. 图片的名称和文本文件的名称必须要一一对应,比如有 img_dir/cat.jpg,就要有text_dir/cat.txt(名字可以随便起,只要能图片名称和文本名称能对应起来即可。 文本文件的内容(prompt)是与图片对应的prompt)。

Directory Structure Example

Below is an example of the expected directory structure:

├── path/to/image
│   ├── cat.png
│   ├── dog.png
│   └── bird.jpg
└── path/to/text
    ├── cat.txt
    ├── dog.txt
    └── bird.txt

In this example,cat.pngis paired withcat.txt,dog.pngis paired withdog.txt, andbird.jpgis paired withbird.txt.

clip score使用

# 使用 clip-score仓库下的clip_score
python -m clip-score/clip_score path/to/image path/to/text

如果存在可用的GPU设备,此程序会自动执行在GPU设备上。 如果你想制定某个GPU 设备,通过 –device cuda:N 去指定。 –device cpu , 表示执行在CPU上。

clip-score/clip_score.py 目前限制 prompt最大长度为77个。如果超过77,默认会挂掉。
可通过修改https://github.com/Taited/clip-score/blob/dbfa0cabd7bfe12f84899786731c35aa62baab4a/src/clip_score/clip_score.py#L131,修改为data = self.tokenizer(data,truncate=True).squeeze(),把超过77的部分截断。

结果展示

CLIP score计算
clip score

2 HuggingFace evaluating

Evaluating Diffusion Models​huggingface.co/docs/diffusers/conceptual/evaluation

环境准备

pip install torchmetrics==0.11.0
# install pytorch
pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu116 # Choose a version that suits your GPU

HF clip_score计算

from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
import torch
import pandas as pd
from PIL import Image
import numpy as np
# for clip_score
from torchmetrics.functional.multimodal import clip_score
from functools import partial

# 加载CLIP模型
clip_score_fn = partial(clip_score, model_name_or_path="openai/clip-vit-base-patch16")

def calculate_clip_score(images, prompts):
    # import pdb;pdb.set_trace()
    # images_int = (np.asarray(images[0]) * 255).astype("uint8")
    images_int = (np.asarray(images) * 255).astype("uint8")
    clip_score = clip_score_fn(torch.from_numpy(images_int).permute(0, 3, 1, 2), prompts).detach()
    return round(float(clip_score), 4)

# 设定随机数种子,规定随机数。  从而使每次执行同样的prompt,生成图片一样
torch.manual_seed(0)

# load a StableDiffusionPipeline 
# 指定加载的stable diffusion模型名称
model_id = "stabilityai/stable-diffusion-2-1-base"
scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler, torch_dtype=torch.float16)
pipe = pipe.to("cuda:1")

prompt = "wood"
images = pipe(prompt, num_images_per_prompt=1, output_type="numpy").images
# 保存图片,此步骤对于计算clip score不是必要的。
images[0].save("wood.png")
# CLIP分数计算
sd_clip_score = calculate_clip_score(images, prompts)
print(f"CLIP score: {sd_clip_score}")
正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 
评论(没有评论)