sequence_scatter_op.h 5.8 KB
Newer Older
Q
Qingsheng Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2018 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 "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
18
#include "paddle/phi/kernels/funcs/scatter.h"
Q
Qingsheng Li 已提交
19 20 21 22

namespace paddle {
namespace operators {

23
using Tensor = phi::DenseTensor;
24
using LoDTensor = phi::DenseTensor;
Q
Qingsheng Li 已提交
25

H
huangjiyi 已提交
26
template <typename T, typename DeviceContext>
Q
Qingsheng Li 已提交
27 28 29
class SequenceScatterOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
30
    auto* x = ctx.Input<phi::DenseTensor>("X");
Q
Qingsheng Li 已提交
31 32
    auto* ids = ctx.Input<LoDTensor>("Ids");
    auto* updates = ctx.Input<LoDTensor>("Updates");
33
    auto* out = ctx.Output<phi::DenseTensor>("Out");
Q
Qingsheng Li 已提交
34 35

    auto& ids_lod = ids->lod();
36 37
    PADDLE_ENFORCE_EQ(ids_lod.empty(),
                      false,
38 39 40
                      platform::errors::InvalidArgument(
                          "Input(Ids) Tensor of SequenceScatter operator does "
                          "not contain LoD information."));
Q
Qingsheng Li 已提交
41 42 43 44 45 46 47 48 49

    // Initialize out as same as x
    out->mutable_data<T>(ctx.GetPlace());
    framework::TensorCopySync(*x, ctx.GetPlace(), out);

    auto x_dims = x->dims();
    auto out_dims = out->dims();

    for (int i = 0; i < x_dims.size(); ++i)
50 51
      PADDLE_ENFORCE_EQ(x_dims[i],
                        out_dims[i],
52 53 54 55
                        platform::errors::InvalidArgument(
                            "Input(X) and output(Out) shape of SequenceScatter "
                            "operator do not match. Received input(X)'s shape "
                            "is [%s], output(Out)'s shape is [%s].",
56 57
                            x_dims,
                            out_dims));
Q
Qingsheng Li 已提交
58 59 60 61 62 63 64

    size_t slice_size = 1;
    for (int i = 1; i < x_dims.size(); ++i) slice_size *= x_dims[i];

    auto lod_vec = ids_lod[0];
    unsigned int seg = 0;
    for (int i = 0; i < ids->dims()[0]; ++i) {
65
      PADDLE_ENFORCE_LT(
66 67
          seg,
          lod_vec.size() - 1,
68 69 70 71
          platform::errors::OutOfRange("The segment index is out of bound in "
                                       "SequenceScatter operator, it must be "
                                       "less than batch size. The segment "
                                       "index is %d, the batch size is %d.",
72 73
                                       seg,
                                       lod_vec.size()));
Q
Qingsheng Li 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
      int lower_bound = lod_vec[seg];
      int upper_bound = lod_vec[seg + 1];
      if (i >= lower_bound && i < upper_bound) {
        T* p_out = out->data<T>();
        const T* p_updates = updates->data<T>();
        const int64_t* p_index = ids->data<int64_t>();
        p_out[seg * slice_size + p_index[i]] += p_updates[i];
      } else {
        ++seg;
        --i;
      }
    }
  }
};

H
huangjiyi 已提交
89
template <typename T, typename DeviceContext>
Q
Qingsheng Li 已提交
90 91 92
class SequenceScatterGradientOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
93
    PADDLE_ENFORCE_EQ(
94 95
        platform::is_cpu_place(ctx.GetPlace()),
        true,
96 97 98
        platform::errors::Unimplemented("Device dose not match. The "
                                        "SequenceScatterGradientOpKernel can "
                                        "only run on CPU device."));
99
    auto* dX = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
Q
Qingsheng Li 已提交
100 101
    auto* dUpdates = ctx.Output<LoDTensor>(framework::GradVarName("Updates"));
    auto* ids = ctx.Input<LoDTensor>("Ids");
102
    auto* dOut = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
Q
Qingsheng Li 已提交
103 104 105 106 107 108 109 110 111 112 113

    auto& ids_lod = ids->lod();

    dX->mutable_data<T>(ctx.GetPlace());
    framework::TensorCopySync(*dOut, ctx.GetPlace(), dX);
    dUpdates->mutable_data<T>(ctx.GetPlace());

    auto dx_dims = dX->dims();
    auto dout_dims = dOut->dims();

    for (int i = 0; i < dx_dims.size(); ++i)
114 115
      PADDLE_ENFORCE_EQ(dx_dims[i],
                        dout_dims[i],
116 117 118 119 120
                        platform::errors::InvalidArgument(
                            "Input(Out@GRAD) and output(X@GRAD) shape of "
                            "SequenceScatterGradient operator do not match. "
                            "Received input(Out@GRAD)'s shape is [%s], "
                            "output(X@GRAD)'s shape is [%s].",
121 122
                            dout_dims,
                            dx_dims));
Q
Qingsheng Li 已提交
123 124 125 126 127 128 129 130

    size_t slice_size = 1;
    for (int i = 1; i < dx_dims.size(); ++i) slice_size *= dx_dims[i];

    auto lod_vec = ids_lod[0];
    unsigned int seg = 0;

    for (int i = 0; i < ids->dims()[0]; ++i) {
131
      PADDLE_ENFORCE_LT(
132 133
          seg,
          lod_vec.size() - 1,
134 135 136 137
          platform::errors::OutOfRange(
              "The segment index is out of bound in SequenceScatterGradient "
              "operator, it must be less than batch size. The segment index is "
              "%d, the batch size is %d.",
138 139
              seg,
              lod_vec.size()));
Q
Qingsheng Li 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      int lower_bound = lod_vec[seg];
      int upper_bound = lod_vec[seg + 1];
      if (i >= lower_bound && i < upper_bound) {
        const T* p_dOut = dOut->data<T>();
        const int64_t* p_index = ids->data<int64_t>();
        T* p_dUpdates = dUpdates->data<T>();
        p_dUpdates[i] = p_dOut[seg * slice_size + p_index[i]];
      } else {
        ++seg;
        --i;
      }
    }
  }
};
}  // namespace operators
}  // namespace paddle