feed_op.cc 8.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
Luo Tao 已提交
2 3 4 5 6 7 8 9 10
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. */
Q
qijun 已提交
11

Y
Yi Wang 已提交
12 13
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
14 15
#include "paddle/fluid/framework/raw_tensor.h"
#include "paddle/phi/core/kernel_registry.h"
16
#include "paddle/phi/core/tensor_utils.h"
Q
qijun 已提交
17

W
wanghuancoder 已提交
18 19 20 21 22 23 24 25 26 27 28 29
namespace paddle {
namespace framework {
class OpDesc;
class Scope;
template <typename T>
class EmptyGradOpMaker;
}  // namespace framework
namespace imperative {
class OpBase;
}  // namespace imperative
}  // namespace paddle

Q
qijun 已提交
30 31
namespace paddle {
namespace operators {
S
Steffy-zxf 已提交
32

33 34 35 36 37 38 39 40 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
const framework::FeedType& CheckAndGetFeedItem(const phi::ExtendedTensor& x,
                                               int col) {
  PADDLE_ENFORCE_GE(col,
                    0,
                    platform::errors::InvalidArgument(
                        "Expected the column index (the attribute 'col' of "
                        "operator 'Feed') of current feeding variable to be "
                        "no less than 0. But received column index = %d.",
                        col));
  auto feed_list = static_cast<const paddle::framework::FeedList*>(&x);
  PADDLE_ENFORCE_LT(
      static_cast<size_t>(col),
      feed_list->size(),
      platform::errors::InvalidArgument(
          "The column index of current feeding variable is expected to be "
          "less than the length of feeding list. But received column index = "
          "%d, the length of feeding list = %d",
          col,
          feed_list->size()));

  return feed_list->at(static_cast<size_t>(col));
}

template <typename Context>
void FeedDenseTensorKernel(const Context& dev_ctx,
                           const phi::ExtendedTensor& x,
                           int col,
                           phi::DenseTensor* out) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      platform::errors::NotFound(
          "Output cannot be found in scope for operator 'Feed'"));
  const auto& feed_item = CheckAndGetFeedItem(x, col);
  const auto& in_tensor = paddle::get<phi::DenseTensor>(feed_item);
  const auto& place = dev_ctx.GetPlace();
  if (platform::is_same_place(in_tensor.place(), place)) {
    out->ShareDataWith(in_tensor);
  } else {
    framework::TensorCopy(in_tensor, place, dev_ctx, out);
S
Steffy-zxf 已提交
72 73
  }

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  out->set_lod(in_tensor.lod());
}

template <typename Context>
void FeedSparseCooTensorKernel(const Context& dev_ctx,
                               const phi::ExtendedTensor& x,
                               int col,
                               phi::SparseCooTensor* out) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      platform::errors::NotFound(
          "Output cannot be found in scope for operator 'Feed'"));
  const auto& feed_item = CheckAndGetFeedItem(x, col);
  const auto& in_tensor = paddle::get<phi::SparseCooTensor>(feed_item);
  const auto& place = dev_ctx.GetPlace();
  if (platform::is_same_place(in_tensor.place(), place)) {
    *out = in_tensor;
  } else {
    phi::DenseTensor indices, values;
    framework::TensorCopy(in_tensor.indices(), place, dev_ctx, &indices);
    framework::TensorCopy(in_tensor.values(), place, dev_ctx, &values);
    out->SetMember(indices, values, in_tensor.meta());
S
Steffy-zxf 已提交
96
  }
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
}

template <typename Context>
void FeedStringsKernel(const Context& dev_ctx,
                       const phi::ExtendedTensor& x,
                       int col,
                       phi::ExtendedTensor* out) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      platform::errors::NotFound(
          "Output cannot be found in scope for operator 'Feed'"));
  const auto& feed_item = CheckAndGetFeedItem(x, col);
  auto strs_out = static_cast<framework::Strings*>(out);
  const auto& in_str = paddle::get<framework::Strings>(feed_item);
  strs_out->resize(in_str.size());
  *strs_out = in_str;
}

class FeedOp : public framework::OperatorWithKernel {
  using framework::OperatorWithKernel::OperatorWithKernel;
S
Steffy-zxf 已提交
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "feed");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "feed");
    if (ctx->IsRuntime()) {
      framework::Variable* x_var =
          PADDLE_GET(framework::Variable*, ctx->GetInputVarPtrs("X")[0]);
      auto& x = x_var->Get<framework::FeedList>();
      int col = ctx->Attrs().Get<int>("col");
      auto& feed_item = x[col];
      if (feed_item.index() == 0) {
        const auto& feed_item = CheckAndGetFeedItem(x, col);
        auto& feed_tensor = PADDLE_GET_CONST(phi::DenseTensor, feed_item);
        ctx->SetOutputDim("Out", feed_tensor.dims());
      } else if (feed_item.index() == 1) {
        auto& feed_str = PADDLE_GET_CONST(framework::Strings, feed_item);
        framework::Variable* out_var =
            PADDLE_GET(framework::Variable*, ctx->GetOutputVarPtrs("Out")[0]);
        out_var->GetMutable<framework::Strings>()->resize(feed_str.size());
      } else {
        auto& feed_sparse_tensor =
            PADDLE_GET_CONST(phi::SparseCooTensor, feed_item);
        framework::Variable* out_var =
            PADDLE_GET(framework::Variable*, ctx->GetOutputVarPtrs("Out")[0]);
        out_var->GetMutable<phi::SparseCooTensor>()->set_meta(
            feed_sparse_tensor.meta());
        out_var->GetMutable<phi::SparseCooTensor>()->SetCoalesced(
            feed_sparse_tensor.coalesced());
        out_var->GetMutable<phi::SparseCooTensor>()->SetIndicesDict(
            feed_sparse_tensor.GetIndicesDict());
      }
148 149 150
    }
  }

