ViT-L-16-SigLIP-256项目介绍
项目背景
ViT-L-16-SigLIP-256是一个基于SigLIP(接受Sigmoid损失的语言图像预训练技术)的模型,该模型训练于WebLI数据集。SigLIP技术主要针对语言与图像信息的对比学习。这个模型最初使用由Google主导的Big Vision项目中JAX框架开发,并且已经被转换为PyTorch格式,便于在OpenCLIP(图片与文本)和timm(仅图片)中使用。
模型详情
- 模型类型: 对比学习图像-文本分类,支持零样本图像分类(Zero-Shot Image Classification)。
- 数据集: WebLI数据集。
- 相关论文: 该模型的开发论文名为《Sigmoid loss for language image pre-training》,详细信息可以在arXiv上查阅(https://arxiv.org/abs/2303.15343)。
模型使用说明
使用OpenCLIP进行预测
在OpenCLIP中,首先需要加载预训练模型及其对应的文本分词器,然后将图像和标签列表经过预处理和编码后进行匹配。通过Sigmoid激活函数,模型可以输出每个标签的概率。以下是示例代码:
import torch
import torch.nn.functional as F
from urllib.request import urlopen
from PIL import Image
from open_clip import create_model_from_pretrained, get_tokenizer
model, preprocess = create_model_from_pretrained('hf-hub:timm/ViT-L-16-SigLIP-256')
tokenizer = get_tokenizer('hf-hub:timm/ViT-L-16-SigLIP-256')
image = Image.open(urlopen('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'))
image = preprocess(image).unsqueeze(0)
labels_list = ["a dog", "a cat", "a donut", "a beignet"]
text = tokenizer(labels_list, context_length=model.context_length)
with torch.no_grad(), torch.cuda.amp.autocast():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
image_features = F.normalize(image_features, dim=-1)
text_features = F.normalize(text_features, dim=-1)
text_probs = torch.sigmoid(image_features @ text_features.T * model.logit_scale.exp() + model.logit_bias)
zipped_list = list(zip(labels_list, [round(p.item(), 3) for p in text_probs[0]]))
print("Label probabilities: ", zipped_list)
使用timm进行图像嵌入提取
如果只需要图像嵌入,可以使用timm库。首先,要加载预训练模型,并获取与模型对应的图像变换。以下是示例代码:
from urllib.request import urlopen
from PIL import Image
import timm
image = Image.open(urlopen('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'))
model = timm.create_model(
'vit_large_patch16_siglip_256',
pretrained=True,
num_classes=0,
)
model = model.eval()
# get model specific transforms (normalization, resize)
data_config = timm.data.resolve_model_data_config(model)
transforms = timm.data.create_transform(**data_config, is_training=False)
output = model(transforms(image).unsqueeze(0)) # output is (batch_size, num_features) shaped tensor
项目参考文献
如需更多技术细节或研究背景,请参考以下论文和资源:
- Zhai, Xiaohua, et al. "Sigmoid loss for language image pre-training." arXiv preprint arXiv:2303.15343, 2023.
- Beyer, Lucas, et al. "Big Vision." GitHub repository, 2022. Big Vision