Diff of /utils/loss.py [000000] .. [190ca4]

Switch to unified view

a b/utils/loss.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
"""
3
Loss functions
4
"""
5
6
import torch
7
import torch.nn as nn
8
9
from utils.metrics import bbox_iou
10
from utils.torch_utils import de_parallel
11
12
13
def smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14
    # return positive, negative label smoothing BCE targets
15
    return 1.0 - 0.5 * eps, 0.5 * eps
16
17
18
class BCEBlurWithLogitsLoss(nn.Module):
19
    # BCEwithLogitLoss() with reduced missing label effects.
20
    def __init__(self, alpha=0.05):
21
        super().__init__()
22
        self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none')  # must be nn.BCEWithLogitsLoss()
23
        self.alpha = alpha
24
25
    def forward(self, pred, true):
26
        loss = self.loss_fcn(pred, true)
27
        pred = torch.sigmoid(pred)  # prob from logits
28
        dx = pred - true  # reduce only missing label effects
29
        # dx = (pred - true).abs()  # reduce missing label and false label effects
30
        alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31
        loss *= alpha_factor
32
        return loss.mean()
33
34
35
class FocalLoss(nn.Module):
36
    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37
    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38
        super().__init__()
39
        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()
40
        self.gamma = gamma
41
        self.alpha = alpha
42
        self.reduction = loss_fcn.reduction
43
        self.loss_fcn.reduction = 'none'  # required to apply FL to each element
44
45
    def forward(self, pred, true):
46
        loss = self.loss_fcn(pred, true)
47
        # p_t = torch.exp(-loss)
48
        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability
49
50
        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51
        pred_prob = torch.sigmoid(pred)  # prob from logits
52
        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53
        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54
        modulating_factor = (1.0 - p_t) ** self.gamma
55
        loss *= alpha_factor * modulating_factor
56
57
        if self.reduction == 'mean':
58
            return loss.mean()
59
        elif self.reduction == 'sum':
60
            return loss.sum()
61
        else:  # 'none'
62
            return loss
63
64
65
class QFocalLoss(nn.Module):
66
    # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67
    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68
        super().__init__()
69
        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()
70
        self.gamma = gamma
71
        self.alpha = alpha
72
        self.reduction = loss_fcn.reduction
73
        self.loss_fcn.reduction = 'none'  # required to apply FL to each element
74
75
    def forward(self, pred, true):
76
        loss = self.loss_fcn(pred, true)
77
78
        pred_prob = torch.sigmoid(pred)  # prob from logits
79
        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80
        modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81
        loss *= alpha_factor * modulating_factor
82
83
        if self.reduction == 'mean':
84
            return loss.mean()
85
        elif self.reduction == 'sum':
86
            return loss.sum()
87
        else:  # 'none'
88
            return loss
89
90
91
class ComputeLoss:
92
    sort_obj_iou = False
93
94
    # Compute losses
95
    def __init__(self, model, autobalance=False):
96
        device = next(model.parameters()).device  # get model device
97
        h = model.hyp  # hyperparameters
98
99
        # Define criteria
100
        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
101
        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102
103
        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104
        self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0))  # positive, negative BCE targets
105
106
        # Focal loss
107
        g = h['fl_gamma']  # focal loss gamma
108
        if g > 0:
109
            BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110
111
        m = de_parallel(model).model[-1]  # Detect() module
112
        self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7
113
        self.ssi = list(m.stride).index(16) if autobalance else 0  # stride 16 index
114
        self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
115
        self.na = m.na  # number of anchors
116
        self.nc = m.nc  # number of classes
117
        self.nl = m.nl  # number of layers
118
        self.anchors = m.anchors
119
        self.device = device
120
121
    def __call__(self, p, targets):  # predictions, targets
122
        lcls = torch.zeros(1, device=self.device)  # class loss
123
        lbox = torch.zeros(1, device=self.device)  # box loss
124
        lobj = torch.zeros(1, device=self.device)  # object loss
125
        tcls, tbox, indices, anchors = self.build_targets(p, targets)  # targets
126
127
        # Losses
