yolov3_loss_op.h 18.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
   http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#pragma once
#include <algorithm>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
16
#include "paddle/fluid/operators/math/math_function.h"
17 18 19 20 21 22 23 24 25 26 27 28 29

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
template <typename T, size_t D, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;

template <typename T>
D
dengkaipeng 已提交
30 31
static inline bool LessEqualZero(T x) {
  return x < 1e-6;
32 33
}

34
template <typename T>
35
static T SigmoidCrossEntropy(T x, T label) {
36 37 38
  return (x > 0 ? x : 0.0) - x * label + std::log(1.0 + std::exp(-std::abs(x)));
}

D
dengkaipeng 已提交
39
template <typename T>
40 41
static T L1Loss(T x, T y) {
  return std::abs(y - x);
D
dengkaipeng 已提交
42 43
}

44
template <typename T>
45
static T SigmoidCrossEntropyGrad(T x, T label) {
46 47 48
  return 1.0 / (1.0 + std::exp(-x)) - label;
}

D
dengkaipeng 已提交
49
template <typename T>
50 51
static T L1LossGrad(T x, T y) {
  return x > y ? 1.0 : -1.0;
D
dengkaipeng 已提交
52 53
}

D
dengkaipeng 已提交
54 55
static int GetMaskIndex(std::vector<int> mask, int val) {
  for (size_t i = 0; i < mask.size(); i++) {
56 57 58 59 60 61 62 63 64
    if (mask[i] == val) {
      return i;
    }
  }
  return -1;
}

template <typename T>
struct Box {
65
  T x, y, w, h;
66 67 68 69 70 71 72 73
};

template <typename T>
static inline T sigmoid(T x) {
  return 1.0 / (1.0 + std::exp(-x));
}

template <typename T>
D
dengkaipeng 已提交
74 75 76
static inline Box<T> GetYoloBox(const T* x, std::vector<int> anchors, int i,
                                int j, int an_idx, int grid_size,
                                int input_size, int index, int stride) {
77 78 79 80 81 82 83 84 85
  Box<T> b;
  b.x = (i + sigmoid<T>(x[index])) / grid_size;
  b.y = (j + sigmoid<T>(x[index + stride])) / grid_size;
  b.w = std::exp(x[index + 2 * stride]) * anchors[2 * an_idx] / input_size;
  b.h = std::exp(x[index + 3 * stride]) * anchors[2 * an_idx + 1] / input_size;
  return b;
}

template <typename T>
D
dengkaipeng 已提交
86
static inline Box<T> GetGtBox(const T* gt, int batch, int max_boxes, int idx) {
87 88 89 90 91 92 93 94 95
  Box<T> b;
  b.x = gt[(batch * max_boxes + idx) * 4];
  b.y = gt[(batch * max_boxes + idx) * 4 + 1];
  b.w = gt[(batch * max_boxes + idx) * 4 + 2];
  b.h = gt[(batch * max_boxes + idx) * 4 + 3];
  return b;
}

template <typename T>
D
dengkaipeng 已提交
96
static inline T BoxOverlap(T c1, T w1, T c2, T w2) {
97 98 99 100 101 102 103 104 105 106
  T l1 = c1 - w1 / 2.0;
  T l2 = c2 - w2 / 2.0;
  T left = l1 > l2 ? l1 : l2;
  T r1 = c1 + w1 / 2.0;
  T r2 = c2 + w2 / 2.0;
  T right = r1 < r2 ? r1 : r2;
  return right - left;
}

template <typename T>
D
dengkaipeng 已提交
107 108 109
static inline T CalcBoxIoU(Box<T> b1, Box<T> b2) {
  T w = BoxOverlap(b1.x, b1.w, b2.x, b2.w);
  T h = BoxOverlap(b1.y, b1.h, b2.y, b2.h);
110 111 112 113 114
  T inter_area = (w < 0 || h < 0) ? 0.0 : w * h;
  T union_area = b1.w * b1.h + b2.w * b2.h - inter_area;
  return inter_area / union_area;
}

D
dengkaipeng 已提交
115 116
static inline int GetEntryIndex(int batch, int an_idx, int hw_idx, int an_num,
                                int an_stride, int stride, int entry) {
117 118 119 120 121 122 123
  return (batch * an_num + an_idx) * an_stride + entry * stride + hw_idx;
}

