eager_utils.h 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* 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. */
#pragma once

13 14 15 16 17
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif

18
#include <Python.h>
19 20 21 22
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
23

24
#include "paddle/fluid/eager/grad_node_info.h"
25
#include "paddle/fluid/eager/hooks.h"
26
#include "paddle/fluid/framework/lod_tensor.h"
27
#include "paddle/fluid/framework/lod_tensor_array.h"
28
#include "paddle/fluid/framework/string_array.h"
29
#include "paddle/fluid/framework/tensor.h"
30
#include "paddle/fluid/jit/function.h"
31
#include "paddle/fluid/platform/place.h"
32
#include "paddle/ir/core/value.h"
33 34
#include "paddle/phi/common/backend.h"
#include "paddle/phi/common/data_type.h"
35
#include "paddle/phi/common/int_array.h"
36
#include "paddle/phi/common/scalar.h"
37
#include "paddle/phi/core/dense_tensor.h"
38
#include "paddle/phi/core/selected_rows.h"
39
#include "paddle/utils/pybind.h"
40 41
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
L
LiYuRio 已提交
42 43 44 45 46
#ifdef PADDLE_WITH_DISTRIBUTE
#include "paddle/phi/core/distributed/auto_parallel/dist_attr.h"
#include "paddle/phi/core/distributed/auto_parallel/dist_tensor.h"
#endif

