CostLayer.cpp 21.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yu Yang 已提交
15
#include "CostLayer.h"
Z
zhangjinchao01 已提交
16 17
#include <algorithm>
#include <cmath>
Y
Yu Yang 已提交
18 19
#include <memory>
#include "paddle/utils/Logging.h"
Z
zhangjinchao01 已提交
20 21 22 23 24 25 26 27

#include "paddle/math/SparseMatrix.h"

namespace paddle {

bool CostLayer::init(const LayerMap& layerMap,
                     const ParameterMap& parameterMap) {
  bool ret = Layer::init(layerMap, parameterMap);
28
  coeff_ = config_.coeff();
Z
zhangjinchao01 已提交
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
  if (!ret) return ret;
  CHECK_GE(inputLayers_.size(), 2UL);
  CHECK_LE(inputLayers_.size(), 3UL);
  if (inputLayers_.size() == 3) {
    weightLayer_ = inputLayers_[2];
  }
  return true;
}

void CostLayer::forward(PassType passType) {
  Layer::forward(passType);

  /* malloc memory for the output_ if necessary */
  int batchSize = getInputValue(*getOutputLayer())->getHeight();
  int size = 1;
  resetOutput(batchSize, size);

  const MatrixPtr& output = getInputValue(*getOutputLayer());
  Argument label = getInput(*getLabelLayer());

  /* get the cost value for each sample*/
  forwardImp(*output, label, *getOutputValue());
  if (weightLayer_) {
    const MatrixPtr& weight = getInputValue(*weightLayer_);
    getOutputValue()->dotMul(*getOutputValue(), *weight);
  }
}

void CostLayer::backward(const UpdateCallback& callback) {
  (void)callback;

  const Argument& output = getInput(*getOutputLayer());
  Argument label = getInput(*getLabelLayer());

  bool support = true;
  if (weightLayer_) {
    support = output.grad->getAbsSum() == 0;
  }

  backwardImp(*output.value, label, *output.grad);

  if (weightLayer_) {
    CHECK(support) << "Weighted cost layer '" << getName()
                   << "' must be the last layer "
                      "connected to the output layer '"
                   << getOutputLayer()->getName() << "'";
    output.grad->rowScale(0, *output.grad, *getInputValue(*weightLayer_));
  }
  if (coeff_ != real(1.0f)) {
    output.grad->add(coeff_, 0);
  }
}

//
// class MultiClassCrossEntropy
//
bool MultiClassCrossEntropy::init(const LayerMap& layerMap,
                                  const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

90 91
void MultiClassCrossEntropy::forwardImp(Matrix& output,
                                        Argument& label,
Z
zhangjinchao01 已提交
92 93 94 95
                                        Matrix& target) {
  target.oneHotCrossEntropy(output, *label.ids);
}

96 97 98
void MultiClassCrossEntropy::backwardImp(Matrix& output,
                                         Argument& label,
                                         Matrix& outputG) {
Z
zhangjinchao01 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  outputG.oneHotCrossEntropyBp(output, *label.ids);
}

//
// class MultiClassCrossEntropyWithSelfNorm
//
REGISTER_LAYER(multi_class_cross_entropy_with_selfnorm,
               MultiClassCrossEntropyWithSelfNorm);

bool MultiClassCrossEntropyWithSelfNorm::init(
    const LayerMap& layerMap, const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

void MultiClassCrossEntropyWithSelfNorm::forwardImp(Matrix& output,
                                                    Argument& label,
                                                    Matrix& target) {
  Matrix::resizeOrCreate(sftMaxSum_, output.getHeight(), 1, false, useGpu_);
  output.rowSum(*sftMaxSum_);
H
hedaoyuan 已提交
118
  sftMaxSum_->log2();
Z
zhangjinchao01 已提交
119 120 121 122

  target.oneHotCrossEntropy(output, *label.ids);
  target.add(*sftMaxSum_);

H
hedaoyuan 已提交
123
  sftMaxSum_->square2();
Z
zhangjinchao01 已提交
124 125 126 127 128 129 130 131 132 133
  target.add(*sftMaxSum_, config_.softmax_selfnorm_alpha());
}

void MultiClassCrossEntropyWithSelfNorm::backwardImp(Matrix& output,
                                                     Argument& label,
                                                     Matrix& outputG) {
  Matrix::resizeOrCreate(sftMaxSum_, output.getHeight(), 1, false, useGpu_);
  output.rowSum(*sftMaxSum_);

  Matrix::resizeOrCreate(sumInv_, output.getHeight(), 1, false, useGpu_);
H
hedaoyuan 已提交
134
  sftMaxSum_->reciprocal2(*sumInv_);
Z
zhangjinchao01 已提交
135 136 137 138

  outputG.oneHotCrossEntropyBp(output, *label.ids);
  outputG.addColumnVector(*sumInv_);

H
hedaoyuan 已提交
139
  sftMaxSum_->log2();
Z
zhangjinchao01 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  sumInv_->dotMul(*sumInv_, *sftMaxSum_);
  sumInv_->mulScalar(2 * config_.softmax_selfnorm_alpha());

  outputG.addColumnVector(*sumInv_);
}

//
// class SoftBinaryClassCrossEntropy
//
REGISTER_LAYER(soft_binary_class_cross_entropy, SoftBinaryClassCrossEntropy);

bool SoftBinaryClassCrossEntropy::init(const LayerMap& layerMap,
                                       const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

156 157
void SoftBinaryClassCrossEntropy::forwardImp(Matrix& output,
                                             Argument& label,
Z
zhangjinchao01 已提交
158
                                             Matrix& target) {
159 160
  Matrix::resizeOrCreate(
      targetPerDim_, output.getHeight(), output.getWidth(), false, useGpu_);
Z
zhangjinchao01 已提交
161 162 163 164 165

  targetPerDim_->softCrossEntropy(output, *label.value);
  targetPerDim_->rowSum(target);
}

166 167 168
void SoftBinaryClassCrossEntropy::backwardImp(Matrix& output,
                                              Argument& label,
                                              Matrix& outputG) {
Z
zhangjinchao01 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
  outputG.softCrossEntropyBp(output, *label.value);
}

//
// class SumOfSquaresCostLayer
//

REGISTER_LAYER(square_error, SumOfSquaresCostLayer);

bool SumOfSquaresCostLayer::init(const LayerMap& layerMap,
                                 const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

183 184
void SumOfSquaresCostLayer::forwardImp(Matrix& output,
                                       Argument& label,
Z
zhangjinchao01 已提交
185 186 187 188
                                       Matrix& target) {
  target.sumOfSquares(output, *label.value);
}

189 190 191
void SumOfSquaresCostLayer::backwardImp(Matrix& output,
                                        Argument& label,
                                        Matrix& outputG) {
Z
zhangjinchao01 已提交
192 193 194
  outputG.sumOfSquaresBp(output, *label.value);
}

G
gaoyuan 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208
//
// class SmoothL1CostLayer
//

REGISTER_LAYER(smooth_l1, SmoothL1CostLayer);

bool SmoothL1CostLayer::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

void SmoothL1CostLayer::forwardImp(Matrix& output,
                                   Argument& label,
                                   Matrix& target) {
G
gaoyuan 已提交
209
  MatrixPtr targetCpu, outputCpu, labelCpu;
G
gaoyuan 已提交
210
  if (useGpu_) {
G
gaoyuan 已提交
211 212 213 214 215 216
    targetCpu =
        Matrix::create(target.getHeight(), target.getWidth(), false, false);
    outputCpu =
        Matrix::create(output.getHeight(), output.getWidth(), false, false);
    labelCpu = Matrix::create(
        label.value->getHeight(), label.value->getWidth(), false, false);
G
gaoyuan 已提交
217 218 219
    targetCpu->copyFrom(target);
    outputCpu->copyFrom(output);
    labelCpu->copyFrom(*label.value);
220
    targetCpu->smoothL1(*outputCpu, *labelCpu, 1.0);
G
gaoyuan 已提交
221 222
    target.copyFrom(*targetCpu);
  } else {
223
    target.smoothL1(output, *label.value, 1.0);
G
gaoyuan 已提交
224 225 226 227 228 229
  }
}

void SmoothL1CostLayer::backwardImp(Matrix& output,
                                    Argument& label,
                                    Matrix& outputG) {
G
gaoyuan 已提交
230
  MatrixPtr outputGCpu, outputCpu, labelCpu;
G
gaoyuan 已提交
231
  if (useGpu_) {
G
gaoyuan 已提交
232 233 234 235 236 237
    outputGCpu =
        Matrix::create(outputG.getHeight(), outputG.getWidth(), false, false);
    outputCpu =
        Matrix::create(output.getHeight(), output.getWidth(), false, false);
    labelCpu = Matrix::create(
        label.value->getHeight(), label.value->getWidth(), false, false);
G
gaoyuan 已提交
238 239 240
    outputGCpu->copyFrom(outputG);
    outputCpu->copyFrom(output);
    labelCpu->copyFrom(*label.value);
241
    outputGCpu->smoothL1Bp(*outputCpu, *labelCpu, 1.0);
G
gaoyuan 已提交
242 243
    outputG.copyFrom(*outputGCpu);
  } else {
244
    outputG.smoothL1Bp(output, *label.value, 1.0);
G
gaoyuan 已提交
245 246 247
  }
}

Z
zhangjinchao01 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
//
// class RankingCost
//
bool RankingCost::init(const LayerMap& layerMap,
                       const ParameterMap& parameterMap) {
  posPairCount_ = 0;
  negPairCount_ = 0;

  bool ret = Layer::init(layerMap, parameterMap);
  if (!ret) return ret;
  CHECK_GE(inputLayers_.size(), 3UL);
  CHECK_LE(inputLayers_.size(), 4UL);
  if (inputLayers_.size() == 4) {
    weightLayer_ = inputLayers_[3];
  }
  return true;
}

void RankingCost::forward(PassType passType) {
  Layer::forward(passType);

  /* malloc memory for the output_ if necessary */
  int batchSize = getInputValue(*getOutputLayer(0))->getHeight();
  int size = 1;
  resizeOutput(batchSize, size);
  Matrix::resizeOrCreate(margin_, batchSize, size, /* trans= */ false, useGpu_);
  MatrixPtr label = getInputValue(*getLabelLayer());
  if (!label) {
    // input label is not in value, try ids
    IVectorPtr idLabel = getInput(*getLabelLayer()).ids;
    CHECK(idLabel) << "label layer has neither value nor ids";
    CHECK_EQ((size_t)batchSize, idLabel->getSize());
280 281
    Matrix::resizeOrCreate(
        labelBuf_, batchSize, /*width*/ 1, /*trans*/ false, useGpu_);
Z
zhangjinchao01 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    labelBuf_->copyFrom(*idLabel);
    label = labelBuf_;
  }

  MatrixPtr output[] = {getInputValue(*getOutputLayer(0)),
                        getInputValue(*getOutputLayer(1))};
  MatrixPtr target = this->getOutputValue();
  margin_->sub(*output[0], *output[1]);

  // for validation
  size_t height = output[0]->getHeight();
  target->biggerThan(*(output[0]), *(output[1]), *label);
  double total = static_cast<double>(height);
  if (weightLayer_) {
    const MatrixPtr& weight = getInputValue(*weightLayer_);
    target->dotMul(*target, *weight);
    total = weight->getSum();
  }
  double pos = target->getSum();
  posPairCount_ += pos;
  negPairCount_ += (total - pos);

  // forward
  target->logisticRegressionLoss(*margin_, *label);
  if (weightLayer_) {
    const MatrixPtr& weight = getInputValue(*weightLayer_);
    target->dotMul(*target, *weight);
  }
}

void RankingCost::backward(const UpdateCallback& callback) {
  (void)callback;

  MatrixPtr label = getInputValue(*getLabelLayer());
  if (!label) {
    // input label is not in value, but in ids
    // use labelBuf_ (should already resized and copied during forward)
    label = labelBuf_;
  }

322 323
  Matrix::resizeOrCreate(
      marginGrad_, label->getHeight(), 1, /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  marginGrad_->zeroMem();
  marginGrad_->logisticRegressionLossBp(*margin_, *label);
  if (weightLayer_) {
    const MatrixPtr& weight = getInputValue(*weightLayer_);
    marginGrad_->dotMul(*marginGrad_, *weight);
  }

  getInputGrad(0)->add(*marginGrad_);
  getInputGrad(1)->sub(*marginGrad_);
}

void RankingCost::onPassEnd() {
  double ratio = posPairCount_ / ((negPairCount_ <= 0) ? 1.0 : negPairCount_);
  LOG(INFO) << "calc pos/neg: " << ratio << " pos= " << posPairCount_
            << " neg= " << negPairCount_;

  posPairCount_ = 0;
  negPairCount_ = 0;
}

//
// class LambdaCost
//
REGISTER_LAYER(lambda_cost, LambdaCost);

bool LambdaCost::init(const LayerMap& layerMap,
                      const ParameterMap& parameterMap) {
  truncationSize_ = config_.ndcg_num();
  maxSortSize_ = config_.max_sort_size();
  if (maxSortSize_ != -1) {
    CHECK_GE(maxSortSize_, truncationSize_)
        << "maxSortSize must be greater than or equal to NDCG size!";
  }
  LOG(INFO) << "LambdaRank v1.3, NDCG size = " << truncationSize_
            << ", Max partial sort size = " << maxSortSize_;
  CHECK(!useGpu_) << "LambdaRank supports CPU only!";
  return Layer::init(layerMap, parameterMap);
}

void LambdaCost::forward(PassType passType) {
  Layer::forward(passType);

  /* malloc memory for the output_ if necessary */
  int batchSize = getInputValue(*getOutputLayer())->getHeight();
  resizeOutput(batchSize, 1);

  MatrixPtr score = getInputValue(*getScoreLayer());
  MatrixPtr output = getInputValue(*getOutputLayer());
  MatrixPtr target = this->getOutputValue();

  real* scoreData = score->getData();
  real* outputData = output->getData();
  real* targetData = target->getData();

378
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
379 380 381 382 383
  const int* startPosData = startPos->getData(false);
  size_t batchNum = startPos->getSize() - 1;
  for (size_t i = 0; i < batchNum; ++i) {
    int beginPos = startPosData[i];
    int endPos = startPosData[i + 1];
384 385
    real NDCG = calcNDCG(
        outputData + beginPos, scoreData + beginPos, endPos - beginPos);
Z
zhangjinchao01 已提交
386 387 388 389 390 391 392 393 394 395
    for (int j = beginPos; j < endPos; ++j) {
      targetData[j] = NDCG;
    }
  }
}

void LambdaCost::backward(const UpdateCallback& callback) {
  (void)callback;
  MatrixPtr score = getInputValue(*getScoreLayer());
  MatrixPtr output = getInputValue(*getOutputLayer());
396 397 398 399 400
  Matrix::resizeOrCreate(marginGrad_,
                         score->getHeight(),
                         1,
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
401 402 403 404 405 406
  marginGrad_->zeroMem();

  real* gradData = marginGrad_->getData();
  real* scoreData = score->getData();
  real* outputData = output->getData();

407
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
408 409 410 411 412 413
  const int* startPosData = startPos->getData(false);
  size_t batchNum = startPos->getSize() - 1;

  for (size_t i = 0; i < batchNum; ++i) {
    int beginPos = startPosData[i];
    int endPos = startPosData[i + 1];
414 415 416
    calcGrad(outputData + beginPos,
             scoreData + beginPos,
             gradData + beginPos,
Z
zhangjinchao01 已提交
417 418 419 420 421 422
             endPos - beginPos);
  }

  getInputGrad(0)->add(*marginGrad_);
}

423 424 425 426
void LambdaCost::calcGrad(const real* outputScore,
                          const real* score,
                          real* gradData,
                          int size) {
Z
zhangjinchao01 已提交
427 428 429 430 431 432 433 434 435
  CHECK_GE(size, truncationSize_)
      << "Invalid: (Sample num in the same list) < (NDCG truncation num) !";
  int sortSize = maxSortSize_ == -1 ? size : std::min(maxSortSize_, size);

  scorePair_.clear();
  for (int i = 0; i < size; ++i) {
    scorePair_.push_back(std::make_pair(score[i], i));
  }
  if (size <= sortSize) {
436 437
    std::sort(scorePair_.begin(),
              scorePair_.end(),
Z
zhangjinchao01 已提交
438 439 440 441 442
              [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
                return a.first > b.first;
              });
  } else {
    std::partial_sort(
443 444 445
        scorePair_.begin(),
        scorePair_.begin() + sortSize,
        scorePair_.end(),
Z
zhangjinchao01 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
          return a.first > b.first;
        });
  }

  real maxDCG = 0;
  for (int i = 0; i < truncationSize_; ++i) {
    maxDCG += (std::pow(2, scorePair_[i].first) - 1) / std::log(i + 2);
  }
  CHECK_GT(maxDCG, 0) << "Invalid: max DCG = 0!";

  for (int i = 0; i < sortSize; ++i) {
    for (int j = i + 1; j < size; ++j) {
      int index_i = scorePair_[i].second;
      int index_j = scorePair_[j].second;
      real score_i = score[index_i];
      real score_j = score[index_j];
      real dcgDif = 0;
      if (j < sortSize) {
        dcgDif = (std::pow(2, score_i) - std::pow(2, score_j)) /
                 (std::log(i + 2) - std::log(j + 2));
      } else {
        dcgDif =
            (std::pow(2, score_i) - std::pow(2, score_j)) / std::log(i + 2);
      }

      real lambda_ij =
          -std::abs(dcgDif) /
          (1 + std::exp(outputScore[index_i] - outputScore[index_j]));
      gradData[index_i] += lambda_ij / maxDCG;
      gradData[index_j] -= lambda_ij / maxDCG;
    }
  }
}

481 482
real LambdaCost::calcNDCG(const real* outputScore,
                          const real* score,
Z
zhangjinchao01 已提交
483 484 485 486 487 488 489 490 491
                          int size) {
  CHECK_GE(size, truncationSize_)
      << "Invalid: (Sample num in the same list) < (NDCG truncation num) !";

  outputScorePair_.clear();
  for (int i = 0; i < size; ++i) {
    outputScorePair_.push_back(std::make_pair(outputScore[i], i));
  }
  std::partial_sort(
492 493
      outputScorePair_.begin(),
      outputScorePair_.begin() + truncationSize_,
Z
zhangjinchao01 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507
      outputScorePair_.end(),
      [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
        return a.first > b.first;
      });

  real DCG = 0;
  for (int i = 0; i < truncationSize_; ++i) {
    DCG +=
        (std::pow(2, score[outputScorePair_[i].second]) - 1) / std::log(i + 2);
  }

  scoreVec_.resize(size);
  std::copy(score, score + size, scoreVec_.begin());
  real maxDCG = 0;
508 509 510 511
  std::partial_sort(scoreVec_.begin(),
                    scoreVec_.begin() + truncationSize_,
                    scoreVec_.end(),
                    std::greater<real>());
Z
zhangjinchao01 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  for (int i = 0; i < truncationSize_; ++i) {
    maxDCG += (std::pow(2, scoreVec_[i]) - 1) / std::log(i + 2);
  }
  CHECK_GT(maxDCG, 0) << "Invalid: max DCG = 0!";

  return DCG / maxDCG;
}

//
// class MultiBinaryLabelCrossEntropy
//

REGISTER_LAYER(multi_binary_label_cross_entropy, MultiBinaryLabelCrossEntropy);

bool MultiBinaryLabelCrossEntropy::init(const LayerMap& layerMap,
                                        const ParameterMap& parameterMap) {
  return CostLayer::init(layerMap, parameterMap);
}

531 532
void MultiBinaryLabelCrossEntropy::forwardImp(Matrix& output,
                                              Argument& label,
Z
zhangjinchao01 已提交
533
                                              Matrix& target) {
H
Haonan 已提交
534 535 536
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!label.value);
H
Haonan 已提交
537
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
Z
zhangjinchao01 已提交
538
  } else {
H
Haonan 已提交
539 540 541
    CHECK(label.value);
    value = label.value;
  }
Z
zhangjinchao01 已提交
542

H
Haonan 已提交
543 544 545
  if (dynamic_cast<CpuSparseMatrix*>(value.get()) ||
      dynamic_cast<GpuSparseMatrix*>(value.get())) {
    target.multiBinaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
546
  } else {
547 548
    Matrix::resizeOrCreate(
        targetPerDim_, output.getHeight(), output.getWidth(), false, useGpu_);
Z
zhangjinchao01 已提交
549

H
Haonan 已提交
550
    targetPerDim_->binaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
551 552 553 554
    targetPerDim_->rowSum(target);
  }
}

555 556 557
void MultiBinaryLabelCrossEntropy::backwardImp(Matrix& output,
                                               Argument& label,
                                               Matrix& outputG) {
H
Haonan 已提交
558 559 560
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!value);
H
Haonan 已提交
561
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
H
Haonan 已提交
562 563 564 565
  } else {
    CHECK(label.value);
    value = label.value;
  }
566

H
Haonan 已提交
567 568 569
  if (dynamic_cast<CpuSparseMatrix*>(value.get()) ||
      dynamic_cast<GpuSparseMatrix*>(value.get())) {
    outputG.multiBinaryLabelCrossEntropyBp(output, *value);
Z
zhangjinchao01 已提交
570
  } else {
H
Haonan 已提交
571
    outputG.binaryLabelCrossEntropyBp(output, *value);
Z
zhangjinchao01 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  }
}

//
// Huber loss for robust 2-classes classification
//
REGISTER_LAYER(huber, HuberTwoClass);

bool HuberTwoClass::init(const LayerMap& layerMap,
                         const ParameterMap& parameterMap) {
  CostLayer::init(layerMap, parameterMap);
  if (useGpu_) {
    tmpCpuInput_.reserve(inputLayers_.size());
    for (size_t i = 0; i < inputLayers_.size(); i++) {
      tmpCpuInput_.push_back(Argument());
    }
  }
  return true;
}

592
void HuberTwoClass::forwardImp(Matrix& output, Argument& label, Matrix& cost) {
Z
zhangjinchao01 已提交
593 594
  if (useGpu_) {
    for (size_t i = 0; i < inputLayers_.size(); i++) {
595 596
      tmpCpuInput_[i].resizeAndCopyFrom(
          getInput(i), false, HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
597
    }
598
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
599 600 601 602
  }
  forwardImpIn(output, label, cost);
}

603 604
void HuberTwoClass::forwardImpIn(Matrix& output,
                                 Argument& label,
Z
zhangjinchao01 已提交
605 606 607 608 609 610 611
                                 Matrix& target) {
  size_t numSamples = target.getHeight();
  CHECK_EQ((*label.ids).getSize(), numSamples);
  CHECK_EQ(output.getHeight(), numSamples);
  CHECK_EQ(output.getWidth(), (size_t)1);
  CHECK_EQ(target.getWidth(), (size_t)1);

612
  real* out = useGpu_ ? tmpCpuInput_[0].value->getData() : output.getData();
Z
zhangjinchao01 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626
  int* lbl = useGpu_ ? tmpCpuInput_[1].ids->getData() : (*label.ids).getData();
  std::vector<real> cost(numSamples);
  for (size_t i = 0; i < numSamples; ++i) {
    int y = 2 * lbl[i] - 1;
    if (out[i] * y < -1)
      cost[i] = -4 * out[i] * y;
    else if (out[i] * y < 1)
      cost[i] = (1 - out[i] * y) * (1 - out[i] * y);
    else
      cost[i] = 0;
  }
  target.copyFrom(cost.data(), numSamples);
}

627 628 629
void HuberTwoClass::backwardImp(Matrix& outputValue,
                                Argument& label,
                                Matrix& outputGrad) {
Z
zhangjinchao01 已提交
630
  if (useGpu_) {
631 632
    backwardImpIn(
        *tmpCpuInput_[0].value, tmpCpuInput_[1], *tmpCpuInput_[0].grad);
Z
zhangjinchao01 已提交
633 634 635 636 637 638
    outputGrad.copyFrom(*tmpCpuInput_[0].grad);
  } else {
    backwardImpIn(outputValue, label, outputGrad);
  }
}

639 640 641
void HuberTwoClass::backwardImpIn(Matrix& output,
                                  Argument& label,
                                  Matrix& outputG) {
Z
zhangjinchao01 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654
  size_t numSamples = output.getHeight();
  real* out = output.getData();
  real* grad = outputG.getData();
  int* lbl = (*label.ids).getData();
  for (size_t i = 0; i < numSamples; ++i) {
    int y = 2 * lbl[i] - 1;
    if (y * out[i] < -1)
      grad[i] += -4 * y;
    else if (y * out[i] < 1)
      grad[i] += -2 * (1 - y * out[i]) * y;
  }
}

X
xuwei06 已提交
655 656 657 658 659 660
/**
 * This cost layer compute the sum of its input as loss.
 * \f[
 * o(i) = \sum_{j=1}^D y_{ij}
 * \f]
 */
X
xuwei06 已提交
661 662 663 664
class SumCostLayer : public Layer {
public:
  explicit SumCostLayer(const LayerConfig& config) : Layer(config) {}

Y
Yu Yang 已提交
665 666
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override {
X
xuwei06 已提交
667 668 669 670 671 672
    bool ret = Layer::init(layerMap, parameterMap);
    if (!ret) return ret;
    CHECK_EQ(inputLayers_.size(), 1UL);
    return true;
  }

Y
Yu Yang 已提交
673
  void forward(PassType passType) override {
X
xuwei06 已提交
674 675 676 677 678 679 680
    Layer::forward(passType);
    const MatrixPtr& input = getInputValue(0);

    /* malloc memory for the output_ if necessary */
    int batchSize = input->getHeight();
    int size = 1;
    resizeOutput(batchSize, size);
681
    output_.value->sumRows(*input, /* scaleSum= */ 1, /* scaleDest= */ 0);
X
xuwei06 已提交
682 683
  }

Y
Yu Yang 已提交
684
  void backward(const UpdateCallback& callback = nullptr) override {
X
xuwei06 已提交
685 686 687 688 689 690
    getInputGrad(0)->add((real)1);
  }
};

REGISTER_LAYER(sum_cost, SumCostLayer);

Z
zhangjinchao01 已提交
691
}  // namespace paddle