模型:

Bingsu/clip-vit-base-patch32-ko

英文

clip-vit-base-patch32-ko

由 Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation 训练的韩文CLIP模型

Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation 로 학습된 한국어 CLIP 모델입니다.

训练代码: https://github.com/Bing-su/KoCLIP_training_code

使用的数据:AIHUB中的所有韩语-英语平行数据

使用方法

1.
import requests
import torch
from PIL import Image
from transformers import AutoModel, AutoProcessor

repo = "Bingsu/clip-vit-base-patch32-ko"
model = AutoModel.from_pretrained(repo)
processor = AutoProcessor.from_pretrained(repo)

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(text=["고양이 두 마리", "개 두 마리"], images=image, return_tensors="pt", padding=True)
with torch.inference_mode():
    outputs = model(**inputs)
logits_per_image = outputs.logits_per_image
probs = logits_per_image.softmax(dim=1)
>>> probs
tensor([[0.9926, 0.0074]])
2.
from transformers import pipeline

repo = "Bingsu/clip-vit-base-patch32-ko"
pipe = pipeline("zero-shot-image-classification", model=repo)

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
result = pipe(images=url, candidate_labels=["고양이 한 마리", "고양이 두 마리", "분홍색 소파에 드러누운 고양이 친구들"], hypothesis_template="{}")
>>> result
[{'score': 0.9456236958503723, 'label': '분홍색 소파에 드러누운 고양이 친구들'},
 {'score': 0.05315302312374115, 'label': '고양이 두 마리'},
 {'score': 0.0012233294546604156, 'label': '고양이 한 마리'}]

分词器

分词器通过将韩语数据和英语数据按7:3的比例混合来进行训练,使用原始CLIP分词器的.train_new_from_iterator进行训练。

https://github.com/huggingface/transformers/blob/bc21aaca789f1a366c05e8b5e111632944886393/src/transformers/models/clip/modeling_clip.py#L661-L666

        # text_embeds.shape = [batch_size, sequence_length, transformer.width]
        # take features from the eot embedding (eot_token is the highest number in each sequence)
        # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
        pooled_output = last_hidden_state[
            torch.arange(last_hidden_state.shape[0]), input_ids.to(torch.int).argmax(dim=-1)
        ]

由于CLIP模型在计算pooled_output时使用最大的id作为标记,因此eos标记应该是最后一个标记。