template <typename T>
static void CalcBoxLocationLoss(T* loss, const T* input, Box<T> gt,
                                std::vector<int> anchors, int an_idx,
                                int box_idx, int gi, int gj, int grid_size,
124
                                int input_size, int stride, T score) {
125 126 127 128 129
  T tx = gt.x * grid_size - gi;
  T ty = gt.y * grid_size - gj;
  T tw = std::log(gt.w * input_size / anchors[2 * an_idx]);
  T th = std::log(gt.h * input_size / anchors[2 * an_idx + 1]);

130
  T scale = (2.0 - gt.w * gt.h) * score;
131 132
  loss[0] += SigmoidCrossEntropy<T>(input[box_idx], tx) * scale;
  loss[0] += SigmoidCrossEntropy<T>(input[box_idx + stride], ty) * scale;
133 134
  loss[0] += L1Loss<T>(input[box_idx + 2 * stride], tw) * scale;
  loss[0] += L1Loss<T>(input[box_idx + 3 * stride], th) * scale;
135 136 137 138 139 140
}

template <typename T>
static void CalcBoxLocationLossGrad(T* input_grad, const T loss, const T* input,
                                    Box<T> gt, std::vector<int> anchors,
                                    int an_idx, int box_idx, int gi, int gj,
141 142
                                    int grid_size, int input_size, int stride,
                                    T score) {
143 144 145 146 147
  T tx = gt.x * grid_size - gi;
  T ty = gt.y * grid_size - gj;
  T tw = std::log(gt.w * input_size / anchors[2 * an_idx]);
  T th = std::log(gt.h * input_size / anchors[2 * an_idx + 1]);

148
  T scale = (2.0 - gt.w * gt.h) * score;
149 150
  input_grad[box_idx] =
      SigmoidCrossEntropyGrad<T>(input[box_idx], tx) * scale * loss;
151
  input_grad[box_idx + stride] =
152
      SigmoidCrossEntropyGrad<T>(input[box_idx + stride], ty) * scale * loss;
153
  input_grad[box_idx + 2 * stride] =
154
      L1LossGrad<T>(input[box_idx + 2 * stride], tw) * scale * loss;
155
  input_grad[box_idx + 3 * stride] =
156
      L1LossGrad<T>(input[box_idx + 3 * stride], th) * scale * loss;
157 158 159 160
}

template <typename T>
static inline void CalcLabelLoss(T* loss, const T* input, const int index,
D
dengkaipeng 已提交
161
                                 const int label, const int class_num,
162 163
                                 const int stride, const T pos, const T neg,
                                 T score) {
D
dengkaipeng 已提交
164 165
  for (int i = 0; i < class_num; i++) {
    T pred = input[index + i * stride];
166
    loss[0] += SigmoidCrossEntropy<T>(pred, (i == label) ? pos : neg) * score;
167 168 169 170 171 172
  }
}

template <typename T>
static inline void CalcLabelLossGrad(T* input_grad, const T loss,
                                     const T* input, const int index,
D
dengkaipeng 已提交
173
                                     const int label, const int class_num,
174 175
                                     const int stride, const T pos, const T neg,
                                     T score) {
D
dengkaipeng 已提交
176 177 178
  for (int i = 0; i < class_num; i++) {
    T pred = input[index + i * stride];
    input_grad[index + i * stride] =
179 180
        SigmoidCrossEntropyGrad<T>(pred, (i == label) ? pos : neg) * score *
        loss;
181 182 183 184
  }
}

template <typename T>
D
dengkaipeng 已提交
185
static inline void CalcObjnessLoss(T* loss, const T* input, const T* objness,
186 187 188 189 190 191 192
                                   const int n, const int an_num, const int h,
                                   const int w, const int stride,
                                   const int an_stride) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < an_num; j++) {
      for (int k = 0; k < h; k++) {
        for (int l = 0; l < w; l++) {
D
dengkaipeng 已提交
193
          T obj = objness[k * w + l];
D
dengkaipeng 已提交
194
          if (obj > 1e-5) {
195 196
            // positive sample: obj = mixup score
            loss[i] += SigmoidCrossEntropy<T>(input[k * w + l], 1.0) * obj;
D
dengkaipeng 已提交
197 198
          } else if (obj > -0.5) {
            // negetive sample: obj = 0
199
            loss[i] += SigmoidCrossEntropy<T>(input[k * w + l], 0.0);
200 201 202 203 204 205 206 207 208 209 210
          }
        }
      }
      objness += stride;
      input += an_stride;
    }
  }
}

