tensor_util.cpp 6.3 KB
Newer Older
W
wangliu 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
朔-望's avatar
朔-望 已提交
2

W
wangliu 已提交
3 4 5
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
朔-望's avatar
朔-望 已提交
6

W
wangliu 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
朔-望's avatar
朔-望 已提交
8

W
wangliu 已提交
9 10 11 12 13
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. */
朔-望's avatar
朔-望 已提交
14 15 16 17 18 19 20

#include "tensor_util.h"
#include <algorithm>
#include <limits>
#include <vector>

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

void TensorCopy(const Tensor &src, Tensor *dst) {
24 25 26 27 28
  //  VLOG(3) << "TensorCopy " << src.dims() << " from " <<
  //  src.place() << " to
  //  "
  //          << dst_place;
  src.check_memory_size();
朔-望's avatar
朔-望 已提交
29

30 31 32
  dst->Resize(src.dims());
  dst->set_layout(src.layout());
  auto src_ptr = src.data<void>();
朔-望's avatar
朔-望 已提交
33

34
  auto dst_ptr = dst->mutable_data(src.type());
朔-望's avatar
朔-望 已提交
35

36
  auto size = src.numel() * SizeOfType(src.type());
朔-望's avatar
朔-望 已提交
37

38
  memory::Copy(dst_ptr, src_ptr, size);
朔-望's avatar
朔-望 已提交
39 40 41
}

void TensorCopySync(const Tensor &src, Tensor *dst) {
42 43 44 45 46 47 48 49 50 51
  //  VLOG(3) << "TensorCopySync " << src.dims() << " from " <<
  //  src.place()
  //          << " to " << dst_place;
  src.check_memory_size();
  dst->Resize(src.dims());
  dst->set_layout(src.layout());
  auto src_ptr = src.data<void>();
  auto dst_ptr = dst->mutable_data(src.type());
  auto size = src.numel() * SizeOfType(src.type());
  memory::Copy(dst_ptr, src_ptr, size);
朔-望's avatar
朔-望 已提交
52 53
}

朔-望's avatar
朔-望 已提交
54 55
template <typename Predicate>
struct AnyDTypeVisitor {
56 57 58 59 60 61 62
  Predicate predicate_;
  const Tensor &tensor_;
  Tensor *out_;

  AnyDTypeVisitor(Predicate predicate, const Tensor &tensor, Tensor *out)
      : predicate_(predicate), tensor_(tensor), out_(out) {}

朔-望's avatar
朔-望 已提交
63 64
  template <typename T>
  void operator()() const {
65 66 67 68 69
    //    auto t = EigenVector<T>::Flatten(tensor_);
    //    auto o = EigenScalar<bool>::From(*out_);
    // return any of predicate_(t) is true.
    //    o.device(*ctx_.eigen_device()) = predicate_(t).any();
  }
朔-望's avatar
朔-望 已提交
70 71 72 73 74
};

template <typename Predicate>
inline void AnyImpl(Predicate predicate, const Tensor &tensor,
                    framework::Tensor *out) {
75 76
  VisitDataType(ToDataType(tensor.type()),
                AnyDTypeVisitor<Predicate>(predicate, tensor, out));
朔-望's avatar
朔-望 已提交
77 78
}

朔-望's avatar
朔-望 已提交
79 80
template <typename Predicate>
struct AnyVisitor {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  const framework::Tensor &tensor_;
  Predicate predicate_;

  AnyVisitor(const framework::Tensor &tensor, Predicate predicate)
      : tensor_(tensor), predicate_(std::move(predicate)) {}

  bool operator()(void) const {
    framework::Tensor out;
    out.Resize({1});
    out.mutable_data<bool>();
    AnyImpl(predicate_, tensor_, &out);
    return this->GetResult(out);
  }

  bool GetResult(const framework::Tensor &out) const {
    return *out.data<bool>();
  }
朔-望's avatar
朔-望 已提交
98 99 100 101
};

template <typename Predicate>
inline bool Any(const framework::Tensor &tensor, Predicate predicate) {
102 103 104
  AnyVisitor<Predicate> visitor(tensor, predicate);
  //  return platform::VisitPlace(visitor);
  return visitor();
朔-望's avatar
朔-望 已提交
105 106 107
}

struct ContainsNANPredicate {
108 109 110 111 112 113
  template <typename T>
  auto operator()(const T &eigen_vec) const
      -> decltype(std::declval<T>().isnan()) {
    // Cast eigen_vector to vector of bool. true if is inf.
    return eigen_vec.isnan();
  }
朔-望's avatar
朔-望 已提交
114 115 116
};

