a b/yolov5/utils/loss.py
1
# YOLOv5 🚀 by Ultralytics, GPL-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 is_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
    # Compute losses
93
    def __init__(self, model, autobalance=False):
94
        self.sort_obj_iou = False
95
        device = next(model.parameters()).device  # get model device
96
        h = model.hyp  # hyperparameters
97
98
        # Define criteria
99
        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
100
        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
101
102
        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
103
        self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0))  # positive, negative BCE targets
104
105
        # Focal loss
106
        g = h['fl_gamma']  # focal loss gamma
107
        if g > 0:
108
            BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
109
110
        det = model.module.model[-1] if is_parallel(model) else model.model[-1]  # Detect() module
111
        self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7
112
        self.ssi = list(det.stride).index(16) if autobalance else 0  # stride 16 index
113
        self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
114
        for k in 'na', 'nc', 'nl', 'anchors':
115
            setattr(self, k, getattr(det, k))
116
117
    def __call__(self, p, targets):  # predictions, targets, model
118
        device = targets.device
119
        lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
120
        tcls, tbox, indices, anchors = self.build_targets(p, targets)  # targets
121
122
        # Losses
123
        for i, pi in enumerate(p):  # layer index, layer predictions
124
            b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx
125
            tobj = torch.zeros_like(pi[..., 0], device=device)  # target obj
126
127
            n = b.shape[0]  # number of targets
128
            if n:
129
                ps = pi[b, a, gj, gi]  # prediction subset corresponding to targets
130
131
                # Regression
132
                pxy = ps[:, :2].sigmoid() * 2 - 0.5
133
                pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
134
                pbox = torch.cat((pxy, pwh), 1)  # predicted box
135
                iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)  # iou(prediction, target)
136
                lbox += (1.0 - iou).mean()  # iou loss
137
138
                # Objectness
139
                score_iou = iou.detach().clamp(0).type(tobj.dtype)
140
                if self.sort_obj_iou:
141
                    sort_id = torch.argsort(score_iou)
142
                    b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id]
143
                tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou  # iou ratio
144
145
                # Classification
146
                if self.nc > 1:  # cls loss (only if multiple classes)
147
                    t = torch.full_like(ps[:, 5:], self.cn, device=device)  # targets
148
                    t[range(n), tcls[i]] = self.cp
149
                    lcls += self.BCEcls(ps[:, 5:], t)  # BCE
150
151
                # Append targets to text file
152
                # with open('targets.txt', 'a') as file:
153
                #     [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
154
155
            obji = self.BCEobj(pi[..., 4], tobj)
156
            lobj += obji * self.balance[i]  # obj loss
157
            if self.autobalance:
158
                self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
159
160
        if self.autobalance:
161
            self.balance = [x / self.balance[self.ssi] for x in self.balance]
162
        lbox *= self.hyp['box']
163
        lobj *= self.hyp['obj']
164
        lcls *= self.hyp['cls']
165
        bs = tobj.shape[0]  # batch size
166
167
        return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
168
169
    def build_targets(self, p, targets):
170
        # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
171
        na, nt = self.na, targets.shape[0]  # number of anchors, targets
172
        tcls, tbox, indices, anch = [], [], [], []
173
        gain = torch.ones(7, device=targets.device)  # normalized to gridspace gain
174
        ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)
175
        targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)  # append anchor indices
176
177
        g = 0.5  # bias
178
        off = torch.tensor([[0, 0],
179
                            [1, 0], [0, 1], [-1, 0], [0, -1],  # j,k,l,m
180
                            # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm
181
                            ], device=targets.device).float() * g  # offsets
182
183
        for i in range(self.nl):
184
            anchors = self.anchors[i]
185
            gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain
186
187
            # Match targets to anchors
188
            t = targets * gain
189
            if nt:
190
                # Matches
191
                r = t[:, :, 4:6] / anchors[:, None]  # wh ratio
192
                j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t']  # compare
193
                # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
194
                t = t[j]  # filter
195
196
                # Offsets
197
                gxy = t[:, 2:4]  # grid xy
198
                gxi = gain[[2, 3]] - gxy  # inverse
199
                j, k = ((gxy % 1 < g) & (gxy > 1)).T
200
                l, m = ((gxi % 1 < g) & (gxi > 1)).T
201
                j = torch.stack((torch.ones_like(j), j, k, l, m))
202
                t = t.repeat((5, 1, 1))[j]
203
                offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
204
            else:
205
                t = targets[0]
206
                offsets = 0
207
208
            # Define
209
            b, c = t[:, :2].long().T  # image, class
210
            gxy = t[:, 2:4]  # grid xy
211
            gwh = t[:, 4:6]  # grid wh
212
            gij = (gxy - offsets).long()
213
            gi, gj = gij.T  # grid xy indices
214
215
            # Append
216
            a = t[:, 6].long()  # anchor indices
217
            indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))  # image, anchor, grid indices
218
            tbox.append(torch.cat((gxy - gij, gwh), 1))  # box
219
            anch.append(anchors[a])  # anchors
220
            tcls.append(c)  # class
221
222
        return tcls, tbox, indices, anch