tensor.cc 41.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
Copyright (c) 2022 NVIDIA 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 <Python.h>
16 17 18 19
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
20 21 22 23 24 25 26 27 28 29 30 31 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>  // NOLINT // for call_once
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/framework/custom_operator.h"
#include "paddle/fluid/framework/data_layout.h"
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/executor_cache.h"
#include "paddle/fluid/framework/executor_gc_helper.h"
#include "paddle/fluid/framework/feed_fetch_method.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/garbage_collector.h"
#include "paddle/fluid/framework/io/fs.h"
#include "paddle/fluid/framework/ir/coalesce_grad_tensor_pass.h"
#include "paddle/fluid/framework/ir/cost_model.h"
#include "paddle/fluid/framework/ir/generate_pass.h"
#include "paddle/fluid/framework/ir/pass_builder.h"
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/new_executor/executor_statistics.h"
#include "paddle/fluid/framework/new_executor/standalone_executor.h"
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/framework/parallel_executor.h"
#include "paddle/fluid/framework/phi_utils.h"
#include "paddle/fluid/framework/prune.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/framework/scope_pool.h"
#include "paddle/fluid/framework/selected_rows_utils.h"
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/framework/trainer.h"
#include "paddle/fluid/framework/type_defs.h"
#include "paddle/fluid/framework/version.h"
#include "paddle/fluid/imperative/amp_auto_cast.h"
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/memory/allocation/cuda_ipc_allocator.h"
#endif
#include "paddle/fluid/memory/allocation/mmap_allocator.h"
#include "paddle/fluid/operators/activation_op.h"
#include "paddle/fluid/operators/common_infer_shape_functions.h"
#include "paddle/fluid/operators/py_func_op.h"
#include "paddle/fluid/platform/cpu_helper.h"
#include "paddle/fluid/platform/device/device_wrapper.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/dynload/dynamic_loader.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/init.h"
#include "paddle/fluid/platform/monitor.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/profiler.h"
#include "paddle/fluid/platform/profiler/event_python.h"
#include "paddle/fluid/platform/profiler/event_tracing.h"
#include "paddle/fluid/platform/profiler/profiler.h"
#include "paddle/fluid/pybind/bind_cost_model.h"
#include "paddle/fluid/pybind/bind_fleet_executor.h"
#include "paddle/fluid/pybind/box_helper_py.h"
#include "paddle/fluid/pybind/communication.h"
#include "paddle/fluid/pybind/compatible.h"
#include "paddle/fluid/pybind/const_value.h"
96
#include "paddle/fluid/pybind/cuda_streams_py.h"
97
#include "paddle/fluid/pybind/data_set_py.h"
98 99
#include "paddle/fluid/pybind/distributed_py.h"
#include "paddle/fluid/pybind/eager.h"
100 101 102 103 104 105
#include "paddle/fluid/pybind/exception.h"
#include "paddle/fluid/pybind/fleet_wrapper_py.h"
#include "paddle/fluid/pybind/generator_py.h"
#include "paddle/fluid/pybind/global_value_getter_setter.h"
#include "paddle/fluid/pybind/gloo_context_py.h"
#include "paddle/fluid/pybind/gloo_wrapper_py.h"
106
#include "paddle/fluid/pybind/graph.h"
107
#include "paddle/fluid/pybind/heter_wrapper_py.h"
108
#include "paddle/fluid/pybind/imperative.h"
109
#include "paddle/fluid/pybind/inference_api.h"
110
#include "paddle/fluid/pybind/io.h"
111 112
#include "paddle/fluid/pybind/metrics_py.h"
#include "paddle/fluid/pybind/ps_gpu_wrapper_py.h"
113
#include "paddle/fluid/pybind/pybind_variant_caster.h"
114
#include "paddle/phi/backends/cpu/cpu_info.h"
115
#include "paddle/phi/backends/device_manager.h"
116 117 118
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/lod_utils.h"
#include "paddle/utils/none.h"
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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#include "paddle/fluid/pybind/nccl_wrapper_py.h"
#endif
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/pybind/protobuf.h"
#include "paddle/fluid/pybind/pybind.h"  // NOLINT
#include "paddle/fluid/pybind/reader_py.h"
#include "paddle/fluid/pybind/tensor_py.h"
#include "paddle/fluid/string/to_string.h"
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
#endif
#ifndef PADDLE_WITH_HIP
#include "paddle/fluid/platform/device/gpu/cuda/cuda_profiler.h"
#endif
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
#endif

#ifdef PADDLE_WITH_XPU
#include "paddle/fluid/platform/device/xpu/xpu_info.h"
#include "paddle/fluid/platform/device/xpu/xpu_op_list.h"
#endif

#ifdef PADDLE_WITH_CUSTOM_DEVICE
#include "paddle/phi/capi/capi.h"
#endif

#include "paddle/fluid/platform/cuda_graph_with_memory_pool.h"