47
namespace paddle {
48
class CustomOpKernelContext;
0
0x45f 已提交
49 50 51
namespace framework {
class Scope;
}
52 53
namespace pybind {

54
namespace py = ::pybind11;
55

56
int TensorDtype2NumpyDtype(phi::DataType dtype);
57

58 59 60
bool PyObject_CheckLongOrConvertToLong(PyObject** obj);
bool PyObject_CheckFloatOrConvertToFloat(PyObject** obj);
bool PyObject_CheckStr(PyObject* obj);
61
bool PyObject_CheckIROpResult(PyObject* obj);
62 63 64
bool CastPyArg2AttrBoolean(PyObject* obj, ssize_t arg_pos);
int CastPyArg2AttrInt(PyObject* obj, ssize_t arg_pos);
int64_t CastPyArg2AttrLong(PyObject* obj, ssize_t arg_pos);
W
wanghuancoder 已提交
65
size_t CastPyArg2AttrSize_t(PyObject* obj, ssize_t arg_pos);
66 67
float CastPyArg2AttrFloat(PyObject* obj, ssize_t arg_pos);
std::string CastPyArg2AttrString(PyObject* obj, ssize_t arg_pos);
J
Jiabin Yang 已提交
68 69
std::shared_ptr<imperative::VarBase> CastPyArg2VarBase(PyObject* obj,
                                                       ssize_t arg_pos);
70 71
std::vector<paddle::Tensor> CastPyArg2VectorOfTensor(PyObject* obj,
                                                     ssize_t arg_pos);
72
platform::Place CastPyArg2Place(PyObject* obj, ssize_t arg_pos);
73
phi::DenseTensor CastPyArg2FrameworkTensor(PyObject* obj, ssize_t arg_pos);
74 75
std::vector<phi::DenseTensor> CastPyArg2VectorOfTensorBase(PyObject* obj,
                                                           ssize_t arg_pos);
76
std::vector<int> CastPyArg2VectorOfInt(PyObject* obj, size_t arg_pos);
77
std::vector<int64_t> CastPyArg2VectorOfInt64(PyObject* obj, size_t arg_pos);
W
wanghuancoder 已提交
78
std::vector<size_t> CastPyArg2VectorOfSize_t(PyObject* obj, size_t arg_pos);
79
std::vector<float> CastPyArg2VectorOfFloat(PyObject* obj, size_t arg_pos);
80 81
ir::OpResult CastPyArg2OpResult(PyObject* obj,
                                const std::string& op_type,
82
                                size_t arg_pos);
83 84
std::vector<ir::OpResult> CastPyArg2VectorOfOpResult(PyObject* obj,
                                                     const std::string& op_type,
85
                                                     size_t arg_pos);
W
wanghuancoder 已提交
86 87
std::vector<std::vector<size_t>> CastPyArg2VectorOfVectorOfSize_t(
    PyObject* obj, size_t arg_pos);
J
Jiabin Yang 已提交
88 89
framework::proto::VarType::Type CastPyArg2ProtoType(PyObject* obj,
                                                    ssize_t arg_pos);
90
paddle::framework::Vocab CastPyArg2Vocab(PyObject* obj, ssize_t arg_pos);
91 92
std::vector<std::string> CastPyArg2VectorOfString(PyObject* obj,
                                                  ssize_t arg_pos);
93 94
std::shared_ptr<jit::Function> CastPyArg2JitFunction(PyObject* obj,
                                                     ssize_t arg_pos);
95
void SetPythonStack();
96

97
PyObject* ToPyObject(int value);
98
PyObject* ToPyObject(uint32_t value);
99 100
PyObject* ToPyObject(bool value);
PyObject* ToPyObject(int64_t value);
W
wanghuancoder 已提交
101
PyObject* ToPyObject(size_t value);
102 103 104 105
PyObject* ToPyObject(float value);
PyObject* ToPyObject(double value);
PyObject* ToPyObject(const char* value);
PyObject* ToPyObject(const std::string& value);
106
PyObject* ToPyObject(const paddle::Tensor& value,
107
                     PyObject* args,
108 109
                     const std::map<ssize_t, ssize_t>& inplace_var_idx_map);
PyObject* ToPyObject(PyObject* args, ssize_t arg_idx);
110 111 112
PyObject* ToPyObject(const std::vector<bool>& value);
PyObject* ToPyObject(const std::vector<int>& value);
PyObject* ToPyObject(const std::vector<int64_t>& value);
W
wanghuancoder 已提交
113
PyObject* ToPyObject(const std::vector<size_t>& value);
114 115
PyObject* ToPyObject(const std::vector<float>& value);
PyObject* ToPyObject(const std::vector<double>& value);
W
wanghuancoder 已提交
116
PyObject* ToPyObject(const std::vector<std::vector<size_t>>& value);
117 118 119
PyObject* ToPyObject(const std::vector<paddle::Tensor>& value,
                     bool return_py_none_if_not_initialize = false);
PyObject* ToPyObject(const std::vector<std::vector<paddle::Tensor>>& value,
120
                     bool return_py_none_if_not_initialize = false);
121
PyObject* ToPyObject(const platform::Place& value);
122
PyObject* ToPyObject(const phi::DenseTensor* value);
L
LiYuRio 已提交
123
#ifdef PADDLE_WITH_DISTRIBUTE
124
PyObject* ToPyObject(const phi::distributed::DistTensor* value);
125
PyObject* ToPyObject(const phi::distributed::TensorDistAttr* value);
L
LiYuRio 已提交
126
#endif
127
PyObject* ToPyObject(const phi::SelectedRows* value);
J
Jiabin Yang 已提交
128
PyObject* ToPyObject(const paddle::framework::proto::VarType::Type& dtype);
129
PyObject* ToPyObject(const paddle::framework::proto::VarType& type);
W
wanghuancoder 已提交
130
PyObject* ToPyObject(const void* value);
131
PyObject* ToPyObject(const std::unordered_map<int, int>& value);
132 133
PyObject* ToPyObject(
    const std::unordered_map<std::string, std::vector<std::string>>& value);
134
PyObject* ToPyObject(const paddle::framework::Vocab& value);
135

136
PyObject* ToPyObject(std::shared_ptr<egr::GradNodeBase> grad_node);
137

138
PyObject* ToPyObject(const ir::OpResult& value);
139
PyObject* ToPyObject(const std::vector<ir::OpResult>& value);
140

141 142 143 144 145 146 147 148 149 150 151
class PyTensorHook : public egr::TensorHook {
 public:
  explicit PyTensorHook(PyObject* func) : py_func_(func) {
    Py_INCREF(py_func_);
  }

  ~PyTensorHook() {
    py::gil_scoped_acquire gil;
    Py_DECREF(py_func_);
  }

152
  paddle::Tensor operator()(const paddle::Tensor& var) override;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

 private:
  PyObject* py_func_;
};

class PyVoidHook : public egr::VoidHook {
 public:
  explicit PyVoidHook(PyObject* func) : py_func_(func) { Py_INCREF(py_func_); }

