Kakao Brain 的開源 ViT、ALIGN 和 COYO 文字-圖片資料集

HuggingFace發表於2023-03-16

最近 Kakao Brain 在 Hugging Face 釋出了一個全新的開源影像文字資料集 COYO,包含 7 億對影像和文字,並訓練了兩個新的視覺語言模型 ViT 和 ALIGN ViTALIGN

這是 ALIGN 模型首次公開發布供開源使用,同時 ViT 和 ALIGN 模型的釋出都附帶有訓練資料集。

Google 的 ViT 和 ALIGN 模型都使用了巨大的資料集 (ViT 訓練於 3 億張影像,ALIGN 訓練於 18 億個影像 - 文字對) 進行訓練,因為資料集不公開導致無法復現。Kakao Brain 的 ViT 和 ALIGN 模型採用與 Google 原始模型相同的架構和超引數,不同的是其在開源 COYO 資料集上進行訓練。對於想要擁有資料並復現視覺語言模型的研究人員有很大的價值。詳細的 Kakao ViT 和 ALIGN 模型資訊可以參照:

這篇部落格將介紹新的 COYO 資料集、Kakao Brain 的 ViT 和 ALIGN 模型,以及如何使用它們!以下是主要要點:

  • 第一個開源的 ALIGN 模型!
  • 第一個在開源資料集 COYO 上訓練的開源 ViT 和 ALIGN 模型。
  • Kakao Brain 的 ViT 和 ALIGN 模型表現與 Google 版本相當。
  • ViT 模型在 HF 上可演示!您可以使用自己的影像樣本線上體驗 ViT!

效能比較

Kakao Brain 釋出的 ViT 和 ALIGN 模型與 Google 的模型表現相當,某些方面甚至更好。Kakao Brain 的 ALIGN-B7-Base 模型雖然訓練的資料對少得多 ( 7 億 VS 1.8 億),但在影像 KNN 分類任務上表現與 Google 的 ALIGN-B7-Base 相當,在 MS-COCO 影像 - 文字檢索、文字 - 影像檢索任務上表現更好。Kakao Brain 的 ViT-L/16 在 384×512 的 ImageNet 和 ImageNet-ReaL 資料上的表現與 Google 的 ViT-L/16 相當。這意味著同行可以使用 Kakao Brain 的 ViT 和 ALIGN 模型來複現 Google 的 ViT 和 ALIGN ,尤其是當使用者需要訓練資料時。所以我們很高興開源這些與現有技術相當的模型!

COYO 資料集

本次釋出的模型特別之處在於都是基於開源的 COYO 資料集訓練的。COYO 資料集包含 7 億影像 - 文字對,類似於 Google 的 ALIGN 1.8B影像 - 文字資料集,是從網頁上收集的“嘈雜”的 html 文字 (alt-text) 和影像對。 COYO-700MALIGN 1.8B都是“嘈雜”的,只使用了適當的清洗處理。 COYO 類似於另一個開源的影像–文字資料集 LAION,但有一些區別。儘管 LAION 2B是一個更大的資料集,包含 20 億個英語配對,但 COYO的附帶有更多後設資料,為使用者提供更多靈活性和更細粒度的使用。以下表格顯示了它們之間的區別: COYO所有資料對都提供了美感評分,更健壯的水印評分和麵部計數資訊 (face count data)。

COYO LAION 2B ALIGN 1.8B
Image-text similarity score calculated with CLIP ViT-B/32 and ViT-L/14 models, they are provided as metadata but nothing is filtered out so as to avoid possible elimination bias Image-text similarity score provided with CLIP (ViT-B/32) - only examples above threshold 0.28 Minimal, Frequency based filtering
NSFW filtering on images and text NSFW filtering on images Google Cloud API
Face recognition (face count) data provided as meta-data No face recognition data NA
700 million pairs all English 2 billion English 1.8 billion
From CC 2020 Oct - 2021 Aug From CC 2014-2020 NA
Aesthetic Score Aesthetic Score Partial NA
More robust Watermark score Watermark Score NA
Hugging Face Hub Hugging Face Hub Not made public
English English English?

