CostLayer.cpp 21.8 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
//
// 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) {
  MatrixPtr targetCpu, labelCpu, outputCpu;
  if (useGpu_) {
    Matrix::resizeOrCreate(
        targetCpu, target.getHeight(), target.getWidth(), false, false);
    Matrix::resizeOrCreate(
        outputCpu, output.getHeight(), output.getWidth(), false, false);
    Matrix::resizeOrCreate(labelCpu,
                           label.value->getHeight(),
                           label.value->getWidth(),
                           false,
                           false);
    targetCpu->copyFrom(target);
    outputCpu->copyFrom(output);
    labelCpu->copyFrom(*label.value);
    targetCpu->smoothL1(*outputCpu, *(labelCpu));
    target.copyFrom(*targetCpu);
  } else {
    target.smoothL1(output, *label.value);
  }
}

void SmoothL1CostLayer::backwardImp(Matrix& output,
                                    Argument& label,
                                    Matrix& outputG) {
  MatrixPtr outputGCpu, labelCpu, outputCpu;
  if (useGpu_) {
    Matrix::resizeOrCreate(
        outputGCpu, outputG.getHeight(), outputG.getWidth(), false, false);
    Matrix::resizeOrCreate(
        outputCpu, output.getHeight(), output.getWidth(), false, false);
    Matrix::resizeOrCreate(labelCpu,
                           label.value->getHeight(),
                           label.value->getWidth(),
                           false,
                           false);
    outputGCpu->copyFrom(outputG);
    outputCpu->copyFrom(output);
    labelCpu->copyFrom(*label.value);
    outputGCpu->smoothL1Bp(*outputCpu, *labelCpu);
    outputG.copyFrom(*outputGCpu);
  } else {
    outputG.smoothL1Bp(output, *label.value);
  }
}

Z
zhangjinchao01 已提交
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 280 281 282 283 284 285
//
// 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());
286 287
    Matrix::resizeOrCreate(
        labelBuf_, batchSize, /*width*/ 1, /*trans*/ false, useGpu_);
Z
zhangjinchao01 已提交
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 322 323 324 325 326 327
    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_;
  }

328 329
  Matrix::resizeOrCreate(
      marginGrad_, label->getHeight(), 1, /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
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 378 379 380 381 382 383
  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();

384
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
385 386 387 388 389
  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];
390 391
    real NDCG = calcNDCG(
        outputData + beginPos, scoreData + beginPos, endPos - beginPos);
Z
zhangjinchao01 已提交
392 393 394 395 396 397 398 399 400 401
    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());
402 403 404 405 406
  Matrix::resizeOrCreate(marginGrad_,
                         score->getHeight(),
                         1,
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
407 408 409 410 411 412
  marginGrad_->zeroMem();

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

413
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
414 415 416 417 418 419
  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];
420 421 422
    calcGrad(outputData + beginPos,
             scoreData + beginPos,
             gradData + beginPos,
Z
zhangjinchao01 已提交
423 424 425 426 427 428
             endPos - beginPos);
  }

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

429 430 431 432
void LambdaCost::calcGrad(const real* outputScore,
                          const real* score,
                          real* gradData,
                          int size) {
Z
zhangjinchao01 已提交
433 434 435 436 437 438 439 440 441
  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) {
442 443
    std::sort(scorePair_.begin(),
              scorePair_.end(),
Z
zhangjinchao01 已提交
444 445 446 447 448
              [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
                return a.first > b.first;
              });
  } else {
    std::partial_sort(
449 450 451
        scorePair_.begin(),
        scorePair_.begin() + sortSize,
        scorePair_.end(),
Z
zhangjinchao01 已提交
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 481 482 483 484 485 486
        [](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;
    }
  }
}

487 488
real LambdaCost::calcNDCG(const real* outputScore,
                          const real* score,
Z
zhangjinchao01 已提交
489 490 491 492 493 494 495 496 497
                          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(
498 499
      outputScorePair_.begin(),
      outputScorePair_.begin() + truncationSize_,
Z
zhangjinchao01 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513
      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;
514 515 516 517
  std::partial_sort(scoreVec_.begin(),
                    scoreVec_.begin() + truncationSize_,
                    scoreVec_.end(),
                    std::greater<real>());
Z
zhangjinchao01 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  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);
}

