CSM.py 6.64 KB
Newer Older
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
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
import torch
import torch.nn.functional as F


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

    Parameters
    ---------
    model: torch model
    imgs_and_preds: 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:
    '''

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

    for tup in imgs_and_preds:
        img, pred, frame, x1, y1, x2, y2 = tup
        if not img.requires_grad:
            img.requires_grad_()
        logit = pred[5:]
        imgs.append(img)

        # rescale network output to avoid gradient obfuscation
        if rescale:
            logit = logit / torch.max(torch.abs(logit)) * 10

        classes = len(logit)

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

            #  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

        try:
            deltas = torch.max(deltas, dim=-3).values  # take only the maximum value of all channels to compute the
            deltas = deltas.view(classes, 1, -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))
        except Exception as e:
            print("error")
            raise e

        #  division by zero can lead to NaNs
        if torch.isnan(csm).any():
            # raise Exception("NaNs in CSM!")
            print("NaNs in csm")
        else:
            print(f'{deltas.mean()}')
            csms.append(csm)
    return imgs, csms


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