dlpack_tensor.cc 5.4 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (c) 2018 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.
6
633WHU 已提交
14
#include <unordered_map>
S
sneaxiy 已提交
15

Y
Yu Yang 已提交
16
#include "paddle/fluid/framework/data_type.h"
6
633WHU 已提交
17
#include "paddle/fluid/framework/dlpack_tensor.h"
S
sneaxiy 已提交
18 19 20 21 22 23 24 25
namespace paddle {
namespace framework {

namespace internal {
template <typename T>
static ::DLDataType GetDLDataTypeCode() {
  ::DLDataType dtype;
  if (std::is_same<T, platform::float16>::value ||
26
      std::is_same<T, platform::bfloat16>::value ||
S
sneaxiy 已提交
27 28 29 30 31 32 33
      std::is_floating_point<T>::value) {
    dtype.code = kDLFloat;
  } else if (std::is_unsigned<T>::value) {
    dtype.code = kDLUInt;
  } else if (std::is_integral<T>::value) {
    dtype.code = kDLInt;
  } else {
34 35 36 37
    PADDLE_THROW(platform::errors::Unavailable(
        "Unsupported data type (%s), only supports float16, float, unsigned "
        "int and int.",
        platform::demangle(typeid(T).name())));
S
sneaxiy 已提交
38 39 40 41 42 43
  }
  dtype.bits = 8 * sizeof(T);
  dtype.lanes = 1;
  return dtype;
}

Y
Yu Yang 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56
static std::unordered_map<int, ::DLDataType> CreateDLDataTypeMap() {
  static std::unordered_map<int, ::DLDataType> result;

#define REG_DL_DATA_TYPE(cpp_type, proto_type) \
  result[static_cast<int>(proto_type)] = GetDLDataTypeCode<cpp_type>()

  _ForEachDataType_(REG_DL_DATA_TYPE);
#undef REG_DL_DATA_TYPE
  return result;
}

static DLDataType GetDLDataTypeFromTypeIndex(proto::VarType::Type type) {
  static auto type_to_dtype_map = CreateDLDataTypeMap();
S
sneaxiy 已提交
57
  static auto type_to_dtype_map_end_it = type_to_dtype_map.end();
Y
Yu Yang 已提交
58
  auto it = type_to_dtype_map.find(static_cast<int>(type));
59 60 61
  PADDLE_ENFORCE_NE(it, type_to_dtype_map_end_it,
                    platform::errors::InvalidArgument(
                        "Unsupported data type (%s).", DataTypeToString(type)));
S
sneaxiy 已提交
62 63 64 65 66 67
  return it->second;
#undef REG_DL_DATA_TYPE
}

struct DLContextVisitor : public boost::static_visitor<::DLContext> {
  inline ::DLContext operator()(const platform::CPUPlace &place) const {
S
sneaxiy 已提交
68
    ::DLContext ctx;
S
sneaxiy 已提交
69 70 71 72 73
    ctx.device_type = kDLCPU;
    ctx.device_id = 0;
    return ctx;
  }

74 75 76 77 78
  inline ::DLContext operator()(const platform::XPUPlace &place) const {
    PADDLE_THROW(
        platform::errors::Unimplemented("platform::XPUPlace is not supported"));
  }

S
sneaxiy 已提交
79 80
  inline ::DLContext operator()(const platform::CUDAPlace &place) const {
#ifdef PADDLE_WITH_CUDA
S
sneaxiy 已提交
81
    ::DLContext ctx;
S
sneaxiy 已提交
82 83 84 85
    ctx.device_type = kDLGPU;
    ctx.device_id = place.device;
    return ctx;
#else
86 87
    PADDLE_THROW(platform::errors::Unavailable(
        "platform::CUDAPlace is not supported in CPU only version."));
S
sneaxiy 已提交
88 89 90 91 92
#endif
  }

  inline ::DLContext operator()(const platform::CUDAPinnedPlace &place) const {
#ifdef PADDLE_WITH_CUDA
S
sneaxiy 已提交
93
    ::DLContext ctx;
S
sneaxiy 已提交
94 95 96 97
    ctx.device_type = kDLCPUPinned;
    ctx.device_id = 0;
    return ctx;
#else
98 99
    PADDLE_THROW(platform::errors::Unavailable(
        "platform::CUDAPinnedPlace is not supported in CPU only version."));
S
sneaxiy 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
#endif
  }
};
}  // namespace internal

DLPackTensor::DLPackTensor(const Tensor &tensor, LaneType lanes) {
  // init data, data buffer
  t_.data = const_cast<void *>(tensor.data<void>());

  // init ctx, DLContext type with device_type and device_id
  auto place = tensor.place();
  t_.ctx = boost::apply_visitor(internal::DLContextVisitor(), place);

  // init dtype
  t_.dtype = internal::GetDLDataTypeFromTypeIndex(tensor.type());
  t_.dtype.lanes = lanes;

  // init ndim, tensor rank
  auto &dims = tensor.dims();
  using DimType = decltype(t_.ndim);  // int
  t_.ndim = static_cast<DimType>(dims.size());

  // init shape, tensor dims
  t_.shape = shape_;
  for (DimType i = 0; i < t_.ndim; ++i) {
    t_.shape[i] = dims[i];
  }

  // init strides, nullptr means the tensor is compact
  t_.strides = nullptr;

  // init byte_offset
  t_.byte_offset = 0;
}

6
633WHU 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
::DLManagedTensor *DLPackTensor::ToCudfCompatibleDLManagedTensor() {
  // init shape, tensor dims
  // for DLManagedTensor shape need to be compatible with ndim
  // refer to cupy and cudf, we new int64[ndim]
  auto shape = new int64_t[t_.ndim];
  using DimType = decltype(t_.ndim);  // int
  for (DimType i = 0; i < t_.ndim; ++i) {
    shape[i] = t_.shape[i];
  }
  t_.shape = shape;

  // init strides, nullptr means the tensor is compact
  // refer to cupy and cudf, the compact tensor first dim's strides need to be 1
  // and second dim's strides need to be length of rows of cudf
  // cudf now only support dim=2
150 151 152 153
  PADDLE_ENFORCE_LE(t_.ndim, 2, platform::errors::InvalidArgument(
                                    "cudf now only supports dimension is 2, "
                                    "but received dimension is %d.",
                                    t_.ndim));
6
633WHU 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

  if (t_.ndim > 1)
    t_.strides = new int64_t[2]{1, t_.shape[1]};
  else
    t_.strides = new int64_t[1]{1};

  auto tensor = new DLManagedTensor;
  tensor->dl_tensor = t_;

  tensor->deleter = [](DLManagedTensor *arg) {
    delete[] arg->dl_tensor.shape;
    delete[] arg->dl_tensor.strides;
    delete arg;
  };

  tensor->manager_ctx = nullptr;

  return tensor;
}

S
sneaxiy 已提交
174 175
}  // namespace framework
}  // namespace paddle