CostLayer.cpp 19.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 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
  outputG.sumOfSquaresBp(output, *label.value);
}

//
// 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());
227 228
    Matrix::resizeOrCreate(
        labelBuf_, batchSize, /*width*/ 1, /*trans*/ false, useGpu_);
Z
zhangjinchao01 已提交
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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    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_;
  }

269 270
  Matrix::resizeOrCreate(
      marginGrad_, label->getHeight(), 1, /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
271 272 273 274 275 276 277 278 279 280 281 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 322 323 324
  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();

325
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
326 327 328 329 330
  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];
331 332
    real NDCG = calcNDCG(
        outputData + beginPos, scoreData + beginPos, endPos - beginPos);
Z
zhangjinchao01 已提交
333 334 335 336 337 338 339 340 341 342
    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());
343 344 345 346 347
  Matrix::resizeOrCreate(marginGrad_,
                         score->getHeight(),
                         1,
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
348 349 350 351 352 353
  marginGrad_->zeroMem();

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

354
  auto startPos = getInput(*getOutputLayer()).sequenceStartPositions;
Z
zhangjinchao01 已提交
355 356 357 358 359 360
  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];
361 362 363
    calcGrad(outputData + beginPos,
             scoreData + beginPos,
             gradData + beginPos,
Z
zhangjinchao01 已提交
364 365 366 367 368 369
             endPos - beginPos);
  }

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

370 371 372 373
void LambdaCost::calcGrad(const real* outputScore,
                          const real* score,
                          real* gradData,
                          int size) {
Z
zhangjinchao01 已提交
374 375 376 377 378 379 380 381 382
  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) {
383 384
    std::sort(scorePair_.begin(),
              scorePair_.end(),
Z
zhangjinchao01 已提交
385 386 387 388 389
              [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
                return a.first > b.first;
              });
  } else {
    std::partial_sort(
390 391 392
        scorePair_.begin(),
        scorePair_.begin() + sortSize,
        scorePair_.end(),
Z
zhangjinchao01 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        [](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;
    }
  }
}

428 429
real LambdaCost::calcNDCG(const real* outputScore,
                          const real* score,
Z
zhangjinchao01 已提交
430 431 432 433 434 435 436 437 438
                          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(
439 440
      outputScorePair_.begin(),
      outputScorePair_.begin() + truncationSize_,
Z
zhangjinchao01 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454
      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;
455 456 457 458
  std::partial_sort(scoreVec_.begin(),
                    scoreVec_.begin() + truncationSize_,
                    scoreVec_.end(),
                    std::greater<real>());
Z
zhangjinchao01 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
  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);
}

478 479
void MultiBinaryLabelCrossEntropy::forwardImp(Matrix& output,
                                              Argument& label,
Z
zhangjinchao01 已提交
480
                                              Matrix& target) {
H
Haonan 已提交
481 482 483
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!label.value);
H
Haonan 已提交
484
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
Z
zhangjinchao01 已提交
485
  } else {
H
Haonan 已提交
486 487 488
    CHECK(label.value);
    value = label.value;
  }
Z
zhangjinchao01 已提交
489

H
Haonan 已提交
490 491 492
  if (dynamic_cast<CpuSparseMatrix*>(value.get()) ||
      dynamic_cast<GpuSparseMatrix*>(value.get())) {
    target.multiBinaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
493
  } else {
494 495
    Matrix::resizeOrCreate(
        targetPerDim_, output.getHeight(), output.getWidth(), false, useGpu_);
Z
zhangjinchao01 已提交
496

H
Haonan 已提交
497
    targetPerDim_->binaryLabelCrossEntropy(output, *value);
Z
zhangjinchao01 已提交
498 499 500 501
    targetPerDim_->rowSum(target);
  }
}

502 503 504
void MultiBinaryLabelCrossEntropy::backwardImp(Matrix& output,
                                               Argument& label,
                                               Matrix& outputG) {
H
Haonan 已提交
505 506 507
  MatrixPtr value = nullptr;
  if (label.ids) {
    CHECK(!value);
H
Haonan 已提交
508
    value = label.ids->toOneHotSparseMatrix(output.getWidth(), useGpu_);
H
Haonan 已提交
509 510 511 512
  } else {
    CHECK(label.value);
    value = label.value;
  }
513

H
Haonan 已提交
514 515 516
  if (dynamic_cast<CpuSparseMatrix*>(value.get()) ||
      dynamic_cast<GpuSparseMatrix*>(value.get())) {
    outputG.multiBinaryLabelCrossEntropyBp(output, *value);
Z
zhangjinchao01 已提交
517
  } else {
H
Haonan 已提交
518
    outputG.binaryLabelCrossEntropyBp(output, *value);
Z
zhangjinchao01 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  }
}

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

539
void HuberTwoClass::forwardImp(Matrix& output, Argument& label, Matrix& cost) {
Z
zhangjinchao01 已提交
540 541
  if (useGpu_) {
    for (size_t i = 0; i < inputLayers_.size(); i++) {
542 543
      tmpCpuInput_[i].resizeAndCopyFrom(
          getInput(i), false, HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
544
    }
545
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
546 547 548 549
  }
  forwardImpIn(output, label, cost);
}

550 551
void HuberTwoClass::forwardImpIn(Matrix& output,
                                 Argument& label,
Z
zhangjinchao01 已提交
552 553 554 555 556 557 558
                                 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);

559
  real* out = useGpu_ ? tmpCpuInput_[0].value->getData() : output.getData();
Z
zhangjinchao01 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573
  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);
}

574 575 576
void HuberTwoClass::backwardImp(Matrix& outputValue,
                                Argument& label,
                                Matrix& outputGrad) {
Z
zhangjinchao01 已提交
577
  if (useGpu_) {
578 579
    backwardImpIn(
        *tmpCpuInput_[0].value, tmpCpuInput_[1], *tmpCpuInput_[0].grad);
Z
zhangjinchao01 已提交
580 581 582 583 584 585
    outputGrad.copyFrom(*tmpCpuInput_[0].grad);
  } else {
    backwardImpIn(outputValue, label, outputGrad);
  }
}

586 587 588
void HuberTwoClass::backwardImpIn(Matrix& output,
                                  Argument& label,
                                  Matrix& outputG) {
Z
zhangjinchao01 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601
  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 已提交
602 603 604 605 606 607
/**
 * This cost layer compute the sum of its input as loss.
 * \f[
 * o(i) = \sum_{j=1}^D y_{ij}
 * \f]
 */
X
xuwei06 已提交
608 609 610 611
class SumCostLayer : public Layer {
public:
  explicit SumCostLayer(const LayerConfig& config) : Layer(config) {}

Y
Yu Yang 已提交
612 613
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override {
X
xuwei06 已提交
614 615 616 617 618 619
    bool ret = Layer::init(layerMap, parameterMap);
    if (!ret) return ret;
    CHECK_EQ(inputLayers_.size(), 1UL);
    return true;
  }

Y
Yu Yang 已提交
620
  void forward(PassType passType) override {
X
xuwei06 已提交
621 622 623 624 625 626 627
    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);
628
    output_.value->sumRows(*input, /* scaleSum= */ 1, /* scaleDest= */ 0);
X
xuwei06 已提交
629 630
  }

Y
Yu Yang 已提交
631
  void backward(const UpdateCallback& callback = nullptr) override {
X
xuwei06 已提交
632 633 634 635 636 637
    getInputGrad(0)->add((real)1);
  }
};

REGISTER_LAYER(sum_cost, SumCostLayer);

Z
zhangjinchao01 已提交
638
}  // namespace paddle