FactorizationMachineLayer.cpp 5.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

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

#include "FactorizationMachineLayer.h"
#include <algorithm>
#include <vector>
X
Xin Pan 已提交
18
#include "paddle/legacy/math/SparseMatrix.h"
X
Xin Pan 已提交
19 20
#include "paddle/legacy/utils/Logging.h"
#include "paddle/legacy/utils/Stat.h"
21 22 23 24 25 26 27 28 29 30 31 32 33 34

namespace paddle {

REGISTER_LAYER(factorization_machine, FactorizationMachineLayer);

bool FactorizationMachineLayer::init(const LayerMap& layerMap,
                                     const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  Layer::init(layerMap, parameterMap);

  factorSize_ = config_.factor_size();

  /* initialize the latentVectors_ */
  CHECK_EQ(inputLayers_.size(), 1UL);
35 36 37 38
  size_t inputSize = inputLayers_[0]->getSize();
  CHECK_EQ(parameters_[0]->getSize(), inputSize * factorSize_);
  latentVectors_ = std::unique_ptr<Weight>(
      new Weight(inputSize, factorSize_, parameters_[0]));
39 40 41 42 43 44 45

  return true;
}

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

W
wangmeng28 已提交
46
  const MatrixPtr& inputV = getInputValue(0);
47

W
wangmeng28 已提交
48
  size_t batchSize = inputV->getHeight();
49 50 51
  size_t outputSize = getSize();
  size_t inputSize = inputLayers_[0]->getSize();
  reserveOutput(batchSize, outputSize);
52 53 54

  MatrixPtr outV = getOutputValue();

55 56 57 58
  Matrix::resizeOrCreate(
      latentVectorsSquare_, inputSize, factorSize_, false, useGpu_);
  Matrix::resizeOrCreate(
      inputMulFactor_, batchSize, factorSize_, false, useGpu_);
W
wangmeng28 已提交
59 60
  Matrix::resizeOrCreate(tmpOut_, batchSize, factorSize_, false, useGpu_);

61
  REGISTER_TIMER_INFO("FmInputMulFactorTimer", getName().c_str());
62 63
  inputMulFactor_->mul(*inputV, *latentVectors_->getW());
  inputMulFactor_->square2(*tmpOut_);
W
wangmeng28 已提交
64 65
  outV->sumRows(*tmpOut_, 0.5, 0);

66 67 68 69 70 71
  if (dynamic_cast<CpuSparseMatrix*>(inputV.get())) {
    Matrix::resizeOrCreateSparseMatrix(inputSquare_,
                                       inputV->getHeight(),
                                       inputV->getWidth(),
                                       inputV->getElementCnt(),
                                       inputV->getValueType());
72 73
    inputSquare_->copyFrom(*inputV);
    (dynamic_cast<CpuSparseMatrix*>(inputSquare_.get()))->square2();
74
  } else {
75 76
    Matrix::resizeOrCreate(
        inputSquare_, inputV->getHeight(), inputV->getWidth(), false, useGpu_);
77
    inputV->square2(*inputSquare_);
78
  }
79 80
  latentVectors_->getW()->square2(*latentVectorsSquare_);
  tmpOut_->mul(*inputSquare_, *latentVectorsSquare_);
W
wangmeng28 已提交
81 82
  outV->sumRows(*tmpOut_, -0.5, 1.0);

83
  /* activation */ {
84
    REGISTER_TIMER_INFO("FmFwAtvTimer", getName().c_str());
85 86 87 88 89
    forwardActivation();
  }
}

void FactorizationMachineLayer::backward(const UpdateCallback& callback) {
90
  /* Do derivation */ { backwardActivation(); }
W
wangmeng28 已提交
91 92 93 94

  const MatrixPtr& inputV = getInputValue(0);
  const MatrixPtr& oGrad = getOutputGrad();

95 96 97 98 99 100 101
  Matrix::resizeOrCreate(
      tmpSum_, 1, latentVectors_->getW()->getHeight(), false, useGpu_);
  MatrixPtr tmpSumTrans = Matrix::create(tmpSum_->getRowBuf(0),
                                         latentVectors_->getW()->getHeight(),
                                         1,
                                         false,
                                         useGpu_);
W
wangmeng28 已提交
102 103 104

  /* Calculate the gradients of the latentVectors_ matrix */
  if (latentVectors_->getWGrad()) {
105
    if (dynamic_cast<CpuSparseMatrix*>(inputV.get())) {
106 107 108 109 110
      Matrix::resizeOrCreateSparseMatrix(tmpInput_,
                                         inputV->getHeight(),
                                         inputV->getWidth(),
                                         inputV->getElementCnt());

111 112 113 114 115
      CpuSparseMatrix* sparseInputV =
          dynamic_cast<CpuSparseMatrix*>(inputV.get());
      CpuSparseMatrix* sparseInputSquare =
          dynamic_cast<CpuSparseMatrix*>(inputSquare_.get());
      CpuSparseMatrix* sparseTmpInput =
116
          dynamic_cast<CpuSparseMatrix*>(tmpInput_.get());
117
      sparseTmpInput->copyFrom(*sparseInputV);
118

119 120 121 122 123 124 125 126 127
      sparseTmpInput->rowScale(0, *sparseInputV, *oGrad);
      latentVectors_->getWGrad()->mul(
          *sparseTmpInput->getTranspose(), *inputMulFactor_, 1, 1);
      sparseTmpInput->rowScale(0, *sparseInputSquare, *oGrad);

      Matrix::resizeOrCreate(negOnes_, 1, inputV->getHeight(), false, useGpu_);
      negOnes_->zeroMem();
      negOnes_->add(-1);
      tmpSum_->mul(*negOnes_, *sparseTmpInput, 1, 0);
128
    } else {
129 130 131 132
      Matrix::resizeOrCreate(
          tmpInput_, inputV->getHeight(), inputV->getWidth(), false, useGpu_);

      tmpInput_->rowScale(0, *inputV, *oGrad);
133
      latentVectors_->getWGrad()->mul(
134 135
          *tmpInput_->getTranspose(), *inputMulFactor_, 1, 1);
      tmpInput_->rowScale(0, *inputSquare_, *oGrad);
136

137
      tmpSum_->sumCols(*tmpInput_, -1, 0);
138
    }
W
wangmeng28 已提交
139 140

    latentVectors_->getWGrad()->addRowScale(
141
        0, *latentVectors_->getW(), *tmpSumTrans);
W
wangmeng28 已提交
142 143 144 145 146 147 148 149

    /* Increasing the number of gradient */
    latentVectors_->getParameterPtr()->incUpdate(callback);
  }

  /* Calculate the input layers gradient */
  MatrixPtr inGrad = getInputGrad(0);
  if (inGrad != NULL) {
150 151 152 153
    inGrad->mul(
        *inputMulFactor_, *latentVectors_->getW()->getTranspose(), 1, 1);
    tmpSumTrans->sumRows(*latentVectorsSquare_, -1, 0);
    inGrad->addColScale(0, *inputV, *tmpSum_);
W
wangmeng28 已提交
154 155
    inGrad->rowScale(0, *inGrad, *oGrad);
  }
156 157 158
}

}  // namespace paddle