ContextProjection.cpp 9.1 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 15

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 "ContextProjection.h"
Y
Yu Yang 已提交
16
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
17 18 19 20 21 22

namespace paddle {

REGISTER_PROJECTION(context, ContextProjection);

ContextProjection::ContextProjection(const ProjectionConfig& config,
23 24
                                     ParameterPtr parameter,
                                     bool useGpu)
Z
zhangjinchao01 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    : Projection(config, parameter, useGpu) {
  CHECK(config.has_context_start());
  CHECK(config.has_context_length());
  if (config.context_start() == 0 && config.context_length() == 1) {
    config_.set_trainable_padding(false);
  }
  if (config_.trainable_padding()) {
    CHECK(parameter);
    beginPad_ = std::max(0, -config.context_start());
    endPad_ = std::max(0, config.context_start() + config.context_length() - 1);
    size_t totalPad = beginPad_ + endPad_;
    size_t inputDim = parameter->getSize() / totalPad;
    CHECK_EQ(config.input_size(), inputDim);
    CHECK_EQ(inputDim * totalPad, parameter->getSize());
    weight_.reset(new Weight(totalPad, inputDim, parameter));
  }
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
  // init forward_ and backward_ functions
  init();
}

bool ContextProjection::init() {
  size_t context_length = config_.context_length();
  int context_start = config_.context_start();
  bool is_padding = config_.trainable_padding();
  size_t total_pad = is_padding ? beginPad_ + endPad_ : 0;
  if (!useGpu_) {  // CPU functions
    createFunction(forward_,
                   "ContextProjectionForward-CPU",
                   FuncConfig()
                       .set("context_length", context_length)
                       .set("context_start", context_start)
                       .set("begin_pad", beginPad_)
                       .set("is_padding", is_padding));
    createFunction(backward_,
                   "ContextProjectionBackward-CPU",
                   FuncConfig()
                       .set("context_length", context_length)
                       .set("context_start", context_start)
                       .set("begin_pad", beginPad_)
                       .set("is_padding", is_padding));
  } else {  // GPU functions
    createFunction(forward_,
                   "ContextProjectionForward-GPU",
                   FuncConfig()
                       .set("context_length", context_length)
                       .set("context_start", context_start)
                       .set("begin_pad", beginPad_)
                       .set("is_padding", is_padding));
    createFunction(backward_,
                   "ContextProjectionBackwardData-GPU",
                   FuncConfig()
                       .set("context_length", context_length)
                       .set("context_start", context_start));

    createFunction(backward_,
                   "ContextProjectionBackwardWeight-GPU",
                   FuncConfig()
                       .set("context_length", context_length)
                       .set("context_start", context_start)
                       .set("begin_pad", beginPad_)
                       .set("total_pad", total_pad));
  }
  return true;
Z
zhangjinchao01 已提交
88 89 90 91 92 93
}

void ContextProjection::resetState() {
  CHECK_LE(config_.context_start() + config_.context_length(), 1)
      << "state is not allowed for future context";
  if (config_.context_start() >= 0) return;
94 95 96
  Matrix::resizeOrCreate(state_,
                         -config_.context_start(),
                         config_.input_size(),
Z
zhangjinchao01 已提交
97 98
                         false,  // trans
                         useGpu_);
99 100
  Matrix::resizeOrCreate(state2_,
                         -config_.context_start(),
Z
zhangjinchao01 已提交
101 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
                         config_.input_size(),
                         false,  // trans
                         useGpu_);
  if (config_.trainable_padding()) {
    state_->assign(*weight_->getW()->subMatrix(0, -config_.context_start()));
  } else {
    state_->zeroMem();
  }
}

void ContextProjection::setState(LayerStatePtr state) {
  CHECK(state->value.size() == 1)
      << "one matrix is expected for ContextProjection state";
  state_->copyFrom(*(state->value[0]));
}

LayerStatePtr ContextProjection::getState() {
  if (state_ == nullptr) {
    return nullptr;
  }
  LayerStatePtr res = std::make_shared<LayerState>();
  res->value.push_back(state_->clone(0, 0, false));
  res->value[0]->copyFrom(*state_);
  return res;
}

void ContextProjection::forward() {
128
  CHECK(in_->value && out_->value);
Z
zhangjinchao01 已提交
129 130
  CHECK(in_->sequenceStartPositions);

131 132 133 134 135
  size_t input_dim = in_->value->getWidth();
  size_t dim = out_->value->getWidth();
  CHECK_EQ(dim, input_dim * config_.context_length());
  size_t batch_size = in_->value->getHeight();
  CHECK_EQ(batch_size, out_->value->getHeight());
Z
zhangjinchao01 已提交
136 137

  REGISTER_TIMER_INFO("ContextProjectionForward", getName().c_str());
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  bool is_padding = config_.trainable_padding();
  /// first use state_, otherwise use weight_(padding false === w nullptr)
  auto w_ptr =
      state_ ? state_.get() : is_padding ? weight_->getW().get() : nullptr;
  auto start_pos = in_->sequenceStartPositions;
  /// if use state_ as weight_, w_ptr already has mem, so padding true
  forward_[0]->init(FuncConfig()
                        .set("context_length", config_.context_length())
                        .set("context_start", config_.context_start())
                        .set("begin_pad", beginPad_)
                        .set("is_padding", state_ ? true : is_padding));
  forward_[0]->calc({Tensor(in_->value->getData(), Dims{batch_size, input_dim}),
                     Tensor(w_ptr ? w_ptr->getData() : nullptr,
                            Dims{w_ptr ? w_ptr->getHeight() : 0, input_dim}),
                     Tensor(reinterpret_cast<real*>(
                                const_cast<int*>(start_pos->getData(useGpu_))),
                            Dims{start_pos->getSize()})},
                    {Tensor(out_->value->getData(), Dims{batch_size, dim})},
                    {});
Z
zhangjinchao01 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

  if (state_ && config_.context_start() < 0) {
    CHECK_EQ(1, in_->getNumSequences());
    const int* starts = in_->sequenceStartPositions->getData(false);
    int length = starts[1] - starts[0];
    if (-config_.context_start() <= length) {
      MatrixPtr sub = in_->value->subMatrix(starts[1] + config_.context_start(),
                                            -config_.context_start());
      state_->copyFrom(*sub);
    } else {
      int prevLength = -config_.context_start() - length;
      state2_->subMatrix(0, prevLength)
          ->copyFrom(*state_->subMatrix(length, prevLength));
      state2_->subMatrix(prevLength, length)
          ->copyFrom(*in_->value->subMatrix(starts[0], length));
      std::swap(state_, state2_);
    }
  }
}

void ContextProjection::backward(const UpdateCallback& callback) {
178 179 180 181 182 183
  CHECK(in_->value && out_->value && out_->grad);
  size_t input_dim = in_->value->getWidth();
  size_t dim = out_->value->getWidth();
  CHECK_EQ(dim, input_dim * config_.context_length());
  size_t batch_size = in_->value->getHeight();
  CHECK_EQ(batch_size, out_->value->getHeight());
Z
zhangjinchao01 已提交
184 185

  REGISTER_TIMER_INFO("ContextProjectionBackward", getName().c_str());
186 187
  bool is_padding = config_.trainable_padding();
  auto start_pos = in_->sequenceStartPositions;
Z
zhangjinchao01 已提交
188
  if (!out_->grad->useGpu()) {
189 190 191 192 193 194 195 196 197 198
    auto w_ptr = is_padding ? weight_->getWGrad() : nullptr;
    backward_[0]->calc({Tensor(in_->grad ? in_->grad->getData() : nullptr,
                               Dims{batch_size, input_dim}),
                        Tensor(w_ptr ? w_ptr->getData() : nullptr,
                               Dims{w_ptr ? w_ptr->getHeight() : 0, input_dim}),
                        Tensor(reinterpret_cast<real*>(const_cast<int*>(
                                   start_pos->getData(useGpu_))),
                               Dims{start_pos->getSize()})},
                       {Tensor(out_->grad->getData(), Dims{batch_size, dim})},
                       {});
Z
zhangjinchao01 已提交
199 200
  } else {
    if (in_->grad) {
201 202 203 204 205 206 207
      backward_[0]->calc(
          {Tensor(in_->grad->getData(), Dims{batch_size, input_dim}),
           Tensor(reinterpret_cast<real*>(
                      const_cast<int*>(start_pos->getData(useGpu_))),
                  Dims{start_pos->getSize()})},
          {Tensor(out_->grad->getData(), Dims{batch_size, dim})},
          {});
Z
zhangjinchao01 已提交
208
    }
209 210 211 212 213 214 215 216 217
    if (is_padding && weight_->getWGrad()) {
      backward_[1]->calc(
          {Tensor(weight_->getWGrad()->getData(),
                  Dims{weight_->getWGrad()->getHeight(), input_dim}),
           Tensor(reinterpret_cast<real*>(
                      const_cast<int*>(start_pos->getData(useGpu_))),
                  Dims{start_pos->getSize()})},
          {Tensor(out_->grad->getData(), Dims{batch_size, dim})},
          {});
Z
zhangjinchao01 已提交
218 219 220 221 222 223 224 225 226
    }
  }

  if (config_.trainable_padding()) {
    weight_->getParameterPtr()->incUpdate(callback);
  }
}

}  // namespace paddle