ViT 和 ALIGN 是如何工作的

這些模型是幹什麼的?讓我們簡要討論一下 ViT 和 ALIGN 模型的工作原理。

ViT—Vision Transformer 是谷歌於 2020 年提出的一種視覺模型,類似於文字 Transformer 架構。這是一種與卷積神經網路不同的視覺方法 (AlexNet 自 2012 年以來一直主導視覺任務)。同樣表現下,它的計算效率比 CNN 高達四倍,且具有域不可知性 (domain agnostic)。ViT 將輸入的影像分解成一系列影像塊 (patch),就像文字 Transformer 輸入文字序列一樣,然後為每個塊提供位置嵌入以學習影像結構。ViT 的效能尤其在於具有出色的效能 - 計算權衡。谷歌的一些 ViT 模型是開源的,但其訓練使用的 JFT-300 百萬影像 - 標籤對資料集尚未公開發布。Kakao Brain 的訓練模型是基於公開發布的 COYO-Labeled-300M 進行訓練,對應的 ViT 模型在各種任務上具有相似表現,其程式碼、模型和訓練資料 (COYO-Labeled-300M) 完全公開,以便能夠進行復現和科學研究。

谷歌在 2021 年推出了 ALIGN,它是一種基於“嘈雜”文字–影像資料訓練的視覺語言模型,可用於各種視覺和跨模態任務,如文字 - 影像檢索。ALIGN 採用簡單的雙編碼器架構,透過對比損失函式學習影像和文字對,ALIGN 的“嘈雜”訓練語料特點包括用語料規模彌補其噪音以及強大的魯棒性。之前的視覺語言表示學習都是在手動標註的大規模資料集上進行訓練,這就需要大量的預先處理和成本。ALIGN 的語料庫使用 HTML 文字 (alt-text) 資料作為影像的描述,導致資料集不可避免地嘈雜,但更大的資料量 (18 億對) 使 ALIGN 能夠在各種任務上表現出 SoTA 水平。Kakao Brain 的模型是第一個 ALIGN 開源版本,它在 COYO 資料集上訓練,表現比谷歌的結果更好。

如何使用 COYO 資料集

我們可以使用 Hugging Face ? 資料集庫的一行程式碼方便地下載 COYO 資料集。要預覽 COYO 資料集並瞭解資料處理過程和包含的元屬性,請前往 Hub 資料集頁面。

開始前,請安裝 Hugging Face ? 資料集庫: pip install datasets,然後下載資料集。

from datasets import load_dataset

dataset = load_dataset('kakaobrain/coyo-700m')
dataset

由於 COYO 資料集非常龐大,包含 747M 個影像 - 文字對,您可能無法在本地下載整個資料集。或者可能只需要下載和使用資料集的子集。為此,可以簡單地將 streaming=True 引數傳遞給 load_dataset()方法,以建立可迭代資料集,並在需要時下載資料例項。

from datasets import load_dataset

dataset = load_dataset('kakaobrain/coyo-700m', streaming=True)
print(next(iter(dataset['train'])))
{'id': 2680060225205, 'url': 'https://cdn.shopify.com/s/files/1/0286/3900/2698/products/TVN_Huile-olive-infuse-et-s-227x300_e9a90ffd-b6d2-4118-95a1-29a5c7a05a49_800x.jpg?v=1616684087', 'text': 'Olive oil infused with Tuscany herbs', 'width': 227, 'height': 300, 'image_phash': '9f91e133b1924e4e', 'text_length': 36, 'word_count': 6, 'num_tokens_bert': 6, 'num_tokens_gpt': 9, 'num_faces': 0, 'clip_similarity_vitb32': 0.19921875, 'clip_similarity_vitl14': 0.147216796875, 'nsfw_score_opennsfw2': 0.0058441162109375, 'nsfw_score_gantman': 0.018961310386657715, 'watermark_score': 0.11015450954437256, 'aesthetic_score_laion_v2': 4.871710777282715}

如何使用 Hub 中的 ViT 和 ALIGN