template <typename T>
static inline void CalcObjnessLossGrad(T* input_grad, const T* loss,
D
dengkaipeng 已提交
211
                                       const T* input, const T* objness,
212 213 214 215 216 217 218
                                       const int n, const int an_num,
                                       const int h, const int w,
                                       const int stride, const int an_stride) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < an_num; j++) {
      for (int k = 0; k < h; k++) {
        for (int l = 0; l < w; l++) {
D
dengkaipeng 已提交
219
          T obj = objness[k * w + l];
D
dengkaipeng 已提交
220
          if (obj > 1e-5) {
221
            input_grad[k * w + l] =
222 223
                SigmoidCrossEntropyGrad<T>(input[k * w + l], 1.0) * obj *
                loss[i];
D
dengkaipeng 已提交
224
          } else if (obj > -0.5) {
225 226
            input_grad[k * w + l] =
                SigmoidCrossEntropyGrad<T>(input[k * w + l], 0.0) * loss[i];
227 228 229 230 231 232 233 234 235 236
          }
        }
      }
      objness += stride;
      input += an_stride;
      input_grad += an_stride;
    }
  }
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
template <typename T>
static void inline GtValid(bool* valid, const T* gtbox, const int n,
                           const int b) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < b; j++) {
      if (LessEqualZero(gtbox[j * 4 + 2]) || LessEqualZero(gtbox[j * 4 + 3])) {
        valid[j] = false;
      } else {
        valid[j] = true;
      }
    }
    valid += b;
    gtbox += b * 4;
  }
}

253
template <typename T>
254 255 256 257
class Yolov3LossKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* input = ctx.Input<Tensor>("X");
D
dengkaipeng 已提交
258 259
    auto* gt_box = ctx.Input<Tensor>("GTBox");
    auto* gt_label = ctx.Input<Tensor>("GTLabel");
260
    auto* gt_score = ctx.Input<Tensor>("GTScore");
D
dengkaipeng 已提交
261
    auto* loss = ctx.Output<Tensor>("Loss");
262 263
    auto* objness_mask = ctx.Output<Tensor>("ObjectnessMask");
    auto* gt_match_mask = ctx.Output<Tensor>("GTMatchMask");
264
    auto anchors = ctx.Attr<std::vector<int>>("anchors");
265
    auto anchor_mask = ctx.Attr<std::vector<int>>("anchor_mask");
266 267
    int class_num = ctx.Attr<int>("class_num");
    float ignore_thresh = ctx.Attr<float>("ignore_thresh");
268
    int downsample_ratio = ctx.Attr<int>("downsample_ratio");
269
    bool use_label_smooth = ctx.Attr<bool>("use_label_smooth");
270 271 272 273 274

    const int n = input->dims()[0];
    const int h = input->dims()[2];
    const int w = input->dims()[3];
    const int an_num = anchors.size() / 2;
275 276
    const int mask_num = anchor_mask.size();
    const int b = gt_box->dims()[1];
277
    int input_size = downsample_ratio * h;
278

279 280 281
    const int stride = h * w;
    const int an_stride = (class_num + 5) * stride;

282 283 284 285 286 287 288
    T label_pos = 1.0;
    T label_neg = 0.0;
    if (use_label_smooth) {
      label_pos = 1.0 - 1.0 / static_cast<T>(class_num);
      label_neg = 1.0 / static_cast<T>(class_num);
    }

289 290 291
    const T* input_data = input->data<T>();
    const T* gt_box_data = gt_box->data<T>();
    const int* gt_label_data = gt_label->data<int>();
292
    T* loss_data = loss->mutable_data<T>({n}, ctx.GetPlace());
D
dengkaipeng 已提交
293
    memset(loss_data, 0, loss->numel() * sizeof(T));
D
dengkaipeng 已提交
294 295 296
    T* obj_mask_data =
        objness_mask->mutable_data<T>({n, mask_num, h, w}, ctx.GetPlace());
    memset(obj_mask_data, 0, objness_mask->numel() * sizeof(T));
297 298
    int* gt_match_mask_data =
        gt_match_mask->mutable_data<int>({n, b}, ctx.GetPlace());
299

300 301
    const T* gt_score_data;
    if (!gt_score) {
D
dengkaipeng 已提交
302 303
      Tensor gtscore;
      gtscore.mutable_data<T>({n, b}, ctx.GetPlace());
304
      math::SetConstant<platform::CPUDeviceContext, T>()(
D
dengkaipeng 已提交
305
          ctx.template device_context<platform::CPUDeviceContext>(), &gtscore,
306
          static_cast<T>(1.0));
D
dengkaipeng 已提交
307 308
      gt_score = &gtscore;
      gt_score_data = gtscore.data<T>();
309 310 311 312
    } else {
      gt_score_data = gt_score->data<T>();
    }

313 314 315 316 317 318
    // calc valid gt box mask, avoid calc duplicately in following code
    Tensor gt_valid_mask;
    bool* gt_valid_mask_data =
        gt_valid_mask.mutable_data<bool>({n, b}, ctx.GetPlace());
    GtValid<T>(gt_valid_mask_data, gt_box_data, n, b);

