The CoCa class implements the Contrastive Captioners architecture. It requires a vision transformer (ViT) as the img_encoder.
Important: The vision transformer must be wrapped in an Extractor with return_embeddings_only = True so that it returns embeddings of shape (batch, seq, dim) instead of class logits.
Key parameters for CoCa:
dim: Model dimension.img_encoder: The vision transformer (wrapped in Extractor).image_dim: Dimension of the image embeddings (if different from dim).num_tokens: Vocabulary size for text tokens.unimodal_depth: Depth of the unimodal transformer.multimodal_depth: Depth of the multimodal transformer.dim_head: Dimension per attention head.heads: Number of attention heads.caption_loss_weight: Weight for the autoregressive caption loss.contrastive_loss_weight: Weight for the contrastive loss between image and text CLS embeddings.
from vit_pytorch.simple_vit_with_patch_dropout import SimpleViT
from vit_pytorch.extractor import Extractor
from coca_pytorch.coca_pytorch import CoCa
import torch
# 1. Setup the vision transformer with Extractor
vit = SimpleViT(
image_size = 256,
patch_size = 32,
num_classes = 1000,
dim = 1024,
depth = 6,
heads = 16,
mlp_dim = 2048,
patch_dropout = 0.5
)
vit = Extractor(vit, return_embeddings_only = True, detach = False)
# 2. Instantiate CoCa
coca = CoCa(
dim = 512,
img_encoder = vit,
image_dim = 1024,
num_tokens = 20000,
unimodal_depth = 6,
multimodal_depth = 6,
dim_head = 64,
heads = 8,
caption_loss_weight = 1.,
contrastive_loss_weight = 1.
).cuda()