fetch_v2_op.cc 9.2 KB
Newer Older
W
wanghuancoder 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* Copyright (c) 2021 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. */

#include <string>

#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace framework {
class OpDesc;
class InferShapeContext;
template <typename T>
class EmptyGradOpMaker;
}  // namespace framework
namespace imperative {
class OpBase;
}  // namespace imperative
}  // namespace paddle

namespace paddle {
namespace operators {

34
static void DeepCopy(const phi::DenseTensor &src_item,
W
wanghuancoder 已提交
35
                     const std::string &fetch_var_name,
36
                     phi::DenseTensor *dst_item) {
W
wanghuancoder 已提交
37 38 39
  if (src_item.IsInitialized() && src_item.numel() > 0) {
#ifdef PADDLE_WITH_MKLDNN
    // Conversion from MKL-DNN to Paddle
40
    if (src_item.layout() == phi::DataLayout::ONEDNN) {
41
      phi::DenseTensor out;
W
wanghuancoder 已提交
42 43
      // Convert to desired Paddle layout, apart from grads of filter
      // as params are not a subject to paddle's data_format
44
      phi::funcs::TransDataLayoutFromOneDNN(
45 46
          src_item.layout(),
          fetch_var_name == framework::GradVarName("Filter")
47
              ? phi::DataLayout::kNCHW
48
              : phi::OneDNNContext::tls().get_cur_paddle_data_layout(),
49 50 51
          src_item,
          &out,
          platform::CPUPlace());
52
      paddle::framework::TensorCopySync(out, platform::CPUPlace(), dst_item);
W
wanghuancoder 已提交
53
    } else {
54 55
      paddle::framework::TensorCopySync(
          src_item, platform::CPUPlace(), dst_item);
W
wanghuancoder 已提交
56 57
    }
#else
58
    paddle::framework::TensorCopySync(src_item, platform::CPUPlace(), dst_item);
W
wanghuancoder 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#endif
  } else {
    // Not copy, if the src tensor is empty.
    dst_item->clear();
    dst_item->Resize({0});
  }
  dst_item->set_lod(src_item.lod());
}

class FetchV2Op : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {}

 protected:
75
  phi::KernelKey GetKernelTypeForVar(
76
      const std::string &var_name,
77
      const phi::DenseTensor &tensor,
78
      const phi::KernelKey &expected_kernel_type) const override {
79
    if (!tensor.IsInitialized()) {
80 81 82
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
83
    }
84 85
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
W
wanghuancoder 已提交
86 87
  }

88
  phi::KernelKey GetExpectedKernelType(
W
wanghuancoder 已提交
89
      const framework::ExecutionContext &ctx) const override {
90 91
    auto *fetch_var = ctx.InputVar("X");
    if (fetch_var == nullptr) {
92 93
      return phi::KernelKey(framework::proto::VarType::FP32,
                            platform::CPUPlace());
94 95
    }

96 97
    if (fetch_var->IsType<phi::DenseTensor>()) {
      auto &src_item = fetch_var->Get<phi::DenseTensor>();
98
      if (!src_item.IsInitialized()) {
99 100
        return phi::KernelKey(framework::proto::VarType::FP32,
                              platform::CPUPlace());
101
      }
102 103 104
    } else if (fetch_var->IsType<phi::SparseCooTensor>()) {
      auto &src_item = fetch_var->Get<phi::SparseCooTensor>();
      if (!src_item.initialized()) {
105 106
        return phi::KernelKey(framework::proto::VarType::FP32,
                              platform::CPUPlace());
107
      }
108 109 110
    } else {
      auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
      if (src_item.empty() || !src_item[0].IsInitialized()) {
111 112
        return phi::KernelKey(framework::proto::VarType::FP32,
                              platform::CPUPlace());
113 114 115
      }
    }

116 117
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          platform::CPUPlace());
W
wanghuancoder 已提交
118 119 120 121 122 123 124 125 126 127 128
  }
};