  ~PyVoidHook() {
    py::gil_scoped_acquire gil;
    Py_DECREF(py_func_);
  }

  void operator()() override;

 private:
  PyObject* py_func_;
};

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
class PyObjectHolder : public egr::PyObjectHolderBase {
 public:
  PyObjectHolder() { ptr_ = nullptr; }
  explicit PyObjectHolder(PyObject* ptr);
  ~PyObjectHolder() override;
  void* get() override;
  void reset(void* ptr) override;
  void inc_ref() override;
  void dec_ref() override;

 private:
  PyObject* ptr_{nullptr};
};

class PackHook : public egr::PackHookBase {
 public:
  explicit PackHook(PyObject* hook);

  ~PackHook();

  std::shared_ptr<egr::PyObjectHolderBase> operator()(
194
      const paddle::Tensor& tensor) override;
195 196 197 198 199 200 201 202 203 204 205 206 207

  void* operator()(void* py_tensor) override;

 private:
  PyObject* hook_;
};

class UnPackHook : public egr::UnPackHookBase {
 public:
  explicit UnPackHook(PyObject* hook);

  ~UnPackHook();

208
  paddle::Tensor operator()(
209 210 211 212 213 214 215
      std::shared_ptr<egr::PyObjectHolderBase> packed_value) override;

  void* operator()(void* packed_value, void* other) override;