319 320 321 322
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < mask_num; j++) {
        for (int k = 0; k < h; k++) {
          for (int l = 0; l < w; l++) {
323 324
            // each predict box find a best match gt box, if overlap is bigger
            // then ignore_thresh, ignore the objectness loss.
325
            int box_idx =
D
dengkaipeng 已提交
326 327 328
                GetEntryIndex(i, j, k * w + l, mask_num, an_stride, stride, 0);
            Box<T> pred = GetYoloBox(input_data, anchors, l, k, anchor_mask[j],
                                     h, input_size, box_idx, stride);
329 330
            T best_iou = 0;
            for (int t = 0; t < b; t++) {
331
              if (!gt_valid_mask_data[i * b + t]) {
332 333
                continue;
              }
334
              Box<T> gt = GetGtBox(gt_box_data, i, b, t);
D
dengkaipeng 已提交
335
              T iou = CalcBoxIoU(pred, gt);
336 337 338 339 340
              if (iou > best_iou) {
                best_iou = iou;
              }
            }

341
            // If best IoU is bigger then ignore_thresh,
342
            // ignore the objectness loss.
343 344
            if (best_iou > ignore_thresh) {
              int obj_idx = (i * mask_num + j) * stride + k * w + l;
D
dengkaipeng 已提交
345
              obj_mask_data[obj_idx] = static_cast<T>(-1);
346
            }
347 348 349
            // all losses should be calculated if best IoU
            // is bigger then truth thresh, but currently,
            // truth thresh is an unreachable value as 1.0.
350 351 352 353
          }
        }
      }
      for (int t = 0; t < b; t++) {
354
        if (!gt_valid_mask_data[i * b + t]) {
355
          gt_match_mask_data[i * b + t] = -1;
356 357
          continue;
        }
358
        Box<T> gt = GetGtBox(gt_box_data, i, b, t);
359 360 361 362 363 364 365
        int gi = static_cast<int>(gt.x * w);
        int gj = static_cast<int>(gt.y * h);
        Box<T> gt_shift = gt;
        gt_shift.x = 0.0;
        gt_shift.y = 0.0;
        T best_iou = 0.0;
        int best_n = 0;
366 367 368
        // each gt box find a best match anchor box as positive sample,
        // for positive sample, all losses should be calculated, and for
        // other samples, only objectness loss is required.
369 370 371 372 373 374
        for (int an_idx = 0; an_idx < an_num; an_idx++) {
          Box<T> an_box;
          an_box.x = 0.0;
          an_box.y = 0.0;
          an_box.w = anchors[2 * an_idx] / static_cast<T>(input_size);
          an_box.h = anchors[2 * an_idx + 1] / static_cast<T>(input_size);
D
dengkaipeng 已提交
375
          float iou = CalcBoxIoU<T>(an_box, gt_shift);
376 377 378 379 380 381
          if (iou > best_iou) {
            best_iou = iou;
            best_n = an_idx;
          }
        }

D
dengkaipeng 已提交
382
        int mask_idx = GetMaskIndex(anchor_mask, best_n);
383
        gt_match_mask_data[i * b + t] = mask_idx;
384
        if (mask_idx >= 0) {
385
          T score = gt_score_data[i * b + t];
D
dengkaipeng 已提交
386 387
          int box_idx = GetEntryIndex(i, mask_idx, gj * w + gi, mask_num,
                                      an_stride, stride, 0);
388
          CalcBoxLocationLoss<T>(loss_data + i, input_data, gt, anchors, best_n,
389
                                 box_idx, gi, gj, h, input_size, stride, score);
390 391

          int obj_idx = (i * mask_num + mask_idx) * stride + gj * w + gi;
392
          obj_mask_data[obj_idx] = score;
393 394

          int label = gt_label_data[i * b + t];
D
dengkaipeng 已提交
395 396
          int label_idx = GetEntryIndex(i, mask_idx, gj * w + gi, mask_num,
                                        an_stride, stride, 5);
D
dengkaipeng 已提交
397
          CalcLabelLoss<T>(loss_data + i, input_data, label_idx, label,
398
                           class_num, stride, label_pos, label_neg, score);
399 400 401 402
        }
      }
    }

403
    CalcObjnessLoss<T>(loss_data, input_data + 4 * stride, obj_mask_data, n,
404
                       mask_num, h, w, stride, an_stride);
405 406 407
  }
};

408
template <typename T>
409 410 411
class Yolov3LossGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
412
    auto* input = ctx.Input<Tensor>("X");