bool TensorContainsNAN(const framework::Tensor &tensor) {
117 118
  ContainsNANPredicate predicate;
  return Any(tensor, predicate);
朔-望's avatar
朔-望 已提交
119 120 121
}

struct ContainsInfPredicate {
122 123 124 125 126 127
  template <typename T>
  auto operator()(const T &eigen_vec) const
      -> decltype(std::declval<T>().isinf()) {
    // Cast eigen_vector to vector of bool. true if is inf.
    return eigen_vec.isinf();
  }
朔-望's avatar
朔-望 已提交
128 129 130
};

bool TensorContainsInf(const framework::Tensor &tensor) {
131 132
  ContainsInfPredicate predicate;
  return Any(tensor, predicate);
朔-望's avatar
朔-望 已提交
133 134 135
}

void TensorToStream(std::ostream &os, const Tensor &tensor) {
朔-望's avatar
朔-望 已提交
136
  {  // the 1st field, uint32_t version
137 138 139
    constexpr uint32_t version = 0;
    os.write(reinterpret_cast<const char *>(&version), sizeof(version));
  }
朔-望's avatar
朔-望 已提交
140
  {  // the 2nd field, tensor description
141 142 143 144 145 146 147 148 149 150 151 152 153
    // int32_t  size
    // void*    protobuf message
    proto::VarType::TensorDesc desc;
    desc.set_data_type(framework::ToDataType(tensor.type()));
    auto dims = framework::vectorize(tensor.dims());
    auto *pb_dims = desc.mutable_dims();
    pb_dims->Resize(static_cast<int>(dims.size()), 0);
    std::copy(dims.begin(), dims.end(), pb_dims->begin());
    int32_t size = desc.ByteSize();
    os.write(reinterpret_cast<const char *>(&size), sizeof(size));
    auto out = desc.SerializeAsString();
    os.write(out.data(), size);
  }
朔-望's avatar
朔-望 已提交
154
  {  // the 3rd field, tensor data
155 156 157 158 159 160 161 162 163
    uint64_t size = tensor.memory_size();
    auto *data_ptr = tensor.data<void>();
    //    PADDLE_ENFORCE(size <
    //    std::numeric_limits<std::streamsize>::max(),
    //                   "Index overflow when writing tensor");

    os.write(static_cast<const char *>(data_ptr),
             static_cast<std::streamsize>(size));
  }
朔-望's avatar
朔-望 已提交
164 165 166
}

struct DeserializedDataFunctor {
167 168
  DeserializedDataFunctor(void **buf, Tensor *tensor)
      : buf_(buf), tensor_(tensor) {}
朔-望's avatar
朔-望 已提交
169

朔-望's avatar
朔-望 已提交
170 171
  template <typename T>
  void operator()() {
172 173
    *buf_ = tensor_->mutable_data<T>();
  }
朔-望's avatar
朔-望 已提交
174

175 176
  void **buf_;
  Tensor *tensor_;
朔-望's avatar
朔-望 已提交
177 178 179
};

void TensorFromStream(std::istream &is, framework::Tensor *tensor) {
180 181 182 183
  uint32_t version;
  is.read(reinterpret_cast<char *>(&version), sizeof(version));
  //  PADDLE_ENFORCE_EQ(version, 0U, "Only version 0 is supported");
  proto::VarType::TensorDesc desc;
朔-望's avatar
朔-望 已提交
184
  {  // int32_t size
185 186 187 188 189 190 191 192
    // proto buffer
    int32_t size;
    is.read(reinterpret_cast<char *>(&size), sizeof(size));
    std::unique_ptr<char[]> buf(new char[size]);
    is.read(reinterpret_cast<char *>(buf.get()), size);
    //    PADDLE_ENFORCE(desc.ParseFromArray(buf.get(), size),
    //                   "Cannot parse tensor desc");
  }
朔-望's avatar
朔-望 已提交
193
  {  // read tensor
194 195 196 197 198 199 200 201 202 203
    std::vector<int64_t> dims;
    dims.reserve(static_cast<size_t>(desc.dims().size()));
    std::copy(desc.dims().begin(), desc.dims().end(), std::back_inserter(dims));
    tensor->Resize(framework::make_ddim(dims));
    void *buf;

    framework::VisitDataType(desc.data_type(),
                             DeserializedDataFunctor(&buf, tensor));
    is.read(static_cast<char *>(buf), tensor->memory_size());
  }
朔-望's avatar
朔-望 已提交
204 205
}

朔-望's avatar
朔-望 已提交
206 207
}  // namespace framework
}  // namespace paddle_mobile