api_custom_impl.cc 6.4 KB
Newer Older
1
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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
#include "paddle/phi/api/lib/api_custom_impl.h"
16

17
#include "paddle/phi/api/lib/api_gen_utils.h"
18 19 20
#include "paddle/phi/api/lib/data_transform.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/api/lib/utils/storage.h"
21
#include "paddle/phi/core/compat/convert_utils.h"
22 23
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/core/meta_tensor.h"
24 25 26
#include "paddle/phi/infermeta/binary.h"
#include "paddle/phi/infermeta/multiary.h"
#include "paddle/phi/infermeta/nullary.h"
27
#include "paddle/phi/infermeta/unary.h"
28

29
#include "glog/logging.h"
30

31 32 33
namespace paddle {
namespace experimental {

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
// TODO(chenweihang):  the original sum grad op can support higher-level
// differentiation,
// but if we use this impl, it will not support. We need to be able to reuse
// the autograd API here, which is not yet implemented
// TODO(chenweihang): we should support call generated api in custom api impl
std::vector<Tensor> add_n_grad_impl(const std::vector<Tensor>& x,
                                    const Tensor& out_grad) {
  auto kernel_key_set = ParseKernelKeyByInputArgs(out_grad);
  auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();

  Backend kernel_backend = kernel_key.backend();
  DataLayout kernel_layout = kernel_key.layout();
  DataType kernel_data_type = kernel_key.dtype();

  auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
      "scale", {kernel_backend, kernel_layout, kernel_data_type});
  VLOG(6) << "add_n_grad API kernel key: [" << kernel_backend << ", "
          << kernel_layout << ", " << kernel_data_type << "]";
  VLOG(6) << "add_n_grad API kernel: " << kernel;

  auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);

  auto dense_out_grad = PrepareData(out_grad, kernel.InputAt(0), {});

  size_t out_number = x.size();
  std::vector<Tensor> x_grad;
  auto dense_x_grad = SetKernelOutput(out_number, kernel_backend, &x_grad);

  using kernel_signature = void (*)(const platform::DeviceContext&,
                                    const phi::DenseTensor&,
                                    const phi::Scalar&,
                                    float,
                                    bool,
                                    phi::DenseTensor*);
  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();

  for (auto* dense_x_grad_t : dense_x_grad) {
    phi::MetaTensor meta_out(dense_x_grad_t);
    phi::UnchangedInferMeta(MakeMetaTensor(*dense_out_grad), &meta_out);
    (*kernel_fn)(
        *dev_ctx, *dense_out_grad, phi::Scalar(1.0), 0.0, true, dense_x_grad_t);
  }

  return x_grad;
}

80
Tensor copy_to_impl(const Tensor& x, Place place, bool blocking) {
81
  auto kernel_key_set = ParseKernelKeyByInputArgs(x);
82 83
  kernel_key_set.backend_set =
      kernel_key_set.backend_set | BackendSet(phi::TransToPhiBackend(place));
84
  auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();
85
  auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
86 87
      "copy", kernel_key);

88 89
  VLOG(6) << "copy API kernel key: " << kernel_key;
  VLOG(6) << "copy API kernel: " << kernel;
90 91 92

  auto* dev_ctx = GetDeviceContextByBackend(kernel_key.backend());

93
  auto dense_x = TensorToDenseTensor(x);
94 95

  Tensor out;
96 97 98 99 100 101 102 103 104
  auto kernel_out = SetKernelOutput(kernel_key.backend(), &out);
  phi::MetaTensor meta_out(kernel_out);
  phi::UnchangedInferMeta(*dense_x, &meta_out);

  using kernel_signature = void (*)(const platform::DeviceContext&,
                                    const phi::DenseTensor&,
                                    phi::Place,
                                    bool,
                                    phi::DenseTensor*);
105

106
  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
107
  (*kernel_fn)(*dev_ctx, *dense_x, place, blocking, kernel_out);
108 109 110 111

  return out;
}

112
std::vector<Tensor> split_impl(const Tensor& x,
113
                               const IntArray& num_or_sections,
114 115
                               const Scalar& axis) {
  auto kernel_key_set = ParseKernelKeyByInputArgs(x);
116
  auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();
117 118 119 120

  Backend kernel_backend = kernel_key.backend();
  DataLayout kernel_layout = kernel_key.layout();
  DataType kernel_data_type = kernel_key.dtype();
C
chentianyu03 已提交
121

122
  auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
C
chentianyu03 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
      "split", {kernel_backend, kernel_layout, kernel_data_type});
  VLOG(6) << "split API kernel key: [" << kernel_backend << ", "
          << kernel_layout << ", " << kernel_data_type << "]";
  VLOG(6) << "split API kernel: " << kernel;

  auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);

  auto dense_x = PrepareData(x, kernel.InputAt(0), {});

  // Calculate the number of out tensors
  size_t out_number;
  if (num_or_sections.GetData().size() == 1) {
    out_number = num_or_sections.GetData()[0];
  } else {
    out_number = num_or_sections.GetData().size();
  }

  std::vector<Tensor> out;
  auto dense_outs = SetKernelOutput(out_number, kernel_backend, &out);
142
  std::vector<phi::MetaTensor> meta_outs;
143 144 145
  meta_outs.reserve(out_number);
  std::vector<phi::MetaTensor*> meta_out_ptrs;
  meta_out_ptrs.reserve(out_number);
C
chentianyu03 已提交
146 147
  for (size_t i = 0; i < out_number; ++i) {
    meta_outs.push_back(dense_outs[i]);
148
    meta_out_ptrs.push_back(&meta_outs.back());
C
chentianyu03 已提交
149 150
  }

151
  phi::SplitInferMeta(
152
      MakeMetaTensor(*dense_x), num_or_sections, axis, meta_out_ptrs);
C
chentianyu03 已提交
153 154

  using kernel_signature = void (*)(const platform::DeviceContext&,
155
                                    const phi::DenseTensor&,
156
                                    const phi::IntArray&,
157 158
                                    const phi::Scalar&,
                                    std::vector<phi::DenseTensor*>&);
C
chentianyu03 已提交
159 160 161
  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
  (*kernel_fn)(*dev_ctx,
               *dense_x,
162
               phi::IntArray(num_or_sections),
163
               phi::Scalar(axis),
C
chentianyu03 已提交
164 165 166 167
               dense_outs);

  return out;
}
168

169 170
}  // namespace experimental
}  // namespace paddle