class FetchV2Kernel {
 public:
  void operator()(const framework::ExecutionContext &ctx) const {
    auto fetch_var_name = ctx.InputName("X");
    auto *fetch_var = ctx.InputVar("X");
    if (fetch_var == nullptr) {
      return;
    }
129
    PADDLE_ENFORCE_EQ(
130 131
        ctx.HasOutput("Out"),
        true,
132
        platform::errors::NotFound("Output(Out) of fetch_v2_op is not found."));
W
wanghuancoder 已提交
133 134 135 136
    auto *out_var = ctx.OutputVar("Out");

    int col = ctx.Attr<int>("col");
    PADDLE_ENFORCE_GE(
137 138
        col,
        0,
139 140 141 142 143
        platform::errors::InvalidArgument(
            "Expected the column index (the attribute 'col' of "
            "operator 'Fetch') of current fetching variable to be "
            "no less than 0. But received column index = %d.",
            col));
W
wanghuancoder 已提交
144 145 146 147 148 149 150

    auto *fetch_list = out_var->GetMutable<framework::FetchList>();

    if (static_cast<size_t>(col) >= fetch_list->size()) {
      fetch_list->resize(col + 1);
    }

151 152
    bool deepcopy = ctx.Attr<bool>("deepcopy");

153 154
    if (fetch_var->IsType<phi::DenseTensor>()) {
      auto &src_item = fetch_var->Get<phi::DenseTensor>();
155 156 157
      if (!src_item.IsInitialized()) {
        return;
      }
158
      auto *dst_item = &(PADDLE_GET(phi::DenseTensor, fetch_list->at(col)));
159 160 161
      bool check_place = platform::is_cpu_place(src_item.place()) ||
                         platform::is_cuda_pinned_place(src_item.place());
      PADDLE_ENFORCE_EQ(
162 163
          check_place,
          true,
164 165
          platform::errors::InvalidArgument("Tensor's place of input(X) must "
                                            "be CPUPlace or CUDAPinnedPlace."));
166 167 168 169
      if (deepcopy) {
        DeepCopy(src_item, fetch_var_name, dst_item);
      } else {
        dst_item->ShareDataWith(src_item);
A
Aurelius84 已提交
170
        dst_item->set_lod(src_item.lod());
171
      }
172 173 174 175 176 177
    } else if (fetch_var->IsType<phi::SparseCooTensor>()) {
      auto &src_item = fetch_var->Get<phi::SparseCooTensor>();
      if (!src_item.initialized()) {
        return;
      }
      fetch_list->at(col) = src_item;
W
wanghuancoder 已提交
178 179 180 181 182
    } else {
      auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
      framework::LoDTensorArray tmp(src_item.size());
      fetch_list->at(col) = tmp;
      auto &dst_item =
R
Ruibiao Chen 已提交
183
          PADDLE_GET(framework::LoDTensorArray, fetch_list->at(col));
W
wanghuancoder 已提交
184
      for (size_t i = 0; i < src_item.size(); ++i) {
185 186
        PADDLE_ENFORCE_EQ(platform::is_cpu_place(src_item[i].place()),
                          true,
187 188 189 190 191 192
                          platform::errors::InvalidArgument(
                              "Tensor's place of input(X) must be CPUPlace."));
        if (deepcopy) {
          DeepCopy(src_item[i], fetch_var_name, &dst_item[i]);
        } else {
          dst_item[i].ShareDataWith(src_item[i]);
A
Aurelius84 已提交
193
          dst_item[i].set_lod(src_item[i].lod());
194
        }
W
wanghuancoder 已提交
195 196 197 198 199 200 201 202 203
      }
    }
  }
};

class FetchV2OpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
204 205
             "(phi::DenseTensor) The resulted phi::DenseTensor which is "
             "expected to return "
W
wanghuancoder 已提交
206 207
             "to users.");
    AddOutput("Out",
208 209
              "(vector<phi::DenseTensor>) A fetching list of phi::DenseTensor "
              "which may have "
W
wanghuancoder 已提交
210 211
              "different dimension, shape and data type.");
    AddAttr<int>("col", "(int) The column index of fetching object.");
212 213
    AddAttr<bool>("deepcopy", "(bool) Whether deep copy is required.")
        .SetDefault(true);
W
wanghuancoder 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226
    AddComment(R"DOC(
FetchV2 Operator.
It should not be configured by users directly.
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OPERATOR(
227 228 229
    fetch_v2,
    ops::FetchV2Op,
    ops::FetchV2OpProtoMaker,
W
wanghuancoder 已提交
230 231 232
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);

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
REGISTER_OP_CPU_KERNEL_FUNCTOR(fetch_v2,
                               float,
                               ops::FetchV2Kernel,
                               double,
                               ops::FetchV2Kernel,
                               int8_t,
                               ops::FetchV2Kernel,
                               uint8_t,
                               ops::FetchV2Kernel,
                               int,
                               ops::FetchV2Kernel,
                               int64_t,
                               ops::FetchV2Kernel,
                               bool,
                               ops::FetchV2Kernel,
                               paddle::platform::bfloat16,
                               ops::FetchV2Kernel,
                               paddle::platform::complex<float>,
                               ops::FetchV2Kernel,
                               paddle::platform::complex<double>,
                               ops::FetchV2Kernel,
                               plat::float16,
                               ops::FetchV2Kernel,
                               int16_t,
                               ops::FetchV2Kernel);