#ifdef PADDLE_WITH_IPU
#include "paddle/fluid/platform/device/ipu/ipu_backend.h"
#include "paddle/fluid/platform/device/ipu/ipu_info.h"
#endif

#ifdef PADDLE_WITH_CRYPTO
#include "paddle/fluid/pybind/crypto.h"
#endif

#if defined PADDLE_WITH_PSCORE
#include "paddle/fluid/pybind/fleet_py.h"
#endif

#ifdef PADDLE_WITH_CINN
#include "paddle/fluid/framework/paddle2cinn/cinn_compiler.h"
#endif

#include "paddle/fluid/eager/api/utils/global_utils.h"
#include "paddle/fluid/imperative/layout_autotune.h"
169
#include "paddle/fluid/pybind/complex.h"
170 171 172
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/fluid/pybind/tensor.h"
#include "paddle/phi/api/ext/op_meta_info.h"
173
#include "paddle/phi/core/distributed/auto_parallel/dist_tensor.h"
174
#include "paddle/phi/core/flags.h"
175 176 177 178
#include "paddle/phi/kernels/autotune/cache.h"
#include "paddle/phi/kernels/autotune/switch_autotune.h"
#include "pybind11/stl.h"

179 180
PHI_DECLARE_bool(use_mkldnn);
PHI_DECLARE_bool(use_shm_cache);
181 182 183 184 185 186 187 188 189 190 191 192 193

// disable auto conversion to list in Python
PYBIND11_MAKE_OPAQUE(paddle::framework::LoDTensorArray);
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchUnmergedList);
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchList);
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchType);

