Implement Multiview Contrastive Learning (DeCLIP)
mainTo support multiview contrastive learning, set multiview_loss_weight during CLIP initialization. When calling the model, pass augmented text and/or images using aug_text and aug_image. These arguments can accept single tensors or tuples of tensors for multiple augmentations.
multiview_loss_weight: Weight for the multiview contrastive loss.aug_text: Augmented text (e.g., backtranslation). Shape:(batch, seq_len)or tuple of such tensors.aug_image: Augmented images. Shape:(batch, C, H, W)or tuple of such tensors.
import torch
from x_clip import CLIP, TextTransformer
# ... (setup encoders) ...
clip = CLIP(
image_encoder = image_encoder,
text_encoder = text_encoder,
dim_image = 512,
dim_text = 512,
dim_latent = 512,
extra_latent_projection = True,
multiview_loss_weight = 0.1
)
text = torch.randint(0, 10000, (4, 256))
images = torch.randn(4, 3, 256, 256)
aug_text = torch.randint(0, 10000, (4, 256))
aug_images = torch.randn(4, 3, 256, 256)
loss = clip(
text,
images,
aug_text = aug_text,
aug_image = aug_images,
return_loss = True,
freeze_image_encoder = True
)
loss.backward()