sum_op.h 5.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12
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. */

#pragma once
13
#include <vector>
Y
Yi Wang 已提交
14 15 16 17 18
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
19 20 21 22 23

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
Q
QI JUN 已提交
24 25
using SelectedRows = framework::SelectedRows;
using LoDTensor = framework::LoDTensor;
26 27 28 29
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;

Q
QI JUN 已提交
30
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
31
class SumKernel : public framework::OpKernel<T> {
32
 public:
33
  void Compute(const framework::ExecutionContext &context) const override {
Y
Yu Yang 已提交
34
    auto in_vars = context.MultiInputVar("X");
35
    size_t in_num = in_vars.size();
Q
QI JUN 已提交
36 37
    auto out_var = context.OutputVar("Out");

Y
Yu Yang 已提交
38 39
    bool in_place = out_var == in_vars[0];

Q
QI JUN 已提交
40
    if (out_var->IsType<framework::LoDTensor>()) {
Y
Update  
Yang Yu 已提交
41
      auto *out = context.Output<LoDTensor>("Out");
Y
Yu Yang 已提交
42
      if (!in_place) {
Y
Refine  
Yang Yu 已提交
43
        out->mutable_data<T>(context.GetPlace());
Y
Update  
Yang Yu 已提交
44 45 46
      }
      auto result = EigenVector<T>::Flatten(*out);
      if (!in_place) {
Q
QI JUN 已提交
47 48
        math::SetConstant<DeviceContext, T> constant_functor;
        constant_functor(context.template device_context<DeviceContext>(), out,
49
                         0.0);
Y
Yu Yang 已提交
50
      }
Q
QI JUN 已提交
51

Q
QI JUN 已提交
52 53 54
      math::SelectedRowsAddToTensor<DeviceContext, T> functor;
      auto &place =
          *context.template device_context<DeviceContext>().eigen_device();
Y
Yu Yang 已提交
55
      // If in_place, just skip the first tensor
56
      for (size_t i = in_place ? 1 : 0; i < in_num; i++) {
Q
QI JUN 已提交
57
        if (in_vars[i]->IsType<framework::LoDTensor>()) {
58
          auto &in_t = in_vars[i]->Get<framework::LoDTensor>();
59 60 61
          if (in_t.numel() == 0) {
            continue;
          }
Q
QI JUN 已提交
62 63 64
          auto in = EigenVector<T>::Flatten(in_t);
          result.device(place) = result + in;
        } else if (in_vars[i]->IsType<framework::SelectedRows>()) {
65
          auto &in_t = in_vars[i]->Get<framework::SelectedRows>();
Q
QI JUN 已提交
66
          functor(context.template device_context<DeviceContext>(), in_t, out);
Q
QI JUN 已提交
67 68 69 70 71
        } else {
          PADDLE_THROW("Variable type must be LoDTensor/SelectedRows.");
        }
      }
    } else if (out_var->IsType<framework::SelectedRows>()) {
Q
Qiao Longfei 已提交
72 73 74
      if (in_place && in_vars.size() < 2) {
        return;
      }
T
tangwei12 已提交
75

Q
qiaolongfei 已提交
76
      std::vector<const paddle::framework::SelectedRows *> inputs;
Q
Qiao Longfei 已提交
77
      SelectedRows temp_in0;
T
tangwei12 已提交
78

Q
Qiao Longfei 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
      if (in_place) {
        auto &in0 = in_vars[0]->Get<SelectedRows>();
        temp_in0.set_height(in0.height());
        temp_in0.set_rows(in0.rows());
        framework::TensorCopy(in0.value(), in0.place(),
                              context.device_context(),
                              temp_in0.mutable_value());
        inputs.push_back(&temp_in0);
        for (size_t i = 1; i < in_vars.size(); ++i) {
          inputs.push_back(&in_vars[i]->Get<SelectedRows>());
        }
      } else {
        for (auto &in_var : in_vars) {
          inputs.push_back(&in_var->Get<SelectedRows>());
        }
94
      }
Q
QI JUN 已提交
95

Q
Qiao Longfei 已提交
96 97 98
      auto *out = context.Output<SelectedRows>("Out");
      out->mutable_rows()->clear();

Q
qiaolongfei 已提交
99 100
      math::scatter::MergeAdd<DeviceContext, T> merge_add;
      merge_add(context.template device_context<DeviceContext>(), inputs, out);
101 102 103 104 105 106 107 108 109 110 111 112 113
    } else if (out_var->IsType<framework::LoDTensorArray>()) {
      auto &out_array = *out_var->GetMutable<framework::LoDTensorArray>();
      for (size_t i = in_place ? 1 : 0; i < in_vars.size(); ++i) {
        PADDLE_ENFORCE(in_vars[i]->IsType<framework::LoDTensorArray>(),
                       "Only support all inputs are TensorArray");
        auto &in_array = in_vars[i]->Get<framework::LoDTensorArray>();

        for (size_t i = 0; i < in_array.size(); ++i) {
          if (in_array[i].numel() != 0) {
            if (i >= out_array.size()) {
              out_array.resize(i + 1);
            }
            if (out_array[i].numel() == 0) {
Y
Yi Wang 已提交
114 115
              framework::TensorCopy(in_array[i], in_array[i].place(),
                                    context.device_context(), &out_array[i]);
116 117 118 119 120
              out_array[i].set_lod(in_array[i].lod());
            } else {
              PADDLE_ENFORCE(out_array[i].lod() == in_array[i].lod());
              auto in = EigenVector<T>::Flatten(in_array[i]);
              auto result = EigenVector<T>::Flatten(out_array[i]);
Q
QI JUN 已提交
121 122
              result.device(*context.template device_context<DeviceContext>()
                                 .eigen_device()) = result + in;
123 124 125 126 127 128 129
            }
          }
        }
      }
    } else {
      PADDLE_THROW("Unexpected branch, output variable type is %s",
                   out_var->Type().name());
130 131 132 133 134
    }
  }
};
}  // namespace operators
}  // namespace paddle