dense_tensor_kernels.cc 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2022 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
#include "paddle/infrt/kernel/phi/dense_tensor_kernels.h"
W
Wilber 已提交
16
#include "llvm/Support/ErrorHandling.h"
17
#include "paddle/infrt/common/string.h"
18 19
#include "paddle/infrt/dialect/phi/data_type.h"
#include "paddle/infrt/kernel/phi/context_kernels.h"
20 21
#include "paddle/infrt/paddle/model_parser.h"
#include "paddle/infrt/paddle/scope.h"
22
#include "paddle/infrt/tensor/tensor_map.h"
W
Wilber 已提交
23 24 25 26 27 28
#include "paddle/phi/backends/all_context.h"
#include "paddle/phi/common/place.h"

#ifdef INFRT_WITH_GPU
#include <cuda_runtime.h>
#endif
29

30 31 32 33 34 35 36 37 38 39 40 41
namespace paddle {
namespace platform {
using DeviceContext = ::phi::DeviceContext;
}  // namespace platform
namespace framework {
using LoDTensor = ::phi::DenseTensor;
void DeserializeFromStream(std::istream& is,
                           LoDTensor* tensor,
                           const platform::DeviceContext& dev_ctx);
}
}  // namespace paddle

42 43
namespace infrt {
namespace kernel {
44
namespace phi {
45

46 47
::phi::DenseTensor CreateDenseTensor(
    const ::phi::CPUContext& context,
48
    host_context::Attribute<std::vector<int64_t>> dims,
49
    host_context::Attribute<std::vector<int64_t>> lod,
50
    host_context::Attribute<::infrt::LayoutType> layout,
51 52 53
    host_context::Attribute<::infrt::PrecisionType> precision) {
  return ::phi::DenseTensor(
      const_cast<::phi::Allocator*>(&context.GetAllocator()),
54
      ::phi::DenseTensorMeta(ConvertPrecisionToPhi(precision.get()),
55
                             ::phi::make_ddim(dims.get()),
56
                             ConvertLayoutToPhi(layout.get()),
57
                             {}));
58 59
}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
::phi::DenseTensor CreateInitedDenseTensorF32(
    const ::phi::CPUContext& context,
    host_context::Attribute<std::vector<int64_t>> dims,
    host_context::Attribute<std::vector<int64_t>> lod,
    host_context::Attribute<::infrt::LayoutType> layout,
    host_context::Attribute<float> value) {
  ::phi::DenseTensor dense_tensor(
      const_cast<::phi::Allocator*>(&context.GetAllocator()),
      ::phi::DenseTensorMeta(
          ConvertPrecisionToPhi(::infrt::PrecisionType::FLOAT32),
          ::phi::make_ddim(dims.get()),
          ConvertLayoutToPhi(layout.get()),
          {}));
  float* a_data = dense_tensor.mutable_data<float>(::phi::CPUPlace());
  for (int64_t i = 0; i < dense_tensor.numel(); ++i) {
    a_data[i] = value.get();
  }
  return dense_tensor;
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
::phi::DenseTensor CreateHostInitedDenseTensorF32(
    const ::phi::CPUContext& context,
    host_context::Attribute<std::vector<int64_t>> dims,
    host_context::Attribute<std::vector<int64_t>> lod,
    host_context::Attribute<::infrt::LayoutType> layout,
    host_context::Attribute<std::vector<float>> values) {
  ::phi::DenseTensor dense_tensor(
      const_cast<::phi::Allocator*>(&context.GetAllocator()),
      ::phi::DenseTensorMeta(
          ConvertPrecisionToPhi(::infrt::PrecisionType::FLOAT32),
          ::phi::make_ddim(dims.get()),
          ConvertLayoutToPhi(layout.get()),
          {}));
  CHECK_EQ(dense_tensor.numel(), static_cast<int64_t>(values.get().size()));
  float* data = dense_tensor.mutable_data<float>(::phi::CPUPlace());
  for (int64_t i = 0; i < dense_tensor.numel(); ++i) {
    data[i] = values.get()[i];
  }
  return dense_tensor;
}

W
Wilber 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114
::phi::DenseTensor CreateGPUDenseTensor(
    const ::phi::GPUContext& context,
    host_context::Attribute<std::vector<int64_t>> dims,
    host_context::Attribute<std::vector<int64_t>> lod,
    host_context::Attribute<::infrt::LayoutType> layout,
    host_context::Attribute<::infrt::PrecisionType> precision) {
  return ::phi::DenseTensor(
      const_cast<::phi::Allocator*>(&context.GetAllocator()),
      ::phi::DenseTensorMeta(ConvertPrecisionToPhi(precision.get()),
                             ::phi::make_ddim(dims.get()),
                             ConvertLayoutToPhi(layout.get()),
                             {}));
}

115
void FillDenseTensorF32(::phi::DenseTensor* dense_tensor,
116
                        host_context::Attribute<std::vector<float>> value) {
W
Wilber 已提交
117
  auto place = dense_tensor->place();
118
  float* a_data = dense_tensor->mutable_data<float>(place);
W
Wilber 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132
  if (place.GetType() == ::phi::AllocationType::CPU) {
    for (int64_t i = 0; i < dense_tensor->numel(); ++i) {
      a_data[i] = (value.get())[i];
    }
  } else if (place.GetType() == ::phi::AllocationType::GPU) {
#ifdef INFRT_WITH_GPU
    // TODO(wilber): how to set the stream parameter to copy with stream.
    cudaMemcpy(a_data,
               value.get().data(),
               sizeof(float) * value.get().size(),
               cudaMemcpyHostToDevice);
#endif
  } else {
    llvm_unreachable("temporarily not support other target.");
133 134
  }
}
135

136
void PrintDenseTensor(::phi::DenseTensor* dense_tensor) {
W
Wilber 已提交
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
#ifndef INFRT_WITH_GPU
#define PRINT_META_DATA(PHI_DATATYPE, DTYPE)                \
  case ::phi::DataType::PHI_DATATYPE: {                     \
    auto place = dense_tensor->place();                     \
    if (place.GetType() == ::phi::AllocationType::CPU) {    \
      DTYPE* data = dense_tensor->data<DTYPE>();            \
      if (dense_tensor->numel() == 0) break;                \
      std::cout << data[0];                                 \
      for (int64_t i = 1; i < dense_tensor->numel(); i++) { \
        std::cout << "," << data[i];                        \
      }                                                     \
    }                                                       \
    break;                                                  \
  }
#else
#define PRINT_META_DATA(PHI_DATATYPE, DTYPE)                     \
  case ::phi::DataType::PHI_DATATYPE: {                          \
    auto place = dense_tensor->place();                          \
    DTYPE* data = dense_tensor->data<DTYPE>();                   \
    if (dense_tensor->numel() == 0) break;                       \
    if (place.GetType() == ::phi::AllocationType::CPU) {         \
      std::cout << data[0];                                      \
      for (int64_t i = 1; i < dense_tensor->numel(); i++) {      \
        std::cout << "," << data[i];                             \
      }                                                          \
    } else if (place.GetType() == ::phi::AllocationType::GPU) {  \
      std::vector<DTYPE> host_data(dense_tensor->numel(), 0);    \
      cudaMemcpy(host_data.data(),                               \
                 data,                                           \
                 sizeof(DTYPE) * dense_tensor->numel(),          \
                 cudaMemcpyDeviceToHost);                        \
      std::cout << host_data[0];                                 \
      for (int64_t i = 1; i < dense_tensor->numel(); i++) {      \
        std::cout << "," << host_data[i];                        \
      }                                                          \
    } else {                                                     \
      llvm_unreachable("temporarily not support other target."); \
    }                                                            \
    break;                                                       \
176
  }
W
Wilber 已提交
177
#endif
178 179 180

  ::phi::DDim dims = dense_tensor->dims();
  std::cout << "dense_tensor: shape=shape" << dims.to_str() << ","
181
            << " value=[";
182 183 184 185 186 187 188 189 190
  switch (dense_tensor->dtype()) {
    PRINT_META_DATA(FLOAT32, float);
    PRINT_META_DATA(INT32, int32_t);
    default:
      std::cout << "Error! Unsupported data type!\n";
  }
  std::cout << "]\n";
#undef PRINT_META_DATA
}
191

192
::infrt::phi::DenseTensorMap LoadParameters(const std::string& file_path) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  std::cout << "loading params from: " << file_path << std::endl;
  ::infrt::phi::DenseTensorMap map;

  const std::string model_path = file_path + "/__model__";
  auto pb_proto_prog = paddle::LoadProgram(model_path);
  auto main_block = pb_proto_prog->blocks(0);

  for (auto& var : main_block.vars()) {
    if (var.name() == "feed" || var.name() == "fetch" || !var.persistable())
      continue;
    std::string param_path = file_path + "/" + var.name();
    std::ifstream param_file(param_path, std::ios::binary);
    switch (var.type().type()) {
      case ::paddle::framework::proto::VarType_Type_LOD_TENSOR: {
        std::unique_ptr<::phi::DenseTensor> tensor{
            std::make_unique<::phi::DenseTensor>()};
        ::phi::CPUContext ctx;
        ::paddle::framework::DeserializeFromStream(
            param_file, tensor.get(), ctx);
        map.SetDenseTensor(var.name(), std::move(tensor));
      } break;
      default: {
        LOG(WARNING) << "Var `" << var.name() << "` type `"
                     << static_cast<int>(var.type().type())
                     << "` has not been supported now.";
      }
    }
  }
  return map;
}

224 225 226 227 228 229 230
::infrt::phi::DenseTensorMap LoadParams(
    host_context::Attribute<std::string> path) {
  return LoadParameters(path.get());
}

::infrt::phi::DenseTensorMap LoadCombinedParameters(
    const std::string& model_path, const std::string& params_path) {
231 232
  ::infrt::phi::DenseTensorMap map;

233
  auto pb_proto_prog = paddle::LoadProgram(model_path);
234 235
  auto main_block = pb_proto_prog->blocks(0);

236
  std::ifstream param_file(params_path, std::ios::binary);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

  std::set<std::string> tmp;
  for (auto& var : main_block.vars()) {
    if (var.name() == "feed" || var.name() == "fetch" || !var.persistable()) {
      continue;
    }
    if (var.type().type() ==
        ::paddle::framework::proto::VarType_Type_LOD_TENSOR) {
      tmp.emplace(var.name());
    } else {
      llvm_unreachable("the tensor type is illegal.");
    }
  }

  for (auto& var : tmp) {
    std::unique_ptr<::phi::DenseTensor> tensor{
        std::make_unique<::phi::DenseTensor>()};
    ::phi::CPUContext ctx;
    ::paddle::framework::DeserializeFromStream(param_file, tensor.get(), ctx);
    map.SetDenseTensor(var, std::move(tensor));
  }

  return map;
}

262 263 264 265 266 267
::infrt::phi::DenseTensorMap LoadCombinedParams(
    host_context::Attribute<std::string> model_path,
    host_context::Attribute<std::string> params_path) {
  return LoadCombinedParameters(model_path.get(), params_path.get());
}

268 269 270 271 272 273 274 275 276 277 278 279
::phi::DenseTensor TensorMapGetTensor(
    const ::infrt::phi::DenseTensorMap& map,
    host_context::Attribute<std::string> name) {
  auto* tensor = map.GetDenseTensor(name.get());
  CHECK(tensor);
  return *tensor;
}

int32_t TensorMapGetSize(const ::infrt::phi::DenseTensorMap& map) {
  return map.size();
}

W
Wilber 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 340 341 342
#ifdef INFRT_WITH_GPU
inline size_t SizeOfDataType(::phi::DataType data_type) {
  switch (data_type) {
    case ::phi::DataType::BOOL:
    case ::phi::DataType::UINT8:
    case ::phi::DataType::INT8:
      return 1;
    case ::phi::DataType::BFLOAT16:
    case ::phi::DataType::FLOAT16:
    case ::phi::DataType::INT16:
    case ::phi::DataType::UINT16:
      return 2;
    case ::phi::DataType::FLOAT32:
    case ::phi::DataType::INT32:
    case ::phi::DataType::UINT32:
      return 4;
    case ::phi::DataType::FLOAT64:
    case ::phi::DataType::INT64:
    case ::phi::DataType::UINT64:
    case ::phi::DataType::COMPLEX64:
      return 8;
    case ::phi::DataType::COMPLEX128:
      return 16;
    case ::phi::DataType::UNDEFINED:
      return 0;
    default:
      llvm_unreachable("should not reach here");
      return 0;
  }
  return 0;
}
::phi::DenseTensor GpuMemCpy(const ::phi::DenseTensor& input,
                             const ::phi::GPUContext& context,
                             bool d2h) {
  if (d2h) {
    ::phi::DenseTensor ret(
        const_cast<::phi::Allocator*>(&context.GetHostAllocator()),
        input.meta());
    CHECK(input.place().GetType() == ::phi::AllocationType::GPU);
    // TODO(wilber): Add sync op and stream.
    cudaMemcpyAsync(ret.data(),
                    input.data(),
                    SizeOfDataType(input.dtype()) * input.numel(),
                    cudaMemcpyDeviceToHost,
                    nullptr);
    return ret;
  } else {
    // h2d
    ::phi::DenseTensor ret(
        const_cast<::phi::Allocator*>(&context.GetAllocator()), input.meta());
    CHECK(input.place().GetType() == ::phi::AllocationType::CPU ||
          input.place().GetType() == ::phi::AllocationType::GPUPINNED);
    // TODO(wilber): Add sync op and stream.
    cudaMemcpyAsync(ret.data(),
                    input.data(),
                    SizeOfDataType(input.dtype()) * input.numel(),
                    cudaMemcpyHostToDevice,
                    nullptr);
    return ret;
  }
}
#endif

343
}  // namespace phi
344 345
}  // namespace kernel
}  // namespace infrt