partial_concat_op.h 4.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
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

#include <string>
#include <utility>
#include <vector>
17

18 19 20 21 22 23 24 25 26 27 28
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/concat_and_split.h"
#include "paddle/fluid/operators/strided_memcpy.h"
#include "paddle/fluid/operators/utils.h"

namespace paddle {
namespace operators {
using Tensor = framework::Tensor;

static inline int64_t ComputeStartIndex(int64_t start_index, int64_t size) {
  PADDLE_ENFORCE_EQ(
29 30
      start_index >= -size && start_index < size,
      true,
31 32
      platform::errors::InvalidArgument(
          "The start_index is expected to be in range of [%d, %d), but got %d",
33 34 35
          -size,
          size,
          start_index));
36 37 38 39 40 41 42 43 44 45 46 47
  if (start_index < 0) {
    start_index += size;
  }
  return start_index;
}

template <typename DeviceContext, typename T>
class PartialConcatKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto ins = ctx.MultiInput<framework::Tensor>("X");
    framework::Tensor* out = ctx.Output<framework::Tensor>("Out");
48 49
    PADDLE_ENFORCE_EQ(ins[0] != nullptr,
                      true,
50 51 52 53
                      platform::errors::InvalidArgument(
                          "The input of partial concat should not be null."));

    auto input_dim = ins[0]->dims();
54 55
    PADDLE_ENFORCE_EQ(input_dim.size(),
                      2,
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
                      platform::errors::InvalidArgument(
                          "Only supports 2-D array with batch size in the 1st "
                          "dimension and data in the 2nd."));
    auto in_size = input_dim[1];

    // may be negative
    auto start_index = ctx.Attr<int>("start_index");
    start_index = ComputeStartIndex(start_index, in_size);

    auto partial_len = ctx.Attr<int>("length");
    if (partial_len < 0) {
      partial_len = in_size - start_index;
    }

    int batch = input_dim[0];
    int out_size = partial_len * ins.size();
    out->Resize({batch, out_size});
    auto place = ctx.GetPlace();
    T* out_data = out->mutable_data<T>(place);

    for (size_t i = 0; i < ins.size(); ++i) {
      for (int j = 0; j < batch; ++j) {
        const T* in_data = ins[i]->data<T>();
        memcpy(out_data + out_size * j + partial_len * i,
80 81
               in_data + in_size * j + start_index,
               partial_len * sizeof(T));
82 83 84 85 86 87 88 89 90 91 92 93 94 95
      }
    }
  }
};

template <typename T>
class PartialConcatGradientOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto ins = ctx.MultiInput<framework::LoDTensor>("X");
    auto outs =
        ctx.MultiOutput<framework::LoDTensor>(framework::GradVarName("X"));

96 97
    PADDLE_ENFORCE_EQ(ins[0] != nullptr,
                      true,
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
                      platform::errors::InvalidArgument(
                          "The input of partial concat should not be null."));
    // all parameters
    auto batch_size = ins[0]->dims()[0];
    auto in_size = ins[0]->dims()[1];
    // may be negative
    auto start_index = ctx.Attr<int>("start_index");
    start_index = ComputeStartIndex(start_index, in_size);
    auto partial_len = ctx.Attr<int>("length");
    if (partial_len < 0) partial_len = in_size - start_index;

    auto in_num = ins.size();
    auto grad_batch_len = partial_len * in_num;
    auto all_length = grad_batch_len * batch_size;

    // initialize
L
Leo Chen 已提交
114 115
    auto& place =
        *ctx.template device_context<phi::CPUContext>().eigen_device();
116 117 118 119 120 121 122 123 124 125 126 127
    for (size_t i = 0; i < outs.size(); ++i) {
      outs[i]->mutable_data<T>(ctx.GetPlace());
      auto dxt = framework::EigenVector<T>::Flatten(*outs[i]);
      dxt.device(place) = dxt.constant(static_cast<T>(0));
    }

    auto* out_grad_t = out_grad->data<T>();
    for (size_t id = 0; id < all_length; id += partial_len) {
      int bs_id = id / grad_batch_len;
      int bs_index = id % grad_batch_len;
      int var_id = bs_index / partial_len;
      auto* out_t = outs[var_id]->data<T>();
128 129
      memcpy(out_t + bs_id * in_size + start_index,
             out_grad_t + id,
130 131 132 133 134 135 136
             partial_len * sizeof(T));
    }
  }
};

}  // namespace operators
}  // namespace paddle