Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CoCa: Condition captioning loss on the CLIP similarity #469

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/open_clip/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def __init__(

self.clip_loss_weight = clip_loss_weight
self.caption_loss_weight = caption_loss_weight
self.caption_loss = nn.CrossEntropyLoss(ignore_index=pad_id)
self.caption_loss = nn.CrossEntropyLoss(reduction='none', ignore_index=pad_id)

def forward(self, image_features, text_features, logits, labels, logit_scale, output_dict=False):
clip_loss = super().forward(image_features, text_features, logit_scale)
Expand All @@ -165,6 +165,26 @@ def forward(self, image_features, text_features, logits, labels, logit_scale, ou
logits.permute(0, 2, 1),
labels,
)

# IDEAS:
# - do we let gradients prop backward from this? maybe a torch.no_grad is due here
# - normalization,
# - we want the distribution to be soft so maybe logit scale? !!!
# - maybe just softmax is fine since we expect it to be unifrom
# p(good_sammple) >> p(bad_sample)
# - TODO: right now posterior = evidence, we need to figure out a smarter
# way of updating our prior which is p(gs) = 1 based on the evidence (CLIP dist)
with torch.no_grad():
cap_weights = (logit_scale * image_features @ text_features.T).softmax(dim=1).diag().unsqueeze(1)
# adjustment = (cap_weights.shape[0] + 1 - cap_weights.sum()) # in the beginning sim ~ U(bs)
# cap_weights = cap_weights * adjustment

def custom_backward_hook(grad):
return cap_weights * grad
caption_loss.register_hook(custom_backward_hook)

caption_loss = torch.mean(caption_loss[caption_loss != 0.0])

caption_loss = caption_loss * self.caption_loss_weight

if output_dict:
Expand Down