tensor_utils.cc 10.0 KB
Newer Older
石晓伟 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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 "paddle/fluid/inference/lite/tensor_utils.h"
W
Wilber 已提交
16
#include <functional>
石晓伟 已提交
17
#include <map>
18
#include <memory>
石晓伟 已提交
19 20
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/inference/lite/engine.h"
21
#include "paddle/fluid/memory/allocation/allocator.h"
石晓伟 已提交
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

namespace paddle {
namespace inference {
namespace lite {
namespace utils {

using paddle::lite_api::TargetType;
using paddle::lite_api::PrecisionType;
using paddle::lite_api::DataLayoutType;

template <typename DstLoD, typename SrcLoD>
void SetLoD(DstLoD* dst, const SrcLoD& src) {
  dst->reserve(src.size());
  dst->clear();
  for (auto&& v : src) {
    dst->emplace_back(v);
  }
}
template void SetLoD<paddle::lite::LoD, framework::LoD>(
    paddle::lite::LoD* dst, const framework::LoD& src);
template void SetLoD<framework::LoD, paddle::lite::LoD>(
    framework::LoD* dst, const paddle::lite::LoD& src);

platform::Place GetNativePlace(const TargetType& type, int id = 0) {
  switch (type) {
    case TargetType::kHost:
    case TargetType::kX86:
W
Wilber 已提交
49
    case TargetType::kARM:
石晓伟 已提交
50 51 52
      return platform::CPUPlace();
    case TargetType::kCUDA:
      return platform::CUDAPlace(id);
53 54 55
    case TargetType::kXPU:
      LOG(ERROR) << "No corresponding device for XPU yet.";
      return platform::Place();
石晓伟 已提交
56
    default:
57 58 59
      PADDLE_THROW(
          platform::errors::Unavailable("Unsupported target type. Now only "
                                        "supports Host, x86, CUDA target."));
石晓伟 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      return platform::Place();
  }
}

TargetType GetLiteTargetType(const platform::Place& place) {
  if (platform::is_cpu_place(place)) {
    return TargetType::kHost;
  }
  return TargetType::kCUDA;
}

PrecisionType GetLitePrecisionType(framework::proto::VarType::Type type) {
  switch (type) {
    case framework::proto::VarType_Type_FP32:
      return PrecisionType::kFloat;
    case framework::proto::VarType_Type_INT8:
      return PrecisionType::kInt8;
    case framework::proto::VarType_Type_INT32:
      return PrecisionType::kInt32;
    case framework::proto::VarType_Type_INT64:
      return PrecisionType::kInt64;
    default:
82 83 84
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported precision type. Now only supports FP32, INT8, INT32 and "
          "INT64."));
石晓伟 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
      return PrecisionType::kUnk;
  }
}

framework::proto::VarType::Type GetNativePrecisionType(
    const PrecisionType& type) {
  switch (type) {
    case PrecisionType::kFloat:
      return framework::proto::VarType_Type_FP32;
    case PrecisionType::kInt8:
      return framework::proto::VarType_Type_INT8;
    case PrecisionType::kInt32:
      return framework::proto::VarType_Type_INT32;
    case PrecisionType::kInt64:
      return framework::proto::VarType_Type_INT64;
    default:
101 102 103
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported precision type. Now only supports FP32, INT8, INT32 and "
          "INT64."));
石晓伟 已提交
104 105 106 107 108 109 110 111 112
      return static_cast<framework::proto::VarType::Type>(-1);
  }
}

framework::DataLayout GetNativeLayoutType(const DataLayoutType& type) {
  switch (type) {
    case DataLayoutType::kNCHW:
      return framework::DataLayout::kNCHW;
    default:
113 114
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported layout type. Now only supports NCHW."));
石晓伟 已提交
115 116 117 118 119 120 121 122 123 124 125
      return static_cast<framework::DataLayout>(-1);
  }
}

