tensor_util.h 2.0 KB
Newer Older
W
wangliu 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
朔-望's avatar
朔-望 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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. */

#pragma once
朔-望's avatar
朔-望 已提交
16
#include <vector>
朔-望's avatar
朔-望 已提交
17 18 19 20 21 22
#include "framework.pb.h"
#include "memory/t_malloc.h"
#include "platform/data_type.h"
#include "tensor.h"

namespace paddle_mobile {
朔-望's avatar
朔-望 已提交
23
namespace framework {
朔-望's avatar
朔-望 已提交
24

朔-望's avatar
朔-望 已提交
25 26
void TensorCopy(const Tensor &src, Tensor *dst);
void TensorCopySync(const Tensor &src, Tensor *dst);
朔-望's avatar
朔-望 已提交
27

朔-望's avatar
朔-望 已提交
28 29
template <typename T>
void TensorFromVector(const std::vector<T> &src, Tensor *dst);
朔-望's avatar
朔-望 已提交
30

朔-望's avatar
朔-望 已提交
31 32
template <typename T>
void TesnorToVector(const Tensor &src, std::vector<T> *dst);
朔-望's avatar
朔-望 已提交
33

朔-望's avatar
朔-望 已提交
34 35
bool TensorContainsNAN(const framework::Tensor &tensor);
bool TensorContainsInf(const framework::Tensor &tensor);
朔-望's avatar
朔-望 已提交
36

朔-望's avatar
朔-望 已提交
37 38
void TensorToStream(std::ostream &os, const Tensor &tensor);
void TensorFromStream(std::istream &is, Tensor *tensor);
朔-望's avatar
朔-望 已提交
39

朔-望's avatar
朔-望 已提交
40 41 42
//
// The implementation of template functions.
//
朔-望's avatar
朔-望 已提交
43

朔-望's avatar
朔-望 已提交
44 45
template <typename T>
void TensorFromVector(const std::vector<T> &src, Tensor *dst) {
46 47 48 49
  auto src_ptr = static_cast<const void *>(src.data());
  dst->Resize({static_cast<int64_t>(src.size())});
  auto dst_ptr = static_cast<void *>(dst->mutable_data<T>());
  auto size = src.size() * sizeof(T);
朔-望's avatar
朔-望 已提交
50

51
  memory::Copy(dst_ptr, src_ptr, size);
朔-望's avatar
朔-望 已提交
52
}
朔-望's avatar
朔-望 已提交
53

朔-望's avatar
朔-望 已提交
54 55
template <typename T>
void TensorToVector(const Tensor &src, std::vector<T> *dst) {
56 57
  auto src_ptr = static_cast<const void *>(src.data<T>());
  auto size = src.numel() * sizeof(T);
朔-望's avatar
朔-望 已提交
58

59 60
  dst->resize(src.numel());
  auto dst_ptr = static_cast<void *>(dst->data());
朔-望's avatar
朔-望 已提交
61

62
  memory::Copy(dst_ptr, src_ptr, size);
朔-望's avatar
朔-望 已提交
63
}
朔-望's avatar
朔-望 已提交
64

朔-望's avatar
朔-望 已提交
65 66
}  // namespace framework
}  // namespace paddle_mobile