128
        for i, pi in enumerate(p):  # layer index, layer predictions
129
            b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx
130
            tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device)  # target obj
131
132
            n = b.shape[0]  # number of targets
133
            if n:
134
                # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1)  # faster, requires torch 1.8.0
135
                pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1)  # target-subset of predictions
136
137
                # Regression
138
                pxy = pxy.sigmoid() * 2 - 0.5
139
                pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
140
                pbox = torch.cat((pxy, pwh), 1)  # predicted box
141
                iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze()  # iou(prediction, target)
142
                lbox += (1.0 - iou).mean()  # iou loss
143
144
                # Objectness
145
                iou = iou.detach().clamp(0).type(tobj.dtype)
146
                if self.sort_obj_iou:
147
                    j = iou.argsort()
148
                    b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
149
                if self.gr < 1:
150
                    iou = (1.0 - self.gr) + self.gr * iou
151
                tobj[b, a, gj, gi] = iou  # iou ratio
152
153
                # Classification
154
                if self.nc > 1:  # cls loss (only if multiple classes)
155
                    t = torch.full_like(pcls, self.cn, device=self.device)  # targets
156
                    t[range(n), tcls[i]] = self.cp
157
                    lcls += self.BCEcls(pcls, t)  # BCE
158
159
                # Append targets to text file
160
                # with open('targets.txt', 'a') as file:
161
                #     [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
162
163
            obji = self.BCEobj(pi[..., 4], tobj)
164
            lobj += obji * self.balance[i]  # obj loss
165
            if self.autobalance:
166
                self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
167
168
        if self.autobalance:
169
            self.balance = [x / self.balance[self.ssi] for x in self.balance]
170
        lbox *= self.hyp['box']
171
        lobj *= self.hyp['obj']
172
        lcls *= self.hyp['cls']
173
        bs = tobj.shape[0]  # batch size
174
175
        return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
176
177
    def build_targets(self, p, targets):
178
        # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
179
        na, nt = self.na, targets.shape[0]  # number of anchors, targets
180
        tcls, tbox, indices, anch = [], [], [], []
181
        gain = torch.ones(7, device=self.device)  # normalized to gridspace gain #
182
        ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)
183
        targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2)  # append anchor indices
184
185
        g = 0.5  # bias
186
        off = torch.tensor(
187
            [
188
                [0, 0],
189
                [1, 0],
190
                [0, 1],
191
                [-1, 0],
192
                [0, -1],  # j,k,l,m
193
                # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm
194
            ],
195
            device=self.device).float() * g  # offsets
196
197
        for i in range(self.nl):
198
            anchors, shape = self.anchors[i], p[i].shape
199
            gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]]  # xyxy gain
200
201
            # Match targets to anchors
202
            t = targets * gain  # shape(3,n,7)
203
            if nt:
204
                # Matches
205
                r = t[..., 4:6] / anchors[:, None]  # wh ratio
206
                j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t']  # compare
207
                # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
208
                t = t[j]  # filter
209
210
                # Offsets
211
                gxy = t[:, 2:4]  # grid xy
212
                gxi = gain[[2, 3]] - gxy  # inverse
213
                j, k = ((gxy % 1 < g) & (gxy > 1)).T
214
                l, m = ((gxi % 1 < g) & (gxi > 1)).T
215
                j = torch.stack((torch.ones_like(j), j, k, l, m))
216
                t = t.repeat((5, 1, 1))[j]
217
                offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
218
            else:
219
                t = targets[0]
220
                offsets = 0
221
222
            # Define
223
            bc, gxy, gwh, a = t.chunk(4, 1)  # (image, class), grid xy, grid wh, anchors
224
            a, (b, c) = a.long().view(-1), bc.long().T  # anchors, image, class
225
            gij = (gxy - offsets).long()
226
            gi, gj = gij.T  # grid indices
227
228
            # Append
229
            indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1)))  # image, anchor, grid
230
            tbox.append(torch.cat((gxy - gij, gwh), 1))  # box
231
            anch.append(anchors[a])  # anchors
232
            tcls.append(c)  # class
233
234
        return tcls, tbox, indices, anch