讓我們嘗試一下新的 ViT 和 ALIGN 模型。由於 ALIGN 是新加入 Hugging Face ? Transformers 的,我們先安裝最新版本的庫: pip install -q git+https://github.com/huggingface/transformers.git然後匯入我們將要使用的模組和庫,開始使用 ViT 進行影像分類。請注意,新新增的 ALIGN 模型將會包含到下一版 PyPI 包。

import requests
from PIL import Image
import torch
from transformers import ViTImageProcessor, ViTForImageClassification

接下來,我們將從 COCO 資料集中隨機下載一張有沙發影像,上邊有兩隻貓和一個遙控器,並對影像進行預處理為模型所期望的輸入格式,我們可以方便地使用相應的前處理器類 (ViTProcessor) 實現這一步。初始化模型和前處理器,可以使用 Hub 中 Kakao Brain ViT repos 之一。請注意使用 Hub 中的庫前處理器,確保預處理後的影像符合特定預訓練模型所需的格式。

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

processor = ViTImageProcessor.from_pretrained('kakaobrain/vit-large-patch16-384')
model = ViTForImageClassification.from_pretrained('kakaobrain/vit-large-patch16-384')

接下來將影像預處理並將其輸入到模型,實現檢索類別標籤。Kakao Brain ViT 影像分類模型是在 ImageNet 標籤上訓練的,輸出形狀為 batch_size×1000 維度的類別 (logits)。

# preprocess image or list of images
inputs = processor(images=image, return_tensors="pt")

# inference
with torch.no_grad():
    outputs = model(**inputs)

# apply SoftMax to logits to compute the probability of each class
preds = torch.nn.functional.softmax(outputs.logits, dim=-1)

# print the top 5 class predictions and their probabilities
top_class_preds = torch.argsort(preds, descending=True)[0, :5]

for c in top_class_preds:
    print(f"{model.config.id2label[c.item()]} with probability {round(preds[0, c.item()].item(), 4)}")

到這裡就完成了!為了更加簡單和簡潔,還可以使用影像分類管道 (pipeline) 並將 Kakao Brain ViT 倉庫名稱作為目標模型傳遞給初始化管道。然後,我們可以傳入影像的 URL 或本地路徑,或 Pillow 影像,可選“top_k”參數列述返回前 k 個預測。讓我們繼續對貓和遙控器圖片獲取前 5 個預測結果。

from transformers import pipeline

classifier = pipeline(task='image-classification', model='kakaobrain/vit-large-patch16-384')
classifier('http://images.cocodataset.org/val2017/000000039769.jpg', top_k=5)

如果您想更多地嘗試 Kakao Brain ViT 模型,請前往 ? Hub 中心的專案空間

我們開始實驗 ALIGN,它可用於檢索文字或影像的多模態嵌入或執行零樣本影像分類。ALIGN 的 Transformer 實現和用法類似於 CLIP。首先,下載預訓練模型和其處理器 (processor),處理器預處理影像和文字,使它們符合 ALIGN 的預期格式,以便將其輸入到視覺和文字編碼器中。這步匯入了我們將要使用的模組並初始化前處理器和模型。

import requests
from PIL import Image
import torch
from transformers import AlignProcessor, AlignModel

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

processor = AlignProcessor.from_pretrained('kakaobrain/align-base')
model = AlignModel.from_pretrained('kakaobrain/align-base')

先從零樣本影像分類開始。為此,我們將提供候選標籤 (自由格式文字),並使用 AlignModel 找出更好地描述影像的表述。我們將首先預處理影像和文字輸入,並將預處理後的輸入送到 AlignModel 中。

candidate_labels = ['an image of a cat', 'an image of a dog']

inputs = processor(images=image, text=candidate_labels, return_tensors='pt')

with torch.no_grad():
    outputs = model(**inputs)

# this is the image-text similarity score
logits_per_image = outputs.logits_per_image

# we can take the softmax to get the label probabilities
probs = logits_per_image.softmax(dim=1)
print(probs)

