lite_tensor.h 9.1 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (c) 2019 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.

#pragma once

#include <algorithm>
#include <functional>  // for multiplies
#include <memory>
#include <numeric>
#include <string>
#include <vector>

24
#include "lite/backends/fpga/KD/tensor.hpp"
Y
Yan Chunwei 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include "lite/core/memory.h"

namespace paddle {
namespace lite {

class DDimLite;
class TensorLite;

using DDim = lite::DDimLite;
using Tensor = lite::TensorLite;

class DDimLite {
 public:
  using value_type = int64_t;

  DDimLite() = default;

  explicit DDimLite(const std::vector<value_type> &x) { ConstructFrom(x); }

  void ConstructFrom(const std::vector<value_type> &x) { data_ = x; }

  value_type operator[](int offset) const { return data_[offset]; }
  value_type &operator[](int offset) { return data_[offset]; }
  std::vector<int64_t> Vectorize() const { return data_; }

  size_t size() const { return data_.size(); }
  bool empty() const { return data_.empty(); }

  value_type production() const;

  const std::vector<value_type> &data() const { return data_; }
  value_type count(int start, int end) const;

  DDimLite Slice(int start, int end) const;

60
  DDimLite Flatten2D(int col) const {
Y
Yan Chunwei 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    return DDimLite(std::vector<value_type>(
        {Slice(0, col).production(), Slice(col, size()).production()}));
  }

  std::string repr() const;

  friend std::ostream &operator<<(std::ostream &os, const DDimLite &dims) {
    os << dims.repr();
    return os;
  }

  friend bool operator==(const DDimLite &a, const DDimLite &b) {
    if (a.size() != b.size()) return false;
    for (size_t i = 0; i < a.size(); i++) {
      if (a[i] != b[i]) return false;
    }
    return true;
  }

  friend bool operator!=(const DDimLite &a, const DDimLite &b) {
    return !(a == b);
  }

C
chonwhite 已提交
84 85 86 87
  ~DDimLite() {
    // std::cout << "free DDimLite\n";
  }

Y
Yan Chunwei 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
 private:
  std::vector<value_type> data_;
};

using LoD = std::vector<std::vector<uint64_t>>;

// A light-weight tensor implementation.
class TensorLite {
 public:
  TensorLite() : buffer_(std::make_shared<Buffer>()) {}

  template <typename DType, typename DimT, TargetType Target>
  void Assign(DType *data, const DimT &dim) {
    Resize(dim);
    auto *dst = mutable_data<DType, void>(Target);
    CopySync<Target>(
        dst, data, dim.production() * sizeof(DType), IoDirection::HtoD);
  }

  // T is the data type and R is the return type
  // For OpenCL, the return type can be cl::Buffer
  // and the data type can be float/int8_t.
  // For other devices, T and R may be the same type.
  template <typename T, typename R = T>
  const R *data() const {
T
TianXiaogang 已提交
113
    return zynq_tensor_->data<R>() + offset_;
Y
Yan Chunwei 已提交
114 115
  }

C
chonwhite 已提交
116 117 118 119 120 121
  void Resize(const DDimLite &ddim) {
    // std::cout << "Resize \n";
    // std::cout << "ddim:" << & ddim << std::endl;
    dims_ = ddim;
    // std::cout << "after Reize \n";
  }
Y
Yan Chunwei 已提交
122 123 124 125 126 127 128 129
  void Resize(const std::vector<int64_t> &x) { dims_ = DDimLite(x); }

  const DDimLite &dims() const { return dims_; }
  int64_t numel() const { return dims_.production(); }

  const LoD &lod() const { return lod_; }
  LoD *mutable_lod() { return &lod_; }

130 131 132 133 134 135 136
  void set_lod(const LoD &lod) { lod_ = lod; }

  PrecisionType precision() const { return precision_; }
  void set_precision(PrecisionType precision) { precision_ = precision; }

