tensor_method.cc 9.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

15
// clang-format off
16
#include "paddle/phi/api/include/tensor.h"
17

18
#include "paddle/phi/common/int_array.h"
19 20 21
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/tensor_base.h"

22
#include "paddle/phi/api/include/sparse_api.h"
23 24 25
#include "paddle/phi/api/lib/api_gen_utils.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/infermeta/unary.h"
26
// clang-format off
27

28 29 30 31
namespace paddle {
namespace experimental {
// declare cast api
Tensor cast(const Tensor &x, DataType out_dtype);
32
Tensor copy_to(const Tensor &x, const Place &place, bool blocking);
33 34 35 36 37

Tensor Tensor::cast(DataType target_type) const {
  return experimental::cast(*this, target_type);
}

38
Tensor Tensor::copy_to(const Place &place, bool blocking) const {
39
  return experimental::copy_to(*this, place, blocking);
40 41 42
}

template <typename T>
43
Tensor Tensor::copy_to(const Place &target_place) const {
44 45 46 47 48 49
  LOG_FIRST_N(WARNING, 1)
      << "The Tensor's `copy_to` method is deprecated since version "
         "2.3, and will be removed in version 2.4, please use "
         "`copy_to` method without template argument instead. "
         "reason: copying a Tensor to another device does not need "
         "to specify the data type template argument.";
50
  return copy_to(target_place, /*blocking=*/false);
51 52 53
}

template PADDLE_API Tensor
54
Tensor::copy_to<float>(const Place &target_place) const;
55
template PADDLE_API Tensor
56
Tensor::copy_to<double>(const Place &target_place) const;
57
template PADDLE_API Tensor
58
Tensor::copy_to<int64_t>(const Place &target_place) const;
59
template PADDLE_API Tensor
60
Tensor::copy_to<int32_t>(const Place &target_place) const;
61
template PADDLE_API Tensor
62
Tensor::copy_to<uint8_t>(const Place &target_place) const;
63
template PADDLE_API Tensor
64
Tensor::copy_to<int8_t>(const Place &target_place) const;
65
template PADDLE_API Tensor
66
Tensor::copy_to<int16_t>(const Place &target_place) const;
67
template PADDLE_API Tensor
68
Tensor::copy_to<bool>(const Place &target_place) const;
69
template PADDLE_API Tensor
70 71 72 73 74
Tensor::copy_to<phi::dtype::complex<float>>(const Place &target_place) const;
template PADDLE_API Tensor
Tensor::copy_to<phi::dtype::complex<double>>(const Place &target_place) const;
template PADDLE_API Tensor
Tensor::copy_to<phi::dtype::float16>(const Place &target_place) const;
75

76 77 78
void Tensor::copy_(const Tensor &src,
                   const phi::Place &target_place,
                   bool blocking) {
79
  if (!src.initialized()) {
80
    VLOG(8) << "Src is empty, skip copy";
81 82
    return;
  }
83 84 85
  // Prepare copy kernel key and outputs
  auto kernel_key_set = ParseKernelKeyByInputArgs(src);
  KernelType kernel_type = ParseKernelTypeByInputArgs(src);
86
  VLOG(3) << "Deep copy Tensor from " << src.name() << " to " << name();
87
  if (initialized()) {
88 89
    PADDLE_ENFORCE_EQ(dtype(),
                      src.dtype(),
J
Jiabin Yang 已提交
90
                      phi::errors::PreconditionNotMet(
91 92 93 94 95 96
                          "Tensor %s has different data type with Tensor %s, "
                          "Tensor Copy cannot be performed!",
                          name(),
                          src.name()));
    PADDLE_ENFORCE_EQ(impl()->type_info().id(),
                      src.impl()->type_info().id(),
J
Jiabin Yang 已提交
97
                      phi::errors::PreconditionNotMet(
98 99 100 101
                          "Tensor %s has different type with Tensor %s, Tensor "
                          "Copy cannot be performed!",
                          name(),
                          src.name()));
102
    PADDLE_ENFORCE_EQ(target_place,
C
Chen Weihang 已提交
103
                      place(),
J
Jiabin Yang 已提交
104
                      phi::errors::PreconditionNotMet(
105 106 107
                          "Place is different of dst tensor and args %s, which "
                          "current tensor holds %s "
                          "Copy cannot be performed!",
J
Jiabin Yang 已提交
108
                          target_place,
C
Chen Weihang 已提交
109 110 111
                          place()));
    kernel_key_set.backend_set = kernel_key_set.backend_set |
                                 BackendSet(phi::TransToPhiBackend(place()));
112 113 114 115 116 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  } else {
    // Deep Copy AutoGrad info from src to self.
    *autograd_meta_ = *(src.autograd_meta_);
  }

  auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();
  auto *dev_ctx = GetDeviceContextByBackend(kernel_key.backend());
  Backend kernel_backend = Backend::UNDEFINED;
  DataLayout kernel_layout = DataLayout::UNDEFINED;
  DataType kernel_data_type = DataType::UNDEFINED;

  if (kernel_backend == Backend::UNDEFINED ||
      kernel_layout == DataLayout::UNDEFINED ||
      kernel_data_type == DataType::UNDEFINED) {
    if (kernel_backend == Backend::UNDEFINED) {
      kernel_backend = kernel_key.backend();
    }
    if (kernel_layout == DataLayout::UNDEFINED) {
      kernel_layout = kernel_key.layout();
    }
    if (kernel_data_type == DataType::UNDEFINED) {
      kernel_data_type = kernel_key.dtype();
    }
  }

  if (kernel_type == KernelType::DENSE_TENSOR_KENREL) {
    auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
        "copy", {kernel_backend, kernel_layout, kernel_data_type});
    VLOG(6) << "copy API kernel key: " << kernel_key;
    VLOG(6) << "copy API kernel: " << kernel;
    using kernel_signature = void (*)(const platform::DeviceContext &,
                                      const phi::DenseTensor &,
                                      phi::Place,
                                      bool,
                                      phi::DenseTensor *);
    SetKernelOutput(kernel_backend, this);
    phi::MetaTensor meta_out(impl_.get());
    phi::UnchangedInferMeta(
        MakeMetaTensor(
            *(std::static_pointer_cast<phi::DenseTensor>(src.impl_))),
        &meta_out);
    auto *kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
    (*kernel_fn)(*dev_ctx,
                 (*(std::static_pointer_cast<phi::DenseTensor>(src.impl_))),
                 target_place,
                 blocking,
                 static_cast<phi::DenseTensor *>(impl_.get()));
  } else if (kernel_type == KernelType::SELECTED_ROWS_KENREL) {
    auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
        "copy_sr", {kernel_backend, kernel_layout, kernel_data_type});
    VLOG(6) << "copy API kernel key: " << kernel_key;
    VLOG(6) << "copy API kernel: " << kernel;
    using kernel_signature = void (*)(const platform::DeviceContext &,
                                      const phi::SelectedRows &,
                                      phi::Place,
                                      bool,
                                      phi::SelectedRows *);
    SetSelectedRowsKernelOutput(kernel_backend, this);
    phi::MetaTensor meta_out(impl_.get());
    phi::UnchangedInferMeta(
        MakeMetaTensor(
            *(std::static_pointer_cast<phi::SelectedRows>(src.impl_))),
        &meta_out);
    auto *kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
    (*kernel_fn)(*dev_ctx,
                 (*(std::static_pointer_cast<phi::SelectedRows>(src.impl_))),
                 target_place,
                 blocking,
                 static_cast<phi::SelectedRows *>(impl_.get()));
181 182 183 184 185 186 187 188 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
  } else if (kernel_type == KernelType::SPARSE_COO_KERNEL) {
    auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
        "copy_sparse_coo", {kernel_backend, kernel_layout, kernel_data_type});
    VLOG(6) << "copy API kernel key: " << kernel_key;
    VLOG(6) << "copy API kernel: " << kernel;
    using kernel_signature = void (*)(const platform::DeviceContext &,
                                      const phi::SparseCooTensor &,
                                      phi::Place,
                                      bool,
                                      phi::SparseCooTensor *);
    this->set_impl(std::make_shared<phi::SparseCooTensor>());
    auto *kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
    (*kernel_fn)(*dev_ctx,
                 (*(std::static_pointer_cast<phi::SparseCooTensor>(src.impl_))),
                 target_place,
                 blocking,
                 static_cast<phi::SparseCooTensor *>(impl_.get()));
  } else if (kernel_type == KernelType::SPARSE_CSR_KERNEL) {
    auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
        "copy_sparse_csr", {kernel_backend, kernel_layout, kernel_data_type});
    VLOG(6) << "copy API kernel key: " << kernel_key;
    VLOG(6) << "copy API kernel: " << kernel;
    using kernel_signature = void (*)(const platform::DeviceContext &,
                                      const phi::SparseCsrTensor &,
                                      phi::Place,
                                      bool,
                                      phi::SparseCsrTensor *);
    this->set_impl(std::make_shared<phi::SparseCsrTensor>());
    auto *kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
    (*kernel_fn)(*dev_ctx,
                 (*(std::static_pointer_cast<phi::SparseCsrTensor>(src.impl_))),
                 target_place,
                 blocking,
                 static_cast<phi::SparseCsrTensor *>(impl_.get()));
215
  } else {
J
Jiabin Yang 已提交
216
    PADDLE_THROW(phi::errors::InvalidArgument(
217 218
        "We currently only support dense tensor copy for now and if u need to "
        "copy selected rows please raise a issue."));
219 220 221
  }
}

222 223 224 225 226 227 228 229 230 231 232 233
Tensor Tensor::to_sparse_coo(const int64_t sparse_dim) const {
  return experimental::sparse::to_sparse_coo(*this, sparse_dim);
}

Tensor Tensor::to_sparse_csr() const {
  return experimental::sparse::to_sparse_csr(*this);
}

Tensor Tensor::to_dense() const {
  return experimental::sparse::to_dense(*this);
}

234 235
}  // namespace experimental
}  // namespace paddle