namespace paddle {
namespace pybind {

PyTypeObject *g_framework_tensor_pytype = nullptr;

template <typename PlaceType>
194 195
static void TensorCopyFrom(phi::DenseTensor *dst,
                           const phi::DenseTensor &src,
196 197 198 199 200 201 202 203 204 205 206 207
                           const PlaceType &place,
                           int64_t batch_size) {
  if (batch_size < 0) {
    framework::TensorCopy(src, place, dst);
  } else {
    auto sliced = src.Slice(0, batch_size);
    framework::TensorCopy(sliced, place, dst);
  }
}

void BindTensor(pybind11::module &m) {  // NOLINT
  using namespace paddle::framework;    // NOLINT
208
  py::class_<phi::DenseTensor> framework_tensor(
209 210 211 212 213
      m, "Tensor", py::buffer_protocol());
  g_framework_tensor_pytype =
      reinterpret_cast<PyTypeObject *>(framework_tensor.ptr());
  framework_tensor
      .def("__array__",
214
           [](phi::DenseTensor &self) { return TensorToPyArray(self); })
215
      .def("_ptr",
216
           [](const phi::DenseTensor &self) {
217 218
             return reinterpret_cast<uintptr_t>(self.data());
           })
219 220
      .def("_slice", &phi::DenseTensor::Slice)
      .def("_numel", &phi::DenseTensor::numel)
221
      .def("_is_initialized",
222
           [](const phi::DenseTensor &self) { return self.IsInitialized(); })
223
      .def("_get_dims",
224
           [](const phi::DenseTensor &self) { return vectorize(self.dims()); })
225
      .def("_set_dims",
226
           [](phi::DenseTensor &self, const std::vector<int64_t> &dim) {
227 228 229
             self.Resize(phi::make_ddim(dim));
           })
      .def("_set_layout",
230
           [](phi::DenseTensor &self, const std::string &layout) {
231
             self.set_layout(phi::StringToDataLayout(layout));
232 233
           })
      .def("_alloc_float",
234
           [](phi::DenseTensor &self, paddle::platform::CustomPlace &place) {
235 236 237
             self.mutable_data<float>(place);
           })
      .def("_alloc_float",
238
           [](phi::DenseTensor &self, paddle::platform::CUDAPlace &place) {
239 240 241
             self.mutable_data<float>(place);
           })
      .def("_alloc_float",
242
           [](phi::DenseTensor &self, paddle::platform::XPUPlace &place) {
243 244 245
             self.mutable_data<float>(place);
           })
      .def("_alloc_float",
246
           [](phi::DenseTensor &self, paddle::platform::CPUPlace &place) {
247 248 249
             self.mutable_data<float>(place);
           })
      .def("_alloc_double",
250
           [](phi::DenseTensor &self, paddle::platform::CPUPlace &place) {
251 252 253
             self.mutable_data<double>(place);
           })
      .def("_alloc_int",
254
           [](phi::DenseTensor &self, paddle::platform::CPUPlace &place) {
255 256 257
             self.mutable_data<int>(place);
           })
      .def("_alloc_int",
258
           [](phi::DenseTensor &self, paddle::platform::CustomPlace &place) {
259 260 261
             self.mutable_data<int>(place);
           })
      .def("_alloc_int",
262
           [](phi::DenseTensor &self, paddle::platform::XPUPlace &place) {
263 264 265
             self.mutable_data<int>(place);
           })
      .def("_alloc_int",
266
           [](phi::DenseTensor &self, paddle::platform::CUDAPlace &place) {
267 268
             self.mutable_data<int>(place);
           })
269 270 271 272 273 274 275 276 277 278
      .def(
          "_alloc_int",
          [](phi::DenseTensor &self, paddle::platform::CUDAPinnedPlace &place) {
            self.mutable_data<int>(place);
          })
      .def(
          "_alloc_float",
          [](phi::DenseTensor &self, paddle::platform::CUDAPinnedPlace &place) {
            self.mutable_data<float>(place);
          })
279
      .def("_mutable_data",
280
           [](phi::DenseTensor &self,
281 282 283 284 285 286
              paddle::platform::CPUPlace &place,
              paddle::framework::proto::VarType::Type type) {
             return reinterpret_cast<uintptr_t>(
                 self.mutable_data(place, framework::TransToPhiDataType(type)));
           })
      .def("_mutable_data",
287
           [](phi::DenseTensor &self,
288 289 290 291 292 293
              paddle::platform::CustomPlace &place,
              paddle::framework::proto::VarType::Type type) {
             return reinterpret_cast<uintptr_t>(
                 self.mutable_data(place, framework::TransToPhiDataType(type)));
           })
      .def("_mutable_data",
294
           [](phi::DenseTensor &self,
295 296 297 298 299 300
              paddle::platform::XPUPlace &place,
              paddle::framework::proto::VarType::Type type) {
             return reinterpret_cast<uintptr_t>(
                 self.mutable_data(place, framework::TransToPhiDataType(type)));
           })
      .def("_mutable_data",
301
           [](phi::DenseTensor &self,
302 303 304 305 306 307
              paddle::platform::CUDAPlace &place,
              paddle::framework::proto::VarType::Type type) {
             return reinterpret_cast<uintptr_t>(
                 self.mutable_data(place, framework::TransToPhiDataType(type)));
           })
      .def("_mutable_data",
308
           [](phi::DenseTensor &self,
309 310 311 312 313
              paddle::platform::CUDAPinnedPlace &place,
              paddle::framework::proto::VarType::Type type) {
             return reinterpret_cast<uintptr_t>(
                 self.mutable_data(place, framework::TransToPhiDataType(type)));
           })
314
      .def("_clear", &phi::DenseTensor::clear)
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::CPUPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::CustomPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::XPUPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::CUDAPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::CUDAPinnedPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
A
Allen Guo 已提交
340 341 342 343 344
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::IPUPlace>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
      .def("_copy_from",
           &TensorCopyFrom<paddle::platform::Place>,
           py::arg("tensor"),
           py::arg("place"),
           py::arg("batch_size") = -1)
      .def("set",
           SetTensorFromPyArray<paddle::platform::CPUPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false)
      .def("set",
           SetTensorFromPyArray<paddle::platform::CustomPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false)
      .def("set",
           SetTensorFromPyArray<paddle::platform::XPUPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false)
      .def("set",
           SetTensorFromPyArray<paddle::platform::CUDAPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false)
      .def("set",
           SetTensorFromPyArray<paddle::platform::IPUPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false)
      .def("set",
           SetTensorFromPyArray<paddle::platform::CUDAPinnedPlace>,
           py::arg("array"),
           py::arg("place"),
           py::arg("zero_copy") = false,
           R"DOC(
        Set the data of Tensor on place with given numpy array.
382

383 384
        Args:
          lod (numpy.ndarray): The data to set.
张春乔 已提交
385
          place (CPUPlace|CUDAPlace|XPUPlace|IPUPlace|CUDAPinnedPlace): The place where the
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
          Tensor is to be set.
          zero_copy (bool, optional): Whether to share memory with the input numpy array.
          This parameter only works with CPUPlace. Default: False.

        Returns:
            None.

        Examples:
            .. code-block:: python

                import paddle.fluid as fluid
                import numpy as np

                t = fluid.Tensor()
                t.set(np.ndarray([5, 30]), fluid.CPUPlace())
          )DOC")

      .def(
          "shape",
405
          [](phi::DenseTensor &self) { return vectorize(self.dims()); },
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
          R"DOC(
           Return the shape of Tensor.

           Returns:
               list[int]: The shape of Tensor.


           Examples:
               .. code-block:: python

                  import paddle.fluid as fluid
                  import numpy as np

                  t = fluid.Tensor()
                  t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                  print(t.shape())  # [5, 30]
           )DOC")
      .def("_to_dlpack",
424
           [](phi::DenseTensor &self) {
S
Siming Dai 已提交
425 426
             DLManagedTensor *dmt = framework::toDLPack(self);
             auto capsule = pybind11::capsule(
427
                 static_cast<void *>(dmt), "dltensor", [](PyObject *ptr) {
S
Siming Dai 已提交
428 429
                   if (!PyCapsule_IsValid(ptr, "dltensor")) {
                     return;
430
                   }
S
Siming Dai 已提交
431 432 433
                   DLManagedTensor *dmt = static_cast<DLManagedTensor *>(
                       PyCapsule_GetPointer(ptr, "dltensor"));
                   dmt->deleter(dmt);
434 435 436 437 438 439 440
                 });
             return capsule;
           })
      .def("_set_float_element", TensorSetElement<float>)
      .def("_get_float_element", TensorGetElement<float>)
      .def("_set_double_element", TensorSetElement<double>)
      .def("_get_double_element", TensorGetElement<double>)
441 442 443 444
      .def("_set_complex64_element", TensorSetElement<paddle::complex64>)
      .def("_get_complex64_element", TensorGetElement<paddle::complex64>)
      .def("_set_complex128_element", TensorSetElement<paddle::complex128>)
      .def("_get_complex128_element", TensorGetElement<paddle::complex128>)
445
      .def("_place", [](phi::DenseTensor &self) { return self.place(); })
446
      .def("_dtype",
447
           [](phi::DenseTensor &self) {
448 449 450
             return framework::TransToProtoVarType(self.type());
           })
      .def("_layout",
451
           [](phi::DenseTensor &self) {
452
             return phi::DataLayoutToString(self.layout());
453
           })
454
      .def("_share_data_with", &phi::DenseTensor::ShareDataWith)
455 456
      .def("__getitem__", PySliceTensor, py::return_value_policy::reference)
      .def("__str__",
457
           [](const phi::DenseTensor &self) {
458 459 460 461 462
             std::stringstream ostr;
             ostr << self;
             return ostr.str();
           }) /* ------ End of original Tensor ------ */
      .def("__init__",
463
           [](phi::DenseTensor &instance,
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
              const std::vector<std::vector<size_t>>
                  &recursive_sequence_lengths) {
             LoD new_lod;
             new_lod.reserve(recursive_sequence_lengths.size());
             std::copy(recursive_sequence_lengths.begin(),
                       recursive_sequence_lengths.end(),
                       std::back_inserter(new_lod));
             LoD new_offset_lod = ConvertToOffsetBasedLoD(new_lod);
             PADDLE_ENFORCE_EQ(
                 CheckLoD(new_offset_lod, -1),
                 true,
                 platform::errors::InvalidArgument(
                     "The provided recursive_sequence_lengths info is "
                     "invalid, "
                     "the LoD converted by recursive_sequence_lengths is %s",
                     new_lod));
480
             new (&instance) phi::DenseTensor(new_offset_lod);
481 482
           })
      .def("__init__",
483 484
           [](phi::DenseTensor &instance) {
             new (&instance) phi::DenseTensor();
485 486 487 488 489 490 491 492 493
           })
      // We implement offset based LOD in C++ while we use length based with
      // Python API. So we changed set_lod to set_recursive_sequence_lengths
      // to
      // avoid misuse.
      // The discussion is here:
      // https://github.com/PaddlePaddle/Paddle/issues/10855
      .def(
          "set_lod",
494
          [](phi::DenseTensor &self,
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
             const std::vector<std::vector<size_t>> &lod) {
            // the input lod is offset-based level-of-detail info
            LoD new_lod;
            new_lod.reserve(lod.size());
            std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
            PADDLE_ENFORCE_EQ(
                CheckLoD(new_lod, vectorize(self.dims()).front()),
                true,
                platform::errors::InvalidArgument(
                    "The provided LoD is invalid, the LoD is %s", new_lod));
            self.set_lod(new_lod);
          },
          py::arg("lod"),
          R"DOC(
           Set LoD of the Tensor.

           Args:
               lod (list[list[int]]): The lod to set.

           Returns:
                None.

           Examples:
               .. code-block:: python

                 import paddle.fluid as fluid
                 import numpy as np

                 t = fluid.Tensor()
                 t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                 t.set_lod([[0, 2, 5]])
                 print(t.lod()) # [[0, 2, 5]]
           )DOC")
      .def(
          "set_recursive_sequence_lengths",
530
          [](phi::DenseTensor &self,
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
             const std::vector<std::vector<size_t>>
                 &recursive_sequence_lengths) {
            // the input recursive_sequence_lengths is length-based
            // level-of-detail info
            LoD new_lod;
            new_lod.reserve(recursive_sequence_lengths.size());
            std::copy(recursive_sequence_lengths.begin(),
                      recursive_sequence_lengths.end(),
                      std::back_inserter(new_lod));
            LoD new_offset_lod = ConvertToOffsetBasedLoD(new_lod);
            PADDLE_ENFORCE_EQ(
                CheckLoD(new_offset_lod, vectorize(self.dims()).front()),
                true,
                platform::errors::InvalidArgument(
                    "The provided recursive_sequence_lengths info is "
                    "invalid, "
                    "the LoD converted by recursive_sequence_lengths is "
                    "%s",
                    new_lod));
            self.set_lod(new_offset_lod);
          },
          py::arg("recursive_sequence_lengths"),
          R"DOC(
           Set LoD of the Tensor according to recursive sequence lengths.

           For example, if recursive_sequence_lengths=[[2, 3]], which means
           there are two sequences with length 2 and 3 respectively, the
           corresponding lod would be [[0, 2, 2+3]], i.e., [[0, 2, 5]].

           Args:
                recursive_sequence_lengths (list[list[int]]): The recursive sequence lengths.
562

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
           Returns:
                None.

           Examples:
               .. code-block:: python

                 import paddle.fluid as fluid
                 import numpy as np

                 t = fluid.Tensor()
                 t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                 t.set_recursive_sequence_lengths([[2, 3]])
                 print(t.recursive_sequence_lengths())  # [[2, 3]]
                 print(t.lod())  # [[0, 2, 5]]
           )DOC")
      .def(
          "lod",
580
          [](phi::DenseTensor &self) -> std::vector<std::vector<size_t>> {
581 582 583 584 585 586 587 588 589 590 591 592
            // output the offset-based lod info
            LoD lod = self.lod();
            std::vector<std::vector<size_t>> new_lod;
            new_lod.reserve(lod.size());
            std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
            return new_lod;
          },
          R"DOC(
           Return the LoD of the Tensor.

           Returns:
               list[list[int]]: The lod of the Tensor.
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607
           Examples:
               .. code-block:: python

                 import paddle.fluid as fluid
                 import numpy as np

                 t = fluid.Tensor()
                 t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                 t.set_lod([[0, 2, 5]])
                 print(t.lod()) # [[0, 2, 5]]
           )DOC")
      // Set above comments of set_lod.
      .def(
          "recursive_sequence_lengths",
608
          [](phi::DenseTensor &self) -> std::vector<std::vector<size_t>> {
609 610 611 612 613 614 615 616
            // output the length-based lod info
            LoD lod = phi::ConvertToLengthBasedLoD(self.lod());
            std::vector<std::vector<size_t>> new_lod;
            new_lod.reserve(lod.size());
            std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
            return new_lod;
          },
          R"DOC(
617
           Return the recursive sequence lengths corresponding to of the LodD
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
           of the Tensor.

           Returns:
                list[list[int]]: The recursive sequence lengths.

           Examples:
               .. code-block:: python

                 import paddle.fluid as fluid
                 import numpy as np

                 t = fluid.Tensor()
                 t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                 t.set_recursive_sequence_lengths([[2, 3]])
                 print(t.recursive_sequence_lengths()) # [[2, 3]]
           )DOC")
      .def(
          "has_valid_recursive_sequence_lengths",
636
          [](phi::DenseTensor &self) -> bool {
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            // Check that the lod info is valid and match the outermost
            // dimension of the Tensor data
            return CheckLoD(self.lod(), vectorize(self.dims()).front());
          },
          R"DOC(
           Check whether the LoD of the Tensor is valid.

           Returns:
               bool: Whether the LoD is valid.

           Examples:
               .. code-block:: python

                 import paddle.fluid as fluid
                 import numpy as np

                 t = fluid.Tensor()
                 t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                 t.set_recursive_sequence_lengths([[2, 3]])
                 print(t.has_valid_recursive_sequence_lengths()) # True
           )DOC")
      .def("_as_type",
659
           [](const phi::DenseTensor &self,
660
              paddle::framework::proto::VarType::Type type) {
661
             phi::DenseTensor dst;
662 663 664 665 666 667
             if (self.IsInitialized() && self.numel() > 0) {
               TransDataType(self, type, &dst);
             }
             return dst;
           })
      .def("_copy",
668
           [](const phi::DenseTensor &self, const platform::Place &place) {
669
             // follow fetch_op's inplementation
670
             phi::DenseTensor dst;
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
             if (self.IsInitialized() && self.numel() > 0) {
               TensorCopySync(self, place, &dst);
             } else {
               // Not copy, if the src tensor is empty.
               dst.clear();
               dst.Resize({0});
             }
             dst.set_lod(self.lod());
             return dst;
#ifdef _WIN32
           });
#else
           })
#ifdef PADDLE_WITH_CUDA
      .def("_share_buffer_with",
686
           [](phi::DenseTensor &self, const phi::DenseTensor src,
687 688 689 690 691 692 693 694 695 696 697 698 699 700
              py::tuple t) {
             auto *cuda_ipc_allocation =
                 dynamic_cast<memory::allocation::CudaIpcAllocation *>(
                     src.Holder().get());

             PADDLE_ENFORCE_NOT_NULL(
                 cuda_ipc_allocation,
                 platform::errors::PreconditionNotMet(
                     "Tensor is not Cuda IPC shared tensor. "
                     "Now only Tensor shared by cuda ipc could use this "
                     "api."));

             size_t size = t[0].cast<size_t>();
             auto dtype =
701
                 static_cast<phi::DataType>(t[1].cast<int>());
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
             auto dims = phi::make_ddim(t[2].cast<std::vector<int>>());
             auto lod_info = t[3].cast<framework::LoD>();
             auto device_id = t[4].cast<int>();

             auto shared_reader_holder =
                 std::make_shared<memory::allocation::Allocation>(
                     cuda_ipc_allocation->ptr(),
                     cuda_ipc_allocation->base_ptr(), size,
                     platform::CUDAPlace(device_id));

             self.ResetHolderWithType(shared_reader_holder, dtype);
             self.Resize(dims);
             self.set_lod(lod_info);

             VLOG(6) << "Reconstructed tensor with buffer shared!";
           },
           R"DOC(
           Deserialize GPU Tensor for existed shared Cuda IPC tensor.

           Params:
               tensor: Shared Cuda IPC tensor.
               tuple: contrains data size, data type,
                      tensor dims, lod information, device index.

       )DOC")
      .def("_share_cuda",
728
           [](phi::DenseTensor self) {
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
             if (!self.IsInitialized() || self.numel() == 0)
               throw std::runtime_error(
                   "Tensor not initialized or numel is 0.  could not pass "
                   "to shared memory. ");

             auto *holder = dynamic_cast<memory::allocation::Allocation *>(
                 self.Holder().get());
             PADDLE_ENFORCE_EQ(
                 platform::is_gpu_place(holder->place()), true,
                 platform::errors::InvalidArgument(
                     "Tensor is not on GPU. share_cuda only support GPU "
                     "Tensor, share_filename is for CPU tensor."));

             void *base_ptr = holder->base_ptr();
             ptrdiff_t offset_bytes = reinterpret_cast<char *>(holder->ptr()) -
                                      reinterpret_cast<char *>(base_ptr);

             cudaIpcMemHandle_t handle;
             PADDLE_ENFORCE_GPU_SUCCESS(cudaIpcGetMemHandle(&handle, base_ptr));

             auto _handle = py::bytes(reinterpret_cast<char *>(&handle),
                                      (py::ssize_t)CUDA_IPC_HANDLE_SIZE);

             // TODO(ZHUI): use cuda event, to avoid sync.
             const auto &device_id = paddle::platform::GetCurrentDeviceId();
             auto stream =
L
Leo Chen 已提交
755
                 paddle::platform::get_current_stream(device_id);
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
             stream->Synchronize();

             int type_idx = static_cast<int>(self.type());
             size_t data_size =
                 self.numel() *
                 framework::SizeOfType(
                     framework::TransToProtoVarType(self.type()));

             return py::make_tuple(_handle, (py::size_t)offset_bytes, data_size,
                                   type_idx, vectorize(self.dims()), self.lod(),
                                   device_id);
           },
           R"DOC(
           Serialize GPU Tensor by cudaIpcMemHandle.

           Returns:
               tuple: contrains handle, data size, data type,
                      tensor dims, lod information, device index.

           Examples:
               .. code-block:: python

                 import paddle
                 tensor = paddle.ones([3,3])
                 metainfo = tensor.value().get_tensor()._share_cuda()

      )DOC")
      .def("_new_shared_cuda",
           [](py::tuple t) {
             if (t.size() != 7)
               throw std::runtime_error(
                   "Invalid Tensor meta info for shared cuda tensor!");

             // 1. Create a new C++ instance
790
             phi::DenseTensor tensor;
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807

             // 2. Rebuild Allocation from handle
             const std::string &handle = t[0].cast<std::string>();
             ptrdiff_t offset_bytes = (ptrdiff_t)t[1].cast<int64_t>();
             auto device_id = t[6].cast<int>();
             auto base_ptr = memory::allocation::GetIpcBasePtr(handle);
             size_t size = t[2].cast<size_t>();
             void *dev = base_ptr.get();
             dev = reinterpret_cast<char *>(dev) + offset_bytes;

             auto shared_reader_holder =
                 std::make_shared<memory::allocation::CudaIpcAllocation>(
                     dev, size, device_id, std::move(base_ptr));

             // 3. Rebuild Tensor
             tensor.ResetHolderWithType(
                 shared_reader_holder,
808
                 static_cast<phi::DataType>(t[3].cast<int>()));
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
             tensor.Resize(phi::make_ddim(t[4].cast<std::vector<int>>()));
             tensor.set_lod(t[5].cast<framework::LoD>());

             return tensor;
           },
           R"DOC(
           Deserialize GPU lod tensor from cudaIpcMemHandle.

           Params:
               tuple: contrains handle, data size, data type,
                      tensor dims, lod information, device index.

           Examples:
               .. code-block:: python

                 import paddle
                 tensor = paddle.ones([3,3])
                 metainfo = tensor.value().get_tensor()._share_cuda()
                 tensor_from_shared = paddle.to_tensor(paddle.fluid.core.LoDTensor._new_shared_cuda(metainfo))

        )DOC")
#endif
      .def("_share_filename",
832
           [](phi::DenseTensor &self) {
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
             if (!self.IsInitialized() || self.numel() == 0)
               throw std::runtime_error(
                   "Tensor not initialized or numel is 0. could not pass to "
                   "shared memory. ");

             auto holder = self.Holder();
             PADDLE_ENFORCE_EQ(
                 platform::is_cpu_place(holder->place()) ||
                     platform::is_cuda_pinned_place(holder->place()),
                 true, platform::errors::InvalidArgument(
                           "Tensor is not on CPU. share_filename only "
                           "support CPU Tensor."));

             auto *mmap_allocation = dynamic_cast<
                 memory::allocation::RefcountedMemoryMapAllocation *>(
                 holder.get());
             // If the tensor is not shared, allocate memory map allocation.
             if (mmap_allocation == nullptr) {
               void *data_ptr = self.data();
               size_t data_size =
                   self.numel() *
                   framework::SizeOfType(
                       framework::TransToProtoVarType(self.type()));

               int flags = memory::allocation::MAPPED_SHAREDMEM |
                           memory::allocation::MAPPED_EXCLUSIVE;
               std::string handle = memory::allocation::GetIPCName();
860 861 862 863 864 865 866
               int find_id = -1;
               if (FLAGS_use_shm_cache) {
                 find_id = memory::allocation::MemoryMapAllocationPool::Instance().FindFromCache(flags, data_size); // NOLINT
               }
               if (find_id != -1) {
                 handle = memory::allocation::MemoryMapAllocationPool::Instance().GetById(find_id).file_name_; // NOLINT
               }
867 868
               auto shared_holder =
                   memory::allocation::AllocateRefcountedMemoryMapAllocation(
869
                       handle, flags, data_size, find_id);
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910

               // copy data & reset holder
               if (platform::is_cuda_pinned_place(holder->place())) {
#ifdef PADDLE_WITH_CUDA
                 memory::Copy(platform::CPUPlace(), shared_holder->ptr(),
                              platform::CUDAPinnedPlace(), data_ptr, data_size);
#endif
               } else {
                 memory::Copy(platform::CPUPlace(), shared_holder->ptr(),
                              platform::CPUPlace(), data_ptr, data_size);
               }
               self.ResetHolder(shared_holder);
               mmap_allocation = shared_holder.get();
             }
             int type_idx = static_cast<int>(self.type());

             return py::make_tuple(mmap_allocation->ipc_name(),
                                   mmap_allocation->size(), type_idx,
                                   vectorize(self.dims()), self.lod());
           },
           R"DOC(
           Serialize CPU lod tensor in shared memory to tuple.
           If the tensor is not in shared memory, we will copy it first.

           Returns:
               tuple: contrains ipc name, data size, data type,
                      tensor dims and lod imformation.

           Examples:
               .. code-block:: python

                 import paddle
                 tensor = paddle.ones([3,3])
                 metainfo = tensor.value().get_tensor()._share_filename()

       )DOC")
      .def("_new_shared_filename",
           [](py::tuple t) {  // __setstate__
             if (t.size() != 5)
               throw std::runtime_error("Invalid Tensor meta info state!");

911
             phi::DenseTensor tensor;
912 913 914 915 916 917

             // 2. Rebuild Allocation
             const std::string &ipc_name = t[0].cast<std::string>();
             size_t size = t[1].cast<size_t>();
             int flags = memory::allocation::MAPPED_SHAREDMEM |
                         memory::allocation::MAPPED_NOCREATE;
918 919 920 921
             int find_id = -1;
             if (FLAGS_use_shm_cache) {
               find_id = memory::allocation::MemoryMapAllocationPool::Instance().FindFromCache(flags, size, ipc_name, /*check_refcount*/ false); // NOLINT
             }
922 923
             auto shared_holder =
                 memory::allocation::AllocateRefcountedMemoryMapAllocation(
924
                     ipc_name, flags, size, find_id);
925 926 927 928

             // 3. Rebuild Tensor
             tensor.ResetHolderWithType(
                 shared_holder,
929
                 static_cast<phi::DataType>(t[2].cast<int>()));
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
             tensor.Resize(phi::make_ddim(t[3].cast<std::vector<int>>()));
             tensor.set_lod(t[4].cast<framework::LoD>());

             return tensor;
           },
           R"DOC(
           Deserialize CPU lod tensor from shared memory.

           Params:
               tuple: contrains ipc file name, data size, data type,
                      tensor dims and lod information.

           Examples:
               .. code-block:: python

                 import paddle
                 tensor = paddle.ones([3,3])
                 metainfo = tensor.value().get_tensor()._share_filename()
                 tensor_from_shared = paddle.to_tensor(paddle.fluid.core.LoDTensor._new_shared_filename(metainfo))

        )DOC")
      .def("_shared_incref",
952
           [](phi::DenseTensor &self) {
953 954 955 956 957 958 959 960 961 962 963
             auto *mmap_allocation = dynamic_cast<
                 memory::allocation::RefcountedMemoryMapAllocation *>(
                 self.Holder().get());
             if (mmap_allocation) {
               mmap_allocation->incref();
             }
           },
           R"DOC(
            Increase reference count of share_filename tensor.
      )DOC")
      .def("_shared_decref",
964
           [](phi::DenseTensor &self) {
965 966 967 968 969 970 971 972 973 974 975
             auto *mmap_allocation = dynamic_cast<
                 memory::allocation::RefcountedMemoryMapAllocation *>(
                 self.Holder().get());
             if (mmap_allocation) {
               mmap_allocation->decref();
             }
           },
           R"DOC(
            Decrease reference count of share_filename tensor.
      )DOC")
      .def(py::pickle(
976
          [](const phi::DenseTensor &t) {  // __getstate__
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
            auto holder = t.Holder();
            PADDLE_ENFORCE_EQ(platform::is_cpu_place(holder->place()), true,
                              platform::errors::PreconditionNotMet(
                                  "Tensor is not on CPU."
                                  "Now only Tensor on CPU can be serialized."));
            auto *mmap_writer_allocation =
                dynamic_cast<memory::allocation::MemoryMapWriterAllocation *>(
                    holder.get());
            PADDLE_ENFORCE_NOT_NULL(
                mmap_writer_allocation,
                platform::errors::PreconditionNotMet(
                    "Tensor is not in shared memory."
                    "Now only Tensor on shared memory can be serialized."));
            int type_idx = static_cast<int>(t.type());

            return py::make_tuple(mmap_writer_allocation->ipc_name(),
                                  mmap_writer_allocation->size(), type_idx,
                                  vectorize(t.dims()), t.lod());
          },
          [](py::tuple t) {  // __setstate__
            if (t.size() != 5)
              throw std::runtime_error("Invalid Tensor state!");

            // 1. Create a new C++ instance
1001
            phi::DenseTensor tensor;
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

            // 2. Rebuild Allocation
            const std::string &ipc_name = t[0].cast<std::string>();
            size_t size = t[1].cast<size_t>();
            auto shared_reader_holder =
                memory::allocation::RebuildMemoryMapReaderAllocation(ipc_name,
                                                                     size);

            // 3. Maintain global fd set
            VLOG(3) << "Tensor ipc name: " << ipc_name;
            memory::allocation::MemoryMapFdSet::Instance().Insert(ipc_name);

            // 4. Rebuild Tensor
            tensor.ResetHolderWithType(
                shared_reader_holder,
1017
                static_cast<phi::DataType>(t[2].cast<int>()));
1018 1019 1020 1021 1022 1023 1024
            tensor.Resize(phi::make_ddim(t[3].cast<std::vector<int>>()));
            tensor.set_lod(t[4].cast<framework::LoD>());

            return tensor;
          }));
#endif

L
LiYuRio 已提交
1025
#ifdef PADDLE_WITH_DISTRIBUTE
1026
  using phi::distributed::DistTensor;
L
LiYuRio 已提交
1027 1028 1029
  py::class_<DistTensor>(m, "DistTensor")
      .def(
          "get_tensor",
1030
          [](DistTensor &self) { return self.value(); },
L
LiYuRio 已提交
1031 1032 1033 1034 1035
          py::return_value_policy::reference)
      .def("numel",
           [](DistTensor &self) -> int64_t { return self.value().numel(); });
#endif

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  py::class_<phi::SelectedRows>(m, "SelectedRows")
      .def("__init__",
           [](phi::SelectedRows &instance) {
             new (&instance) phi::SelectedRows();
           })
      .def("__init__",
           [](phi::SelectedRows &instance,
              const std::vector<int64_t> rows,
              const int64_t &height) {
             new (&instance) phi::SelectedRows(rows, height);
           })
      .def(
          "get_tensor",
          [](phi::SelectedRows &self) { return self.mutable_value(); },
          py::return_value_policy::reference)
      .def("numel",
           [](phi::SelectedRows &self) -> int64_t {
             return self.value().numel();
           })
      .def("set_height", &phi::SelectedRows::set_height)
      .def("height", &phi::SelectedRows::height)
      .def("set_rows",
           [](phi::SelectedRows &self, std::vector<int64_t> rows) {
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
             self.set_rows(rows);
#else
H
Huang Jiyi 已提交
1062
        std::vector<int64_t> new_rows(rows);
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        self.set_rows(new_rows);
#endif
           })
      .def("sync_index",
           [](phi::SelectedRows &instance) { instance.SyncIndex(); })
      .def("rows", [](phi::SelectedRows &self) {
        auto rows = self.rows();
        std::vector<int64_t> new_rows;
        new_rows.reserve(rows.size());
        std::copy(rows.begin(), rows.end(), std::back_inserter(new_rows));
        return new_rows;
      });
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

  py::class_<phi::SparseCooTensor>(m, "SparseCooTensor")
      .def("__init__",
           [](phi::SparseCooTensor &instance) {
             new (&instance) phi::SparseCooTensor();
           })
      .def("numel",
           [](const phi::SparseCooTensor &self) -> int64_t {
             return self.numel();
           })
1085 1086 1087
      .def("indices", [](const phi::SparseCooTensor &self) -> phi::DenseTensor {
        return self.indices();
      });
1088 1089 1090 1091
}

}  // namespace pybind
}  // namespace paddle