CSM.py 7.27 KB
Newer Older
1
2
import torch
import torch.nn.functional as F
3
import matplotlib.pyplot as plt
4

5
from main import coco_class_names
6

7
8
9
10
11

def calc_yolo_person_csms(imgs_and_logits: torch.Tensor,
                          sign: bool = True,
                          rescale_factor = 0,
                          loss_rescale_factor = 1) -> torch.Tensor:
12
    '''
13
    computes the YOLO cosine similarity map for given input images X
14
15
16
17

    Parameters
    ---------
    model: torch model
18
    imgs_and_logits: torch tensor; shape: (Batch_Size, Channels, Width, Height)
19
    sign: use sign of gradients to calculate cosine similarity maps
20

21
22
23
24
25
26
27
28

    Returns
    ---------
    return: cosine_similarity_map:
    '''

    csms = []  # saliency maps w.r.t. all possible output classes
    imgs = []
29
    clss = []
30

31
32
    for tup in imgs_and_logits:
        img, logit, frame, x1, y1, x2, y2 = tup
33
34
        if not img.requires_grad:
            img.requires_grad_()
35
        cls = torch.argmax(logit)
36
37

        # rescale network output to avoid gradient obfuscation
38
39
        if rescale_factor > 0:
            logit = rescale_factor * logit / torch.max(torch.abs(logit))
40

41
        # calculate all classes
42
        classes = len(logit)
43
44
45
46
47
48
49
50
51

        # get top10 classes and person
        classes = list(torch.sort(logit, descending=True)[1][:10])
        class_names = [coco_class_names[c] for c in classes]

        if classes[0] != 0:  # do not consider predictions if person is not the top prediction
            continue

        print(f'Top Ten: {class_names}')
52
53

        deltas = []
54
        for c in classes:
55
56
            #  calculate loss and compute gradient w.r.t. the input of the current class
            y = torch.ones(1, device="cuda", dtype=torch.long) * c
57
58
            loss = F.cross_entropy(logit.unsqueeze(0), y) * loss_rescale_factor
            frame_grad = torch.autograd.grad(loss, frame, retain_graph=True)[0]
59
60
            img_grad = frame_grad[int(y1):int(y2), int(x1):int(x2), :]

61
62
63
64
65
66
            try:
                if torch.min(img_grad) == 0:
                    print(f"img grad contains zero {c}")
            except Exception as e:
                print(e)

67
68
69
70
71
72
73
74
75
            #  take sign of gradient as in the original paper
            if sign:
                img_grad = torch.sign(img_grad)

            deltas.append(img_grad.clone().detach())

        deltas = torch.stack(deltas)
        #  compute cosine similarity matrices

76
77
78
79
80
        deltas = torch.max(deltas, dim=-1).values  # take only the maximum value of all channels to compute the
        deltas = deltas.view(len(classes), 1, -1)
        norm = torch.norm(deltas, p=2, dim=2, keepdim=True)
        # norm[norm == 0] = 1
        if torch.min(norm) != 0:
81
            deltas = deltas / norm
82
83
84
85
        else:
            print("norm min contains 0")
        deltas = deltas.transpose(0, 1)
        csm = torch.matmul(deltas, deltas.transpose(1, 2))
86
87
88

        #  division by zero can lead to NaNs
        if torch.isnan(csm).any():
89
90
            raise Exception("NaNs in CSM!")
            # print("NaNs in csm")
91
        else:
92
            imgs.append(img)
93
            csms.append(csm)
94
95
            clss.append(cls)
    return imgs, csms, clss
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219


def calc_csm(model: torch.nn.Module,
             X: torch.Tensor,
             sign: bool = True,
             rescale: bool = True) -> torch.Tensor:
    '''
    computes the cosine similarity map for given input images X

    Parameters
    ---------
    model: torch model
    X: torch tensor; shape: (Batch_Size, Channels, Width, Height)
    sign: use sign of gradients to calculate cosine similarity maps
    rescale: rescale the logits before applying softmax -> solves gradient obfuscation problem of large logits

    Returns
    ---------
    return: cosine_similarity_map:
    '''

    deltas = []  # saliency maps w.r.t. all possible output classes
    if not X.requires_grad:
        X.requires_grad_()

    logits = model(X)  # network output

    # rescale network output to avoid gradient obfuscation
    if rescale:
        logits = logits / torch.max(torch.abs(logits), 1, keepdim=True).values * 10

    B = logits.shape[0]  # batch size
    classes = logits.shape[-1]  # output classes

    for c in range(classes):
        #  calculate loss and compute gradient w.r.t. the input of the current class
        y = torch.ones(B, device="cuda", dtype=torch.long) * c
        loss = F.cross_entropy(logits, y)
        grad = torch.autograd.grad(loss, X, retain_graph=True)[0]

        #  take sign of gradient as in the original paper
        if sign:
            grad = torch.sign(grad)
        deltas.append(grad.detach().clone())

    model.zero_grad()
    deltas = torch.stack(deltas, dim=0)

    deltas = torch.max(deltas,
                       dim=-3).values  # take only the maximum value of all channels to compute the cosine similarity

    #  compute cosine similarity matrices
    deltas = deltas.view(classes, B, -1)
    norm = torch.norm(deltas, p=2, dim=2, keepdim=True)
    deltas = deltas / norm
    deltas = deltas.transpose(0, 1)
    csm = torch.matmul(deltas, deltas.transpose(1, 2))

    #  division by zero can lead to NaNs
    if torch.isnan(csm).any():
        raise Exception("NaNs in CSM!")
    return csm


def calc_csm_partial_network(model_first_part: torch.nn.Module,
                             model_second_part: torch.nn.Module,
                             X: torch.Tensor,
                             sign: bool = True,
                             rescale: bool = True,
                             scalar_product: bool = False) -> torch.Tensor:
    '''
        computes the cosine similarity map for given input images X

        Parameters
        ---------
        model: torch model
        X: torch tensor; shape: (Batch_Size, Channels, Width, Height)
        sign: use sign of gradients to calculate cosine similarity maps
        rescale: rescale the logits before applying softmax -> solves gradient obfuscation problem of large logits

        Returns
        ---------
        return: cosine_similarity_map:
        '''

    deltas = []  # saliency maps w.r.t. all possible output classes

    pre_ultimate_output = model_first_part(X)
    pre_ultimate_output.requires_grad_()
    logits = model_second_part(pre_ultimate_output)  # network output

    # rescale network output to avoid gradient obfuscation
    if rescale:
        logits = logits / torch.max(torch.abs(logits), 1, keepdim=True).values * 10

    B = logits.shape[0]  # batch size
    classes = logits.shape[-1]  # output classes

    for c in range(classes):
        #  calculate loss and compute gradient w.r.t. the input of the current class
        y = torch.ones(B, device="cuda", dtype=torch.long) * c
        loss = F.cross_entropy(logits, y)
        grad = torch.autograd.grad(loss, pre_ultimate_output, retain_graph=True)[0]

        #  take sign of gradient as in the original paper
        if sign:
            grad = torch.sign(grad)
        deltas.append(grad.detach().clone())

    deltas = torch.stack(deltas, dim=0)

    #  compute cosine similarity matrices
    deltas = deltas.view(classes, B, -1)
    norm = torch.norm(deltas, p=2, dim=2, keepdim=True)
    if not scalar_product:
        deltas = deltas / norm

    deltas = deltas.transpose(0, 1)
    csm = torch.matmul(deltas, deltas.transpose(1, 2))

    #  division by zero can lead to NaNs
    if torch.isnan(csm).any():
        raise Exception("NaNs in CSM!")
    return csm