void MemoryCopyAsync(const platform::Place& dst_place, void* dst_data,
                     const platform::Place& src_place, const void* src_data,
                     const size_t size, const platform::DeviceContext& ctx) {
  const platform::CPUPlace cpu_place;
  if (platform::is_cpu_place(dst_place) && platform::is_cpu_place(src_place)) {
    memory::Copy(cpu_place, dst_data, cpu_place, src_data, size);
  } else {
126
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
石晓伟 已提交
127 128
    if (platform::is_cpu_place(dst_place) &&
        platform::is_gpu_place(src_place)) {
129 130
      PADDLE_THROW(platform::errors::Unimplemented(
          "Lite::MemoryCopy GPU->CPU is not yet implemented."));
石晓伟 已提交
131 132
    } else if (platform::is_gpu_place(dst_place) &&
               platform::is_cpu_place(src_place)) {
133 134
      PADDLE_THROW(platform::errors::Unimplemented(
          "Lite::MemoryCopy CPU->GPU is not yet implemented."));
石晓伟 已提交
135 136
    } else if (platform::is_gpu_place(dst_place) &&
               platform::is_gpu_place(src_place)) {
137
      auto gpu_place = BOOST_GET_CONST(platform::CUDAPlace, src_place);
石晓伟 已提交
138 139 140 141 142
      memory::Copy(
          gpu_place, dst_data, gpu_place, src_data, size,
          static_cast<const platform::CUDADeviceContext&>(ctx).stream());
    }
#else
143 144
    PADDLE_THROW(platform::errors::PreconditionNotMet(
        "You must define PADDLE_WITH_CUDA for using CUDAPlace."));
石晓伟 已提交
145 146 147 148
#endif
  }
}

W
Wilber 已提交
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 181 182 183
void* GetLiteTensorDataPtr(paddle::lite_api::Tensor* src,
                           PrecisionType precision_type,
                           TargetType target_type) {
  void* res{nullptr};
  switch (precision_type) {
    case PrecisionType::kFloat:
      res = static_cast<void*>(src->mutable_data<float>(target_type));
      break;
    case PrecisionType::kInt8:
      res = static_cast<void*>(src->mutable_data<int8_t>(target_type));
      break;
    case PrecisionType::kInt32:
      res = static_cast<void*>(src->mutable_data<int32_t>(target_type));
      break;
    case PrecisionType::kInt64:
      res = static_cast<void*>(src->mutable_data<int64_t>(target_type));
      break;
    default:
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported precision type. Now only supports FP32, INT8, INT32 and "
          "INT64."));
      break;
  }
  return res;
}

int64_t GetLiteTensorNumel(const paddle::lite_api::Tensor& tensor) {
  auto shape = tensor.shape();
  int64_t numel = std::accumulate(shape.begin(), shape.end(), 1,
                                  std::multiplies<int64_t>());
  return numel;
}

void InitDstTensor(paddle::lite_api::Tensor* dst,
                   const framework::LoDTensor& src) {
石晓伟 已提交
184 185 186
  // Currently, Lite needs to explicitly specify the target type of
  // the input tensor.
  constexpr int empty_size = 0;
W
Wilber 已提交
187 188 189 190 191 192 193
  dst->Resize({empty_size});
  GetLiteTensorDataPtr(dst, GetLitePrecisionType(src.type()),
                       GetLiteTargetType(src.place()));
  dst->SetPrecision(GetLitePrecisionType(src.type()));
  paddle::lite::LoD lite_lod;
  SetLoD(&lite_lod, src.lod());
  dst->SetLoD(lite_lod);
石晓伟 已提交
194 195
}

W
Wilber 已提交
196 197
void InitDstTensor(framework::LoDTensor* dst,
                   const paddle::lite_api::Tensor& src) {
石晓伟 已提交
198
  dst->mutable_data(inference::lite::utils::GetNativePlace(src.target()),
W
Wilber 已提交
199
                    GetNativePrecisionType(src.precision()));
石晓伟 已提交
200 201 202 203
  SetLoD(dst->mutable_lod(), src.lod());
}

