Skip to content

Commit

Permalink
contrastive loss needs both directions
Browse files Browse the repository at this point in the history
  • Loading branch information
lucidrains committed Mar 29, 2023
1 parent cad7b49 commit b95e54b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
13 changes: 8 additions & 5 deletions musiclm_pytorch/musiclm_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,10 +581,12 @@ def forward(self, *, audio_layers, text_layers):
eye = torch.eye(batch, device = device, dtype = torch.bool)
cosine_sims_exp = cosine_sims_exp.masked_fill(eye, 0.)

denominator = reduce(cosine_sims_exp, 'l i j -> l i', 'sum')
contrastive_loss = -log(numerator) + log(denominator)
denominator_i = reduce(cosine_sims_exp, 'l i j -> l i', 'sum')
denominator_j = reduce(cosine_sims_exp, 'l i j -> l j', 'sum')

contrastive_loss = reduce(contrastive_loss, 'l i -> l', 'mean')
contrastive_loss = -log(numerator) + 0.5 * (log(denominator_i) + log(denominator_j))

contrastive_loss = reduce(contrastive_loss, 'l n -> l', 'mean')
return contrastive_loss.sum()

# main classes
Expand Down Expand Up @@ -696,9 +698,10 @@ def forward(
eye = torch.eye(batch, device = device, dtype = torch.bool)
cosine_sim_exp = cosine_sim_exp.masked_fill(eye, 0.)

denominator = reduce(cosine_sim_exp, 'i j -> i', 'sum')
denominator_i = reduce(cosine_sim_exp, 'i j -> i', 'sum')
denominator_j = reduce(cosine_sim_exp, 'i j -> j', 'sum')

contrastive_loss = -log(numerator) + log(denominator)
contrastive_loss = -log(numerator) + 0.5 * (log(denominator_i) + log(denominator_j))
cl_loss = contrastive_loss.mean()

if not exists(self.multi_layer_contrastive_learning):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
setup(
name = 'musiclm-pytorch',
packages = find_packages(exclude=[]),
version = '0.1.1',
version = '0.1.2',
license='MIT',
description = 'MusicLM - AudioLM + Audio CLIP to text to music synthesis',
author = 'Phil Wang',
Expand Down

0 comments on commit b95e54b

Please sign in to comment.