D
dengkaipeng 已提交
413 414
    auto* gt_box = ctx.Input<Tensor>("GTBox");
    auto* gt_label = ctx.Input<Tensor>("GTLabel");
415
    auto* gt_score = ctx.Input<Tensor>("GTScore");
416 417
    auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* loss_grad = ctx.Input<Tensor>(framework::GradVarName("Loss"));
418 419
    auto* objness_mask = ctx.Input<Tensor>("ObjectnessMask");
    auto* gt_match_mask = ctx.Input<Tensor>("GTMatchMask");
420
    auto anchors = ctx.Attr<std::vector<int>>("anchors");
421
    auto anchor_mask = ctx.Attr<std::vector<int>>("anchor_mask");
422
    int class_num = ctx.Attr<int>("class_num");
423
    int downsample_ratio = ctx.Attr<int>("downsample_ratio");
424
    bool use_label_smooth = ctx.Attr<bool>("use_label_smooth");
425

426 427 428 429
    const int n = input_grad->dims()[0];
    const int c = input_grad->dims()[1];
    const int h = input_grad->dims()[2];
    const int w = input_grad->dims()[3];
430
    const int mask_num = anchor_mask.size();
431
    const int b = gt_match_mask->dims()[1];
432
    int input_size = downsample_ratio * h;
433

434 435 436
    const int stride = h * w;
    const int an_stride = (class_num + 5) * stride;

437 438 439 440 441 442 443
    T label_pos = 1.0;
    T label_neg = 0.0;
    if (use_label_smooth) {
      label_pos = 1.0 - 1.0 / static_cast<T>(class_num);
      label_neg = 1.0 / static_cast<T>(class_num);
    }

444 445 446 447
    const T* input_data = input->data<T>();
    const T* gt_box_data = gt_box->data<T>();
    const int* gt_label_data = gt_label->data<int>();
    const T* loss_grad_data = loss_grad->data<T>();
D
dengkaipeng 已提交
448
    const T* obj_mask_data = objness_mask->data<T>();
449
    const int* gt_match_mask_data = gt_match_mask->data<int>();
450 451
    T* input_grad_data =
        input_grad->mutable_data<T>({n, c, h, w}, ctx.GetPlace());
452 453
    memset(input_grad_data, 0, input_grad->numel() * sizeof(T));

454 455
    const T* gt_score_data;
    if (!gt_score) {
D
dengkaipeng 已提交
456 457
      Tensor gtscore;
      gtscore.mutable_data<T>({n, b}, ctx.GetPlace());
458
      math::SetConstant<platform::CPUDeviceContext, T>()(
D
dengkaipeng 已提交
459
          ctx.template device_context<platform::CPUDeviceContext>(), &gtscore,
460
          static_cast<T>(1.0));
D
dengkaipeng 已提交
461 462
      gt_score = &gtscore;
      gt_score_data = gtscore.data<T>();
463 464 465 466
    } else {
      gt_score_data = gt_score->data<T>();
    }

467 468
    for (int i = 0; i < n; i++) {
      for (int t = 0; t < b; t++) {
469
        int mask_idx = gt_match_mask_data[i * b + t];
470
        if (mask_idx >= 0) {
471
          T score = gt_score_data[i * b + t];
D
dengkaipeng 已提交
472 473 474 475
          Box<T> gt = GetGtBox(gt_box_data, i, b, t);
          int gi = static_cast<int>(gt.x * w);
          int gj = static_cast<int>(gt.y * h);

D
dengkaipeng 已提交
476 477
          int box_idx = GetEntryIndex(i, mask_idx, gj * w + gi, mask_num,
                                      an_stride, stride, 0);
478 479 480 481
          CalcBoxLocationLossGrad<T>(input_grad_data, loss_grad_data[i],
                                     input_data, gt, anchors,
                                     anchor_mask[mask_idx], box_idx, gi, gj, h,
                                     input_size, stride, score);
482 483

          int label = gt_label_data[i * b + t];
D
dengkaipeng 已提交
484 485
          int label_idx = GetEntryIndex(i, mask_idx, gj * w + gi, mask_num,
                                        an_stride, stride, 5);
486
          CalcLabelLossGrad<T>(input_grad_data, loss_grad_data[i], input_data,
487 488
                               label_idx, label, class_num, stride, label_pos,
                               label_neg, score);
489 490 491 492 493
        }
      }
    }

    CalcObjnessLossGrad<T>(input_grad_data + 4 * stride, loss_grad_data,
494
                           input_data + 4 * stride, obj_mask_data, n, mask_num,
495
                           h, w, stride, an_stride);
496 497 498 499 500
  }
};

}  // namespace operators
}  // namespace paddle