  bool persistable() const { return persistable_; }
  void set_persistable(bool persistable) { persistable_ = persistable; }
T
TianXiaogang 已提交
137

Y
Yan Chunwei 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  // T is the data type and R is the return type
  // For OpenCL, the return type can be cl::Buffer
  // and the data type can be float/int8_t.
  // For other devices, T and R may be the same type.
  template <typename T, typename R = T>
  R *mutable_data();

  // T is the data type and R is the return type
  // For OpenCL, the return type can be cl::Buffer
  // and the data type can be float/int8_t.
  // For other devices, T and R may be the same type.
  template <typename T, typename R = T>
  R *mutable_data(TargetType target);
  void *mutable_data(size_t memory_size);
  void *mutable_data(TargetType target, size_t memory_size);

C
chonwhite 已提交
154 155 156
  const void *raw_data() const {
    return buffer_->data();
  }  // TODO(chonwhite) delete buffer;
Y
Yan Chunwei 已提交
157 158 159 160 161

  size_t data_size() const { return this->dims().production(); }

  size_t memory_size() const { return zynq_tensor_->memorySize(); }

T
TianXiaogang 已提交
162 163
  size_t offset() const { return offset_; }

C
chonwhite 已提交
164 165 166
  bool IsInitialized() const {
    return buffer_->data();
  }  // TODO(chonwhite) delete buffer;
Y
Yan Chunwei 已提交
167 168 169 170 171 172

  // Other share data to this.
  void ShareDataWith(const TensorLite &other);

  void CopyDataFrom(const TensorLite &other);

173 174 175
  template <typename T>
  TensorLite Slice(int64_t begin, int64_t end) const;

T
TianXiaogang 已提交
176 177 178
  template <typename T>
  void Slice(TensorLite &dst, int64_t begin, int64_t end) const;  // NOLINT

Y
Yan Chunwei 已提交
179 180
  TargetType target() const { return target_; }

181 182 183
  // template <typename T>
  // TensorLite Slice(int64_t begin, int64_t end) const;

C
chonwhite 已提交
184
  zynqmp::Tensor *ZynqTensor() const { return zynq_tensor_.get(); }
Y
Yan Chunwei 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197

  friend std::ostream &operator<<(std::ostream &os, const TensorLite &tensor) {
    os << "Tensor:" << '\n';
    os << "dim: " << tensor.dims() << '\n';
    for (int i = 0; i < tensor.dims().production(); i++) {
      os << tensor.template data<float>()[i] << " ";
    }
    os << "\n";
    return os;
  }

 private:
  TargetType target_{TargetType::kHost};
T
TianXiaogang 已提交
198 199 200 201 202 203 204 205 206

  // precision_ and persistable_ are only used for persistable vars.
  // If your tensor wants to be saved and loaded correctly, you must
  // set values of precision_ and persistable_ after updating it.
  // If your tensor is just a temp tensor, such as activations,
  // you can ignore these two attributes.
  PrecisionType precision_{PrecisionType::kUnk};
  bool persistable_{false};

Y
Yan Chunwei 已提交
207 208 209 210
  DDimLite dims_;
  std::shared_ptr<Buffer> buffer_;
  LoD lod_;
  size_t memory_size_{};
211 212
  size_t offset_{0};

C
chonwhite 已提交
213 214
  // zynqmp::Tensor *zynq_tensor_ = new zynqmp::Tensor();
  std::shared_ptr<zynqmp::Tensor> zynq_tensor_;
Y
Yan Chunwei 已提交
215 216 217 218 219 220 221 222

