dense_tensor_kernels.cc 2.6 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"
16
#include <iostream>
17 18
namespace infrt {
namespace kernel {
19
namespace phi {
20

21
::phi::DenseTensor CreateDenseTensorCpuF32Nchw(
22
    backends::CpuPhiAllocator* allocator,
23 24
    host_context::Attribute<std::vector<int64_t>> dims,
    host_context::Attribute<std::vector<int64_t>> lod) {
25 26 27 28 29
  return ::phi::DenseTensor(allocator,
                            ::phi::DenseTensorMeta(::phi::DataType::FLOAT32,
                                                   ::phi::make_ddim(dims.get()),
                                                   ::phi::DataLayout::NCHW,
                                                   {}));
30 31
}

32
void FillDenseTensorF32(::phi::DenseTensor* dense_tensor,
33 34 35 36 37 38 39
                        host_context::Attribute<std::vector<float>> values) {
  auto place = ::phi::CPUPlace();
  float* a_data = dense_tensor->mutable_data<float>(place);
  for (int64_t i = 0; i < dense_tensor->numel(); ++i) {
    a_data[i] = (values.get())[i];
  }
}
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
void PrintDenseTensor(::phi::DenseTensor* dense_tensor) {
#define PRINT_META_DATA(PHI_DATATYPE, DTYPE)              \
  case ::phi::DataType::PHI_DATATYPE: {                   \
    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;                                                \
  }

  ::phi::DDim dims = dense_tensor->dims();
  std::cout << "dense_tensor: shape=shape" << dims.to_str() << ","
            << " values=[";
  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
}
65
}  // namespace phi
66 67
}  // namespace kernel
}  // namespace infrt