forked from AngeLouCN/Min_Max_Similarity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrastive_loss.py
120 lines (95 loc) · 4.41 KB
/
contrastive_loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 3 11:37:12 2022
@author: loua2
"""
import torch
from torch import nn
import torch.nn.functional as F
import warnings
warnings.filterwarnings("ignore")
class ConLoss(torch.nn.Module):
def __init__(self, temperature=0.07, base_temperature=0.07):
"""
Contrastive Learning for Unpaired Image-to-Image Translation
models/patchnce.py
"""
super(ConLoss, self).__init__()
self.temperature = temperature
self.base_temperature = base_temperature
self.nce_includes_all_negatives_from_minibatch = False
self.cross_entropy_loss = torch.nn.CrossEntropyLoss()
self.mask_dtype = torch.bool
def forward(self, feat_q, feat_k):
assert feat_q.size() == feat_k.size(), (feat_q.size(), feat_k.size())
batch_size = feat_q.shape[0]
dim = feat_q.shape[1]
width = feat_q.shape[2]
feat_q = feat_q.view(batch_size, dim, -1).permute(0, 2, 1)
feat_k = feat_k.view(batch_size, dim, -1).permute(0, 2, 1)
feat_q = F.normalize(feat_q, dim=-1, p=1)
feat_k = F.normalize(feat_k, dim=-1, p=1)
feat_k = feat_k.detach()
# pos logit
l_pos = torch.bmm(feat_q.reshape(-1, 1, dim), feat_k.reshape(-1, dim, 1))
l_pos = l_pos.view(-1, 1)
# neg logit
if self.nce_includes_all_negatives_from_minibatch:
# reshape features as if they are all negatives of minibatch of size 1.
batch_dim_for_bmm = 1
else:
batch_dim_for_bmm = batch_size
# reshape features to batch size
feat_q = feat_q.reshape(batch_dim_for_bmm, -1, dim)
feat_k = feat_k.reshape(batch_dim_for_bmm, -1, dim)
npatches = feat_q.size(1)
l_neg_curbatch = torch.bmm(feat_q, feat_k.transpose(2, 1))
diagonal = torch.eye(npatches, device=feat_q.device, dtype=self.mask_dtype)[None, :, :]
l_neg_curbatch.masked_fill_(diagonal, -10.0)
l_neg = l_neg_curbatch.view(-1, npatches)
out = torch.cat((l_pos, l_neg), dim=1) / self.temperature
loss = self.cross_entropy_loss(out, torch.zeros(out.size(0), dtype=torch.long,
device=feat_q.device))
return loss
class contrastive_loss_sup(torch.nn.Module):
def __init__(self, temperature=0.07, base_temperature=0.07):
"""
Contrastive Learning for Unpaired Image-to-Image Translation
models/patchnce.py
"""
super(contrastive_loss_sup, self).__init__()
self.temperature = temperature
self.base_temperature = base_temperature
self.nce_includes_all_negatives_from_minibatch = False
self.cross_entropy_loss = torch.nn.CrossEntropyLoss()
self.mask_dtype = torch.bool
def forward(self, feat_q, feat_k):
assert feat_q.size() == feat_k.size(), (feat_q.size(), feat_k.size())
batch_size = feat_q.shape[0]
dim = feat_q.shape[1]
width = feat_q.shape[2]
feat_q = feat_q.view(batch_size, dim, -1).permute(0, 2, 1)
feat_k = feat_k.view(batch_size, dim, -1).permute(0, 2, 1)
feat_q = F.normalize(feat_q, dim=-1, p=1)
feat_k = F.normalize(feat_k, dim=-1, p=1)
feat_k = feat_k.detach()
# pos logit
l_pos = torch.zeros((batch_size*2304,1)).cuda()
# neg logit
if self.nce_includes_all_negatives_from_minibatch:
# reshape features as if they are all negatives of minibatch of size 1.
batch_dim_for_bmm = 1
else:
batch_dim_for_bmm = batch_size
# reshape features to batch size
feat_q = feat_q.reshape(batch_dim_for_bmm, -1, dim)
feat_k = feat_k.reshape(batch_dim_for_bmm, -1, dim)
npatches = feat_q.size(1)
l_neg_curbatch = torch.bmm(feat_q, feat_k.transpose(2, 1))
diagonal = torch.eye(npatches, device=feat_q.device, dtype=self.mask_dtype)[None, :, :]
l_neg_curbatch.masked_fill_(diagonal, -10.0)
l_neg = l_neg_curbatch.view(-1, npatches)
out = torch.cat((l_pos, l_neg), dim=1) / self.temperature
loss = self.cross_entropy_loss(out, torch.zeros(out.size(0), dtype=torch.long,
device=feat_q.device))
return loss