151 152 153 154
 protected:
  phi::KernelKey GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return phi::KernelKey(framework::proto::VarType::FP32, ctx.GetPlace());
Q
qijun 已提交
155 156 157
  }
};

Y
Yu Yang 已提交
158 159
class FeedOpInfoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
160
  void Make() override {
161
    AddInput("X",
162 163
             "(vector<phi::DenseTensor>) "
             "A feeding list of phi::DenseTensor, which may have "
164 165
             "different dimension and data type.");
    AddOutput("Out",
166
              "(phi::DenseTensor) The phi::DenseTensor which is a copy "
S
Steffy-zxf 已提交
167
              "of the col-th feeding "
168 169
              "object.");
    AddAttr<int>("col", "(int) The column index of current feeding object.");
K
kexinzhao 已提交
170 171 172 173
    AddComment(R"DOC(
Feed Operator.
It should not be configured by users directly.
)DOC");
Y
Yu Yang 已提交
174 175 176
  }
};

Q
qijun 已提交
177 178 179
}  // namespace operators
}  // namespace paddle

180 181 182
// TODO(YuanRisheng): Maybe we need design a new registry macro for
// registering device independent kernels.

H
hong 已提交
183
REGISTER_OPERATOR(
184 185
    feed,
    paddle::operators::FeedOp,
H
hong 已提交
186 187 188
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
    paddle::operators::FeedOpInfoMaker);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

PD_REGISTER_GENERAL_KERNEL(
    feed_dense_tensor,
    CPU,
    ALL_LAYOUT,
    paddle::operators::FeedDenseTensorKernel<phi::CPUContext>,
    ALL_DTYPE) {}

PD_REGISTER_GENERAL_KERNEL(
    feed_sparse_coo_tensor,
    CPU,
    ALL_LAYOUT,
    paddle::operators::FeedSparseCooTensorKernel<phi::CPUContext>,
    ALL_DTYPE) {}

PD_REGISTER_GENERAL_KERNEL(
    feed_strings,
    CPU,
    ALL_LAYOUT,
    paddle::operators::FeedStringsKernel<phi::CPUContext>,
    ALL_DTYPE) {}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
PD_REGISTER_GENERAL_KERNEL(
    feed_dense_tensor,
    GPU,
    ALL_LAYOUT,
    paddle::operators::FeedDenseTensorKernel<phi::GPUContext>,
    ALL_DTYPE) {}
PD_REGISTER_GENERAL_KERNEL(
    feed_sparse_coo_tensor,
    GPU,
    ALL_LAYOUT,
    paddle::operators::FeedSparseCooTensorKernel<phi::GPUContext>,
    ALL_DTYPE) {}
PD_REGISTER_GENERAL_KERNEL(
    feed_strings,
    GPU,
    ALL_LAYOUT,
    paddle::operators::FeedStringsKernel<phi::GPUContext>,
    ALL_DTYPE) {}
#elif defined(PADDLE_WITH_XPU)
PD_REGISTER_GENERAL_KERNEL(
    feed_dense_tensor,
    XPU,
    ALL_LAYOUT,
    paddle::operators::FeedDenseTensorKernel<phi::XPUContext>,
    ALL_DTYPE) {}
PD_REGISTER_GENERAL_KERNEL(
    feed_sparse_coo_tensor,
    XPU,
    ALL_LAYOUT,
    paddle::operators::FeedSparseCooTensorKernel<phi::XPUContext>,
    ALL_DTYPE) {}
PD_REGISTER_GENERAL_KERNEL(
    feed_strings,
    XPU,
    ALL_LAYOUT,
    paddle::operators::FeedStringsKernel<phi::XPUContext>,
    ALL_DTYPE) {}
249 250 251 252 253 254 255 256 257 258 259
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
namespace paddle {
namespace operators {
template void FeedDenseTensorKernel<phi::CustomContext>(
    const phi::CustomContext& dev_ctx,
    const phi::ExtendedTensor& x,
    int col,
    phi::DenseTensor* out);
}  // namespace operators
}  // namespace paddle
260
#endif