CosSimVecMatLayer.cpp 6.3 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. */

15 16
#include "Layer.h"
#include "paddle/math/Matrix.h"
Y
Yu Yang 已提交
17
#include "paddle/utils/Logging.h"
Z
zhangjinchao01 已提交
18 19 20
#include "paddle/utils/Stat.h"

namespace paddle {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/**
 * @brief A layer for computing cosine similarity between a vector
 * and each row of a matrix
 * out[i] = cos_scale * cos(in1, in2(i,:));
 * @note used in NEURAL TURING MACHINE
 *
 * Input1: a vector (batchSize * dataDim)
 *
 * Input2: a matrix in vector form (batchSize * (weightDim*dataDim))
 *
 * Output: a vector (batchSize * weightDim)
 */

class CosSimVecMatLayer : public Layer {
public:
  explicit CosSimVecMatLayer(const LayerConfig& config) : Layer(config) {}

  ~CosSimVecMatLayer() {}

  bool init(const LayerMap& layerMap, const ParameterMap& parameterMap);

  void forward(PassType passType);
  void backward(const UpdateCallback& callback = nullptr);

protected:
  MatrixPtr tmpMtx0;
  MatrixPtr tmpMtx1;
  MatrixPtr tmpRow0;
  MatrixPtr tmpRow1;
  MatrixPtr tmpRow2;
  MatrixPtr tmpRow3;
};
Z
zhangjinchao01 已提交
53 54

/**
Q
qijun 已提交
55 56
 * @brief A layer for computing cosine similarity between a vector
 * and each row of a matrix
Z
zhangjinchao01 已提交
57
 * out[i] = cos_scale * cos(in1, in2(i,:));
Q
qijun 已提交
58 59 60 61 62 63 64
 * @note used in NEURAL TURING MACHINE
 *
 * Input1: a vector (batchSize * dataDim)
 *
 * Input2: a matrix in vector form (batchSize * (weightDim*dataDim))
 *
 * Output: a vector (batchSize * weightDim)
Z
zhangjinchao01 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
 */

class CosSimVecMatLayer : public Layer {
protected:
  MatrixPtr tmpMtx0;
  MatrixPtr tmpMtx1;
  MatrixPtr tmpRow0;
  MatrixPtr tmpRow1;
  MatrixPtr tmpRow2;
  MatrixPtr tmpRow3;

public:
  explicit CosSimVecMatLayer(const LayerConfig& config) : Layer(config) {}

  ~CosSimVecMatLayer() {}

Y
Yu Yang 已提交
81 82
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
83

Y
Yu Yang 已提交
84 85
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback = nullptr) override;
Z
zhangjinchao01 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
};

REGISTER_LAYER(cos_vm, CosSimVecMatLayer);

bool CosSimVecMatLayer::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  Layer::init(layerMap, parameterMap);

  CHECK_EQ(inputLayers_.size(), 2U);

  size_t dataDim = inputLayers_[0]->getSize();
  size_t numKeys = getSize();
  size_t memoryDim = inputLayers_[1]->getSize();

  CHECK_EQ(dataDim * numKeys, memoryDim) << "Dimension mismatch";

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  tmpRow0 = Matrix::create(nullptr,
                           /* height= */ 1,
                           dataDim,
                           /* trans= */ false,
                           useGpu_);
  tmpRow1 = Matrix::create(nullptr,
                           /* height= */ 1,
                           dataDim,
                           /* trans= */ false,
                           useGpu_);
  tmpRow2 = Matrix::create(nullptr,
                           /* height= */ numKeys,
                           1,
                           /* trans= */ false,
                           useGpu_);
  tmpRow3 = Matrix::create(nullptr,
                           /* height= */ numKeys,
                           1,
                           /* trans= */ false,
                           useGpu_);

  tmpMtx0 = Matrix::create(nullptr,
                           /* height= */ numKeys,
                           dataDim,
                           /* trans= */ false,
                           useGpu_);
  tmpMtx1 = Matrix::create(nullptr,
                           /* height= */ numKeys,
                           dataDim,
                           /* trans= */ false,
                           useGpu_);