 private:
  PyObject* hook_;
};
216
template <typename Tuple, size_t N>
217
struct TupleTensorResult {
218
  static void Run(const Tuple& out, PyObject* result) {
219
    TupleTensorResult<Tuple, N - 1>::Run(out, result);
220 221
    PyTuple_SET_ITEM(result, N - 1, ToPyObject(std::get<N - 1>(out)));
  }
222

223 224 225
  static void Run(const Tuple& out,
                  PyObject* result,
                  PyObject* args,
226 227 228 229
                  const std::map<ssize_t, ssize_t>& inplace_var_idx_map) {
    TupleTensorResult<Tuple, N - 1>::Run(
        out, result, args, inplace_var_idx_map);
    if (!inplace_var_idx_map.empty() && inplace_var_idx_map.count(N - 1)) {
230
      PyTuple_SET_ITEM(
231
          result, N - 1, ToPyObject(args, inplace_var_idx_map.at(N - 1)));
232 233 234 235
    } else {
      PyTuple_SET_ITEM(result, N - 1, ToPyObject(std::get<N - 1>(out)));
    }
  }
236 237 238
};

template <typename Tuple>
239
struct TupleTensorResult<Tuple, 1> {
240 241 242
  static void Run(const Tuple& out, PyObject* result) {
    PyTuple_SET_ITEM(result, 0, ToPyObject(std::get<0>(out)));
  }
243

244 245 246
  static void Run(const Tuple& out,
                  PyObject* result,
                  PyObject* args,
247 248 249
                  const std::map<ssize_t, ssize_t>& inplace_var_idx_map) {
    if (!inplace_var_idx_map.empty() && inplace_var_idx_map.count(0)) {
      PyTuple_SET_ITEM(result, 0, ToPyObject(args, inplace_var_idx_map.at(0)));
250 251 252 253
    } else {
      PyTuple_SET_ITEM(result, 0, ToPyObject(std::get<0>(out)));
    }
  }
254 255 256 257 258 259 260
};

template <typename... Args>
PyObject* ToPyObject(const std::tuple<Args...>& out) {
  auto len = sizeof...(Args);
  PyObject* result = PyTuple_New(len);

261
  TupleTensorResult<decltype(out), sizeof...(Args)>::Run(out, result);
262 263 264 265

  return result;
}

266
template <typename... Args>
267 268
PyObject* ToPyObject(const std::tuple<Args...>& out,
                     PyObject* args,
269
                     const std::map<ssize_t, ssize_t>& inplace_var_idx_map) {
270 271 272 273
  // For inplace op, directly return the input PyObject of the inplace tensor.
  // [Parameter]
  // out: Outputs tuple after executing op.
  // args: Input PyObject.
274 275 276 277 278
  // inplace_var_idx_map: Index of Tensors in inplace_map, e.g. {{value_idx,
  // arg_idx}}.
  // - value_idx: Index of inplace tensor in outputs tuple. Used to find the
  // output inplace tensor.
  // - arg_idx: Index of inplace PyObject in input args. Used to find the input
279 280 281 282
  // inplace PyObject.
  auto len = sizeof...(Args);
  PyObject* result = PyTuple_New(len);

283
  TupleTensorResult<decltype(out), sizeof...(Args)>::Run(
284
      out, result, args, inplace_var_idx_map);
285 286 287 288

  return result;
}

289 290 291 292
paddle::experimental::Scalar CastPyArg2Scalar(PyObject* obj,
                                              const std::string& op_type,
                                              ssize_t arg_pos);

293 294 295 296
paddle::experimental::Scalar CastNumpy2Scalar(PyObject* obj,
                                              const std::string& op_type,
                                              ssize_t arg_pos);

297 298 299 300
std::vector<phi::Scalar> CastPyArg2ScalarArray(PyObject* obj,
                                               const std::string& op_type,
                                               ssize_t arg_pos);

301 302 303
paddle::experimental::IntArray CastPyArg2IntArray(PyObject* obj,
                                                  const std::string& op_type,
                                                  ssize_t arg_pos);
304

305 306
paddle::Place CastPyArg2Place(PyObject* obj,
                              const std::string& op_type,
307
                              ssize_t arg_pos);
308

309 310
paddle::DataType CastPyArg2DataType(PyObject* obj,
                                    const std::string& op_type,
311
                                    ssize_t arg_pos);
312

313 314 315 316
paddle::DataType CastPyArg2DataTypeDirectly(PyObject* obj,
                                            const std::string& op_type,
                                            ssize_t arg_pos);

L
LiYuRio 已提交
317
#ifdef PADDLE_WITH_DISTRIBUTE
318 319
phi::distributed::TensorDistAttr CastPyArg2DistAttr(PyObject* obj,
                                                    ssize_t arg_pos);
L
LiYuRio 已提交
320 321
#endif

322
paddle::optional<paddle::Tensor> GetOptionalTensorFromArgs(
323 324 325 326 327
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable = false);
328

329 330 331 332 333
paddle::Tensor& GetTensorFromArgs(const std::string& op_type,
                                  const std::string& arg_name,
                                  PyObject* args,
                                  ssize_t arg_idx,
                                  bool dispensable = false);
334

335
paddle::optional<std::vector<paddle::Tensor>> GetOptionalTensorListFromArgs(
336 337 338 339 340
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable = false);
341

342 343 344 345 346 347 348 349 350 351 352
std::vector<paddle::Tensor> GetTensorListFromArgs(const std::string& op_type,
                                                  const std::string& arg_name,
                                                  PyObject* args,
                                                  ssize_t arg_idx,
                                                  bool dispensable = false);

paddle::Tensor* GetTensorPtrFromArgs(const std::string& op_type,
                                     const std::string& arg_name,
                                     PyObject* args,
                                     ssize_t arg_idx,
                                     bool dispensable = false);
353

354
std::vector<paddle::Tensor*> GetTensorPtrListFromArgs(
355 356 357 358 359
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable = false);
360

361
std::vector<paddle::Tensor*> GetTensorPtrListFromPyObject(PyObject* obj);
W
wanghuancoder 已提交
362

363 364 365
std::vector<paddle::Tensor> GetTensorListFromPyObject(PyObject* obj,
                                                      bool allow_none = false);
paddle::Tensor& UnSafeGetTensorFromPyObject(PyObject* obj);
W
wanghuancoder 已提交
366

J
Jiabin Yang 已提交
367
// end of Slice related methods
368

0
0x45f 已提交
369
std::vector<paddle::framework::Scope*> GetScopePtrListFromArgs(
370 371 372 373 374
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable);
J
Jiabin Yang 已提交
375

376 377 378 379 380 381 382 383 384 385 386 387
class eager_gil_scoped_release {
 public:
  eager_gil_scoped_release() { tstate = PyEval_SaveThread(); }
  ~eager_gil_scoped_release() {
    if (!tstate) return;
    PyEval_RestoreThread(tstate);
  }

 private:
  PyThreadState* tstate{nullptr};
};

388 389
}  // namespace pybind
}  // namespace paddle