feed_op.cc 9.9 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
  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]);
124 125 126
      framework::Variable* out_var =
          PADDLE_GET(framework::Variable*, ctx->GetOutputVarPtrs("Out")[0]);

127 128
      auto& x = x_var->Get<framework::FeedList>();
      int col = ctx->Attrs().Get<int>("col");
129 130 131
      const auto& feed_item = CheckAndGetFeedItem(x, col);

      if (feed_item.index() == 0) {  // DenseTensor
132
        auto& feed_tensor = PADDLE_GET_CONST(phi::DenseTensor, feed_item);
133 134 135 136 137 138 139 140
        phi::DenseTensor* out_tensor = out_var->GetMutable<phi::DenseTensor>();
        phi::DenseTensorMeta meta = out_tensor->meta();
        meta.dims = feed_tensor.dims();
        meta.dtype = feed_tensor.dtype();
        meta.layout = feed_tensor.layout();
        meta.lod = feed_tensor.lod();
        out_tensor->set_meta(meta);
      } else if (feed_item.index() == 1) {  // Strings
141 142
        auto& feed_str = PADDLE_GET_CONST(framework::Strings, feed_item);
        out_var->GetMutable<framework::Strings>()->resize(feed_str.size());
143
      } else if (feed_item.index() == 2) {  // SparseCooTensor
144 145 146 147 148 149 150 151
        auto& feed_sparse_tensor =
            PADDLE_GET_CONST(phi::SparseCooTensor, feed_item);
        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());
152 153 154 155
      } else {
        PADDLE_THROW(
            phi::errors::Unimplemented("Only support DenseTnesor, Strings, and "
                                       "SparseCooTensor for feed op now."));
156
      }
157 158 159
    }
  }

160 161 162
 protected:
  phi::KernelKey GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    const framework::Variable* x_var = ctx.InputVar("X");
    auto& x = x_var->Get<framework::FeedList>();
    int col = ctx.Attr<int>("col");
    auto& feed_item = x[col];

    framework::proto::VarType::Type expected_data_type;
    if (feed_item.index() == 0) {  // DenseTensor
      expected_data_type = framework::TransToProtoVarType(
          PADDLE_GET_CONST(phi::DenseTensor, feed_item).dtype());
    } else if (feed_item.index() == 2) {  // SparseCooTensor
      expected_data_type = framework::TransToProtoVarType(
          PADDLE_GET_CONST(phi::SparseCooTensor, feed_item).dtype());
    } else {  // Strings
      expected_data_type = framework::proto::VarType::FP32;
    }

    return phi::KernelKey(expected_data_type, ctx.GetPlace());
Q
qijun 已提交
180 181 182
  }
};

Y
Yu Yang 已提交
183 184
class FeedOpInfoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
185
  void Make() override {
186
    AddInput("X",
187 188
             "(vector<phi::DenseTensor>) "
             "A feeding list of phi::DenseTensor, which may have "
189 190
             "different dimension and data type.");
    AddOutput("Out",
191
              "(phi::DenseTensor) The phi::DenseTensor which is a copy "
S
Steffy-zxf 已提交
192
              "of the col-th feeding "
193 194
              "object.");
    AddAttr<int>("col", "(int) The column index of current feeding object.");
K
kexinzhao 已提交
195 196 197 198
    AddComment(R"DOC(
Feed Operator.
It should not be configured by users directly.
)DOC");
Y
Yu Yang 已提交
199 200 201
  }
};

Q
qijun 已提交
202 203 204
}  // namespace operators
}  // namespace paddle

205 206 207
// TODO(YuanRisheng): Maybe we need design a new registry macro for
// registering device independent kernels.

H
hong 已提交
208
REGISTER_OPERATOR(
209 210
    feed,
    paddle::operators::FeedOp,
H
hong 已提交
211 212 213
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
    paddle::operators::FeedOpInfoMaker);
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

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) {}
274 275
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
276 277 278 279 280 281 282 283 284 285 286 287
PD_REGISTER_GENERAL_KERNEL(
    feed_dense_tensor,
    Custom,
    ALL_LAYOUT,
    paddle::operators::FeedDenseTensorKernel<phi::CustomContext>,
    ALL_DTYPE) {}
PD_REGISTER_GENERAL_KERNEL(
    feed_strings,
    Custom,
    ALL_LAYOUT,
    paddle::operators::FeedStringsKernel<phi::CustomContext>,
    ALL_DTYPE) {}
288
#endif