完成了,就這麼簡單。要進一步嘗試 Kakao Brain ALIGN 模型進行零樣本影像分類,只需前往 Hugging Face ? Hub 上的 demo 演示。請注意, AlignModel 的輸出包括 text_embedsimage_embeds (參閱 ALIGN 的 文件)。如果不需要計算用於零樣本分類的每個影像和每個文字的邏輯 (logits),可以使用 AlignModel 類中的 get_image_features()get_text_features() 方法便捷地檢索視覺和文字嵌入。

text_embeds = model.get_text_features(
    input_ids=inputs['input_ids'],
    attention_mask=inputs['attention_mask'],
    token_type_ids=inputs['token_type_ids'],
)
image_embeds = model.get_image_features(
    pixel_values=inputs['pixel_values'],
)

或者,我們可以使用 ALIGN 的獨立視覺和文字編碼器獲取多模態嵌入。然後可以使用這些嵌入用於各種下游任務的模型訓練,例如目標檢測、影像分割和影像字幕生成。讓我們看看如何使用 AlignTextModelAlignVisionModel 獲取這些嵌入。請注意,我們可以使用便捷的 AlignProcessor 類分別對文字和影像進行預處理。

from transformers import AlignTextModel

processor = AlignProcessor.from_pretrained('kakaobrain/align-base')
model = AlignTextModel.from_pretrained('kakaobrain/align-base')

# get embeddings of two text queries
inputs = processor(['an image of a cat', 'an image of a dog'], return_tensors='pt')

with torch.no_grad():
    outputs = model(**inputs)

# get the last hidden state and the final pooled output
last_hidden_state = outputs.last_hidden_state
pooled_output = outputs.pooler_output

我們也可以在推理過程中設定 output_hidden_states 和 output_attentions 引數為 True,以返回所有隱藏狀態和注意力值。

with torch.no_grad():
    outputs = model(**inputs, output_hidden_states=True, output_attentions=True)
# print what information is returned
for key, value in outputs.items():
    print(key)

在 AlignVisionModel 中執行相同的操作,獲取影像的多模態嵌入。

from transformers import AlignVisionModel

processor = AlignProcessor.from_pretrained('kakaobrain/align-base')
model = AlignVisionModel.from_pretrained('kakaobrain/align-base')

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

inputs = processor(images=image, return_tensors='pt')

with torch.no_grad():
    outputs = model(**inputs)

# print the last hidden state and the final pooled output
last_hidden_state = outputs.last_hidden_state
pooled_output = outputs.pooler_output

與 ViT 類似,使用零樣本影像分類管道 (pipeline) 可以讓過程更加輕鬆。以下實現瞭如何使用此流程使用自由文字候選標籤在野外執行影像分類。

from transformers import pipeline

classifier = pipeline(task='zero-shot-image-classification', model='kakaobrain/align-base')
classifier(
    'https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png',
    candidate_labels=['animals', 'humans', 'landscape'],
)

classifier(
   'https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png',
   candidate_labels=['black and white', 'photorealist', 'painting'],
)

結論

近年來,多模態取得了令人難以置信的進展,例如 CLIP 和 ALIGN 等模型賦能了各種下游任務,例如影像描述、零樣本影像分類和開放世界目標檢測。本部落格,我們介紹了由 Kakao Brain 貢獻的最新開原始碼 ViT 和 ALIGN 模型,以及新的 COYO 文字 - 影像資料集。展示瞭如何使用這些模型執行各種任務,只需幾行程式碼即可單獨使用或作為 ? Transformers pipeline 的一部分使用。

我們正在繼續整合最有影響力的計算機視覺和多模型模型,並樂於聽取您的反饋。要了解計算機視覺和多模態研究的最新訊息,作者及 Twitter: @adirik、@a_e_roberts、@NielsRogge、@RisingSayak 和 @huggingface。


英文原文: https://huggingface.co/blog/vit-align

作者: Alara Dirik、Unso Eun Seo Jo、Minwoo Byeon、sungjunlee

譯者: Cony Zhang (張聰聰)

審校、排版: zhongdongy (阿東)

相關文章