template <>
W
Wilber 已提交
204 205
void TensorCopyAsync(paddle::lite_api::Tensor* dst,
                     const framework::LoDTensor& src,
石晓伟 已提交
206 207 208 209 210 211 212
                     const platform::DeviceContext& ctx) {
  InitDstTensor(dst, src);
  const platform::Place& src_place = src.place();
  const platform::Place& dst_place = GetNativePlace(dst->target());
  const size_t bytes =
      static_cast<size_t>(src.numel()) * framework::SizeOfType(src.type());
  dst->Resize(framework::vectorize(src.dims()));
213
  const void* src_data = src.data();
W
Wilber 已提交
214 215 216
  void* dst_data{nullptr};
  dst_data = GetLiteTensorDataPtr(dst, GetLitePrecisionType(src.type()),
                                  GetLiteTargetType(src.place()));
217 218
  VLOG(3) << "[CopyAsync fluid -> lite] Bytes = " << bytes << ", src = " << &src
          << ", dst = " << dst << ", src_type = " << src.type();
石晓伟 已提交
219
  MemoryCopyAsync(dst_place, dst_data, src_place, src_data, bytes, ctx);
W
Wilber 已提交
220
  VLOG(3) << "[Lite memory size] Bytes = " << bytes;
石晓伟 已提交
221 222 223
}

template <>
W
Wilber 已提交
224 225
void TensorCopyAsync(framework::LoDTensor* dst,
                     const paddle::lite_api::Tensor& src,
石晓伟 已提交
226
                     const platform::DeviceContext& ctx) {
W
Wilber 已提交
227
  dst->Resize(paddle::framework::make_ddim(src.shape()));
石晓伟 已提交
228 229 230
  InitDstTensor(dst, src);
  const platform::Place& src_place = GetNativePlace(src.target());
  const platform::Place& dst_place = dst->place();
W
Wilber 已提交
231 232 233
  int64_t src_numel = GetLiteTensorNumel(src);
  const size_t bytes = src_numel * framework::SizeOfType(dst->type());
  const void* src_data = src.data<void>();
石晓伟 已提交
234 235
  // When Lite is ready, the source type needs to be modified here.
  void* dst_data = dst->mutable_data(dst_place, dst->type());
236 237
  VLOG(3) << "[CopyAsync lite -> fluid] Bytes = " << bytes << ", src = " << &src
          << ", dst = " << dst << ", src_type = " << dst->type();
石晓伟 已提交
238
  MemoryCopyAsync(dst_place, dst_data, src_place, src_data, bytes, ctx);
W
Wilber 已提交
239
  VLOG(3) << "[Lite memory size] Bytes = " << bytes;
石晓伟 已提交
240 241
}

242
template <>
W
Wilber 已提交
243
void TensorDataShare(paddle::lite_api::Tensor* dst, framework::LoDTensor* src) {
244
  dst->Resize(framework::vectorize(src->dims()));
245
  dst->ShareExternalMemory(src->data(), src->memory_size(),
W
Wilber 已提交
246 247 248 249 250
                           GetLiteTargetType(src->place()));
  dst->SetPrecision(GetLitePrecisionType(src->type()));
  paddle::lite::LoD lite_lod;
  SetLoD(&lite_lod, src->lod());
  dst->SetLoD(lite_lod);
251 252 253
}

template <>
W
Wilber 已提交
254 255
void TensorDataShare(framework::LoDTensor* dst, paddle::lite_api::Tensor* src) {
  void* src_raw_data =
W
Wilber 已提交
256 257 258 259
      GetLiteTensorDataPtr(src, src->precision(), src->target());
  size_t memory_size =
      GetLiteTensorNumel(*src) *
      framework::SizeOfType(GetNativePrecisionType(src->precision()));
260 261
  std::shared_ptr<pten::Allocation> holder(new pten::Allocation(
      src_raw_data, memory_size, GetNativePlace(src->target())));
W
Wilber 已提交
262
  dst->Resize(paddle::framework::make_ddim(src->shape()));
263
  SetLoD(dst->mutable_lod(), src->lod());
W
Wilber 已提交
264
  dst->ResetHolderWithType(holder, GetNativePrecisionType(src->precision()));
265 266
}

石晓伟 已提交
267 268 269 270
}  // namespace utils
}  // namespace lite
}  // namespace inference
}  // namespace paddle