FactorizationMachineLayer.cpp 5.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/* Copyright (c) 2016 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. */

#include "FactorizationMachineLayer.h"
#include <algorithm>
#include <vector>
#include "paddle/math/SparseMatrix.h"
#include "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"

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 62 63
  REGISTER_TIMER_INFO("InputMulFactorTimer", getName().c_str());
  inputMulFactor_->mul(*inputV, *latentVectors_->getW());
  inputMulFactor_->square2(*tmpOut_);
W
wangmeng28 已提交
64 65
  outV->sumRows(*tmpOut_, 0.5, 0);

66 67 68 69
  inputSquare_ = inputV->clone(0, 0, useGpu_);
  if (dynamic_cast<CpuSparseMatrix*>(inputSquare_.get())) {
    inputSquare_->copyFrom(*inputV);
    (dynamic_cast<CpuSparseMatrix*>(inputSquare_.get()))->square2();
70
  } else {
71
    inputV->square2(*inputSquare_);
72
  }
73 74
  latentVectors_->getW()->square2(*latentVectorsSquare_);
  tmpOut_->mul(*inputSquare_, *latentVectorsSquare_);
W
wangmeng28 已提交
75 76
  outV->sumRows(*tmpOut_, -0.5, 1.0);

77
  /* activation */ {
78
    REGISTER_TIMER_INFO("FmAtvTimer", getName().c_str());
79 80 81 82 83
    forwardActivation();
  }
}

void FactorizationMachineLayer::backward(const UpdateCallback& callback) {
84
  /* Do derivation */ { backwardActivation(); }
W
wangmeng28 已提交
85 86 87 88

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

89 90 91 92 93 94 95
  Matrix::resizeOrCreate(
      tmpSum_, 1, latentVectors_->getW()->getHeight(), false, useGpu_);
  MatrixPtr tmpSumTrans = Matrix::create(tmpSum_->getRowBuf(0),
                                         latentVectors_->getW()->getHeight(),
                                         1,
                                         false,
                                         useGpu_);
W
wangmeng28 已提交
96 97 98

  /* Calculate the gradients of the latentVectors_ matrix */
  if (latentVectors_->getWGrad()) {
99
    if (dynamic_cast<CpuSparseMatrix*>(inputV.get())) {
100 101 102 103 104
      Matrix::resizeOrCreateSparseMatrix(tmpInput_,
                                         inputV->getHeight(),
                                         inputV->getWidth(),
                                         inputV->getElementCnt());

105 106 107 108 109
      CpuSparseMatrix* sparseInputV =
          dynamic_cast<CpuSparseMatrix*>(inputV.get());
      CpuSparseMatrix* sparseInputSquare =
          dynamic_cast<CpuSparseMatrix*>(inputSquare_.get());
      CpuSparseMatrix* sparseTmpInput =
110
          dynamic_cast<CpuSparseMatrix*>(tmpInput_.get());
111
      sparseTmpInput->copyFrom(*sparseInputV);
112

113 114 115 116 117 118 119 120 121
      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);
122
    } else {
123 124 125 126
      Matrix::resizeOrCreate(
          tmpInput_, inputV->getHeight(), inputV->getWidth(), false, useGpu_);

      tmpInput_->rowScale(0, *inputV, *oGrad);
127
      latentVectors_->getWGrad()->mul(
128 129
          *tmpInput_->getTranspose(), *inputMulFactor_, 1, 1);
      tmpInput_->rowScale(0, *inputSquare_, *oGrad);
130

131
      tmpSum_->sumCols(*tmpInput_, -1, 0);
132
    }
W
wangmeng28 已提交
133 134

    latentVectors_->getWGrad()->addRowScale(
135
        0, *latentVectors_->getW(), *tmpSumTrans);
W
wangmeng28 已提交
136 137 138 139 140 141 142 143

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

  /* Calculate the input layers gradient */
  MatrixPtr inGrad = getInputGrad(0);
  if (inGrad != NULL) {
144 145 146 147
    inGrad->mul(
        *inputMulFactor_, *latentVectors_->getW()->getTranspose(), 1, 1);
    tmpSumTrans->sumRows(*latentVectorsSquare_, -1, 0);
    inGrad->addColScale(0, *inputV, *tmpSum_);
W
wangmeng28 已提交
148 149
    inGrad->rowScale(0, *inGrad, *oGrad);
  }
150 151 152
}

}  // namespace paddle