537 538
void MultiBinaryLabelCrossEntropy::forwardImp(Matrix& output,
                                              Argument& label,
Z
zhangjinchao01 已提交
539
                                              Matrix& target) {
H
Haonan 已提交
540 541 542
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!label.value);
H
Haonan 已提交
543
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
Z
zhangjinchao01 已提交
544
  } else {
H
Haonan 已提交
545 546 547
    CHECK(label.value);
    value = label.value;
  }
Z
zhangjinchao01 已提交
548

H
Haonan 已提交
549 550 551
  if (dynamic_cast<CpuSparseMatrix*>(value.get()) ||
      dynamic_cast<GpuSparseMatrix*>(value.get())) {
    target.multiBinaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
552
  } else {
553 554
    Matrix::resizeOrCreate(
        targetPerDim_, output.getHeight(), output.getWidth(), false, useGpu_);
Z
zhangjinchao01 已提交
555

H
Haonan 已提交
556
    targetPerDim_->binaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
557 558 559 560
    targetPerDim_->rowSum(target);
  }
}

561 562 563
void MultiBinaryLabelCrossEntropy::backwardImp(Matrix& output,
                                               Argument& label,
                                               Matrix& outputG) {
H
Haonan 已提交
564 565 566
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!value);
H
Haonan 已提交
567
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
H
Haonan 已提交
568 569 570 571
  } else {
    CHECK(label.value);
    value = label.value;
  }
572

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

//
// 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;
}

598
void HuberTwoClass::forwardImp(Matrix& output, Argument& label, Matrix& cost) {
Z
zhangjinchao01 已提交
599 600
  if (useGpu_) {
    for (size_t i = 0; i < inputLayers_.size(); i++) {
601 602
      tmpCpuInput_[i].resizeAndCopyFrom(
          getInput(i), false, HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
603
    }
604
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
605 606 607 608
  }
  forwardImpIn(output, label, cost);
}

609 610
void HuberTwoClass::forwardImpIn(Matrix& output,
                                 Argument& label,
Z
zhangjinchao01 已提交
611 612 613 614 615 616 617
                                 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);

618
  real* out = useGpu_ ? tmpCpuInput_[0].value->getData() : output.getData();
Z
zhangjinchao01 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632
  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);
}

633 634 635
void HuberTwoClass::backwardImp(Matrix& outputValue,
                                Argument& label,
                                Matrix& outputGrad) {
Z
zhangjinchao01 已提交
636
  if (useGpu_) {
637 638
    backwardImpIn(
        *tmpCpuInput_[0].value, tmpCpuInput_[1], *tmpCpuInput_[0].grad);
Z
zhangjinchao01 已提交
639 640 641 642 643 644
    outputGrad.copyFrom(*tmpCpuInput_[0].grad);
  } else {
    backwardImpIn(outputValue, label, outputGrad);
  }
}

645 646 647
void HuberTwoClass::backwardImpIn(Matrix& output,
                                  Argument& label,
                                  Matrix& outputG) {
Z
zhangjinchao01 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660
  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 已提交
661 662 663 664 665 666
/**
 * This cost layer compute the sum of its input as loss.
 * \f[
 * o(i) = \sum_{j=1}^D y_{ij}
 * \f]
 */
X
xuwei06 已提交
667 668 669 670
class SumCostLayer : public Layer {
public:
  explicit SumCostLayer(const LayerConfig& config) : Layer(config) {}

Y
Yu Yang 已提交
671 672
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override {
X
xuwei06 已提交
673 674 675 676 677 678
    bool ret = Layer::init(layerMap, parameterMap);
    if (!ret) return ret;
    CHECK_EQ(inputLayers_.size(), 1UL);
    return true;
  }

Y
Yu Yang 已提交
679
  void forward(PassType passType) override {
X
xuwei06 已提交
680 681 682 683 684 685 686
    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);
687
    output_.value->sumRows(*input, /* scaleSum= */ 1, /* scaleDest= */ 0);
X
xuwei06 已提交
688 689
  }

Y
Yu Yang 已提交
690
  void backward(const UpdateCallback& callback = nullptr) override {
X
xuwei06 已提交
691 692 693 694 695 696
    getInputGrad(0)->add((real)1);
  }
};

REGISTER_LAYER(sum_cost, SumCostLayer);

Z
zhangjinchao01 已提交
697
}  // namespace paddle