  template <typename T>
  void mutable_data_internal();
};

template <typename T, typename R>
R *TensorLite::mutable_data() {
  std::vector<int> v;
C
chonwhite 已提交
223
  // std::cout << "mutable_data \n";
Y
Yan Chunwei 已提交
224 225 226 227 228
  for (int i = 0; i < dims_.size(); i++) {
    v.push_back(dims_[i]);
  }
  zynqmp::LayoutType layout_type = zynqmp::NCHW;
  switch (v.size()) {
T
TianXiaogang 已提交
229 230 231
    case 0:
      layout_type = zynqmp::None;
      break;
Y
Yan Chunwei 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245
    case 1:
      layout_type = zynqmp::N;
      break;
    case 2:
      layout_type = zynqmp::NC;
      break;
    case 3:
      layout_type = zynqmp::NHW;
      break;
    case 4:
      layout_type = zynqmp::NCHW;
      break;
  }
  zynqmp::Shape input_shape(layout_type, v);
C
chonwhite 已提交
246
  // std::cout << "input_shape \n";
Y
Yan Chunwei 已提交
247 248 249 250 251 252 253
  zynqmp::DataType data_type = zynqmp::FP32;
  if (typeid(T) == typeid(float)) {
    data_type = zynqmp::FP32;
  }
  if (typeid(T) == typeid(zynqmp::float16)) {
    data_type = zynqmp::FP16;
  }
C
chonwhite 已提交
254 255 256 257 258 259 260
  // std::cout << "mutableData \n";
  // std::cout << "zynq_tensor_:" << zynq_tensor_.get() << std::endl;

  if (zynq_tensor_.get() == nullptr) {
    zynq_tensor_.reset(new zynqmp::Tensor());
  }

Y
Yan Chunwei 已提交
261 262 263 264 265 266 267 268 269
  return zynq_tensor_->mutableData<R>(data_type, input_shape);
}

template <typename T, typename R>
R *TensorLite::mutable_data(TargetType target) {
  target_ = target;
  return mutable_data<T>();
}

270 271
template <typename T>
TensorLite TensorLite::Slice(int64_t begin, int64_t end) const {
T
TianXiaogang 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  throw - 1;
  CHECK_GE(begin, 0);
  CHECK_LE(end, dims_[0]);
  CHECK_LT(begin, end);
  if (dims_[0] == 1) {
    return *this;
  } else {
    int64_t base = numel() / dims_[0];

    TensorLite dst;
    dst.target_ = target_;
    auto dst_dims = dims_;
    dst_dims[0] = end - begin;
    dst.Resize(dst_dims);
    void *dst_data = dst.mutable_data<T>();

    T *src_data = const_cast<T *>(data<T>());
    memcpy(dst_data,
           src_data + static_cast<size_t>(begin * base) * sizeof(T),
           dst_dims.production() * sizeof(T));
    dst.ZynqTensor()->saveToFile("_slice", true);

    return dst;
  }
}

template <typename T>
void TensorLite::Slice(TensorLite &dst, int64_t begin, int64_t end) const {
C
chonwhite 已提交
300
  // TODO(chonwhite) delete this function;
T
TianXiaogang 已提交
301 302 303
  CHECK_GE(begin, 0);
  CHECK_LE(end, dims_[0]);
  CHECK_LT(begin, end);
304 305 306 307 308

  dst.target_ = target_;
  auto dst_dims = dims_;
  dst_dims[0] = end - begin;
  dst.Resize(dst_dims);
T
TianXiaogang 已提交
309 310 311 312 313 314 315 316
  void *dst_data = dst.mutable_data<T>();

  int64_t base = numel() / dims_[0];

  T *src_data = const_cast<T *>(data<T>());
  memcpy(dst_data,
         src_data + static_cast<size_t>(begin * dst_dims.production()),
         dst_dims.production() * sizeof(T));
317
}
T
TianXiaogang 已提交
318 319 320 321 322 323 324 325

template <typename TensorT>
bool TensorCompareWith(const TensorT &a, const TensorT &b) {
  if (a.dims() != b.dims()) return false;
  if (memcmp(a.raw_data(), b.raw_data(), a.data_size()) != 0) return false;
  return true;
}

Y
Yan Chunwei 已提交
326 327
}  // namespace lite
}  // namespace paddle