133 134 135 136 137 138 139 140 141 142

  CHECK(tmpRow0 && tmpRow1 && tmpRow2 && tmpRow3 && tmpMtx0 && tmpMtx1);

  createFunction(forward_,
                 "CosSimForward",
                 FuncConfig().set("scale", (real)config_.cos_scale()));
  createFunction(backward_,
                 "CosSimBackward",
                 FuncConfig().set("scale", (real)config_.cos_scale()));

Z
zhangjinchao01 已提交
143 144 145 146 147
  return true;
}

void CosSimVecMatLayer::forward(PassType passType) {
  Layer::forward(passType);
148
  CHECK_EQ(forward_.size(), 1) << "Only one forward function needed";
Z
zhangjinchao01 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

  MatrixPtr inV0 = getInputValue(0);
  MatrixPtr inV1 = getInputValue(1);

  size_t batchSize = inV0->getHeight();
  size_t numKeys = getSize();

  CHECK_EQ(batchSize, inV1->getHeight());

  {
    REGISTER_TIMER_INFO("FwResetTimer", getName().c_str());
    reserveOutput(batchSize, numKeys);
  }

  MatrixPtr outV = getOutputValue();
164
  CHECK(outV && inV0 && inV1);
Z
zhangjinchao01 已提交
165 166 167 168 169
  REGISTER_TIMER_INFO("FwCosVMTimer", getName().c_str());
  for (size_t i = 0; i < batchSize; i++) {
    tmpRow0->setData(inV0->rowBuf(i));
    tmpMtx0->setData(inV1->rowBuf(i));
    tmpRow2->setData(outV->rowBuf(i));
170

171 172 173 174 175 176
    BufferArgs inputs;
    BufferArgs outputs;
    inputs.addArg(*tmpMtx0);
    inputs.addArg(*tmpRow0);
    outputs.addArg(*tmpRow2, ASSIGN_TO);
    forward_[0]->calc(inputs, outputs);
Z
zhangjinchao01 已提交
177 178 179 180
  }
}

void CosSimVecMatLayer::backward(const UpdateCallback& callback) {
181 182
  CHECK_EQ(backward_.size(), 1) << "Only one forward function needed";

Z
zhangjinchao01 已提交
183 184 185 186 187 188 189 190
  MatrixPtr inV0 = getInputValue(0);
  MatrixPtr inV1 = getInputValue(1);
  MatrixPtr inG0 = getInputGrad(0);
  MatrixPtr inG1 = getInputGrad(1);
  MatrixPtr outV = getOutputValue();
  MatrixPtr outG = getOutputGrad();

  size_t batchSize = inV0->getHeight();
191
  CHECK(inV0 && inV1 && inG0 && inG1 && outV && outG);
Z
zhangjinchao01 已提交
192 193
  REGISTER_TIMER_INFO("BwCosVMTimer", getName().c_str());

194 195 196 197 198 199 200 201
  for (size_t i = 0; i < batchSize; i++) {
    tmpRow0->setData(inV0->rowBuf(i));
    tmpRow1->setData(inG0->rowBuf(i));
    tmpMtx0->setData(inV1->rowBuf(i));
    tmpMtx1->setData(inG1->rowBuf(i));
    tmpRow2->setData(outV->rowBuf(i));
    tmpRow3->setData(outG->rowBuf(i));

202 203 204 205 206 207 208 209 210 211
    BufferArgs inputs;
    BufferArgs outputs;
    inputs.addArg(*tmpRow3);
    inputs.addArg(*tmpRow2);
    inputs.addArg(*tmpMtx0);
    inputs.addArg(*tmpRow0);
    outputs.addArg(*tmpMtx1, ADD_TO);
    outputs.addArg(*tmpRow1, ADD_TO);

    backward_[0]->calc(inputs, outputs);
Z
zhangjinchao01 已提交
212 213 214 215
  }
}

}  // namespace paddle