tensor.h 1.3 KB
Newer Older
D
dzhwinter 已提交
1
#pragma once
2 3 4 5 6
/**
 * @brief tensor used by optimizer
 */

#include <string.h>
D
dzhwinter 已提交
7
#include <memory>
D
dzhwinter 已提交
8 9
#include "paddle/utils/Common.h"
#include "paddle/utils/Logging.h"
10 11 12 13 14

namespace paddle {
namespace optimizer {

template <class T>
D
dzhwinter 已提交
15
class TensorT {
16
public:
D
dzhwinter 已提交
17 18 19
  TensorT(size_t size) : height_(1), width_(size) {
    data_ptr_ = std::shared_ptr<T>(new T[size], std::default_delete<T[]>());
    data_ = data_ptr_.get();
20
  }
D
dzhwinter 已提交
21

D
dzhwinter 已提交
22 23
  TensorT(T* data, size_t size)
      : height_(1), width_(size), data_ptr_(nullptr), data_(data) {}
D
dzhwinter 已提交
24

D
dzhwinter 已提交
25 26
  TensorT(T* data, size_t h, size_t w)
      : height_(h), width_(w), data_ptr_(nullptr), data_(data) {}
D
dzhwinter 已提交
27

28
  virtual ~TensorT() {}
D
dzhwinter 已提交
29

30
  T* get_buffer() { return this->data_; }
D
dzhwinter 已提交
31

32
  T& operator[](const size_t idx) {
D
dzhwinter 已提交
33
    CHECK(idx >= 0 && idx < this->width_) << "out of index range";
D
dzhwinter 已提交
34 35
    return data_[idx];
  }
36
  T& operator[](const size_t idx) const {
D
dzhwinter 已提交
37 38
    CHECK(idx >= 0 && idx < this->width_) << "out of index range";
    return data_[idx];
39
  }
40
  // TODO: replace with tensorshape
D
dzhwinter 已提交
41
  size_t size() const { return this->width_ * this->height_; }
D
dzhwinter 已提交
42 43 44 45

protected:
  size_t height_;
  size_t width_;
D
dzhwinter 已提交
46
  std::shared_ptr<T> data_ptr_;
D
dzhwinter 已提交
47
  T* data_;
48 49
};

D
dzhwinter 已提交
50
// TODO(zhihong): design problem of dynamic datatype, need to fix it
51
typedef TensorT<float> Tensor;
D
dzhwinter 已提交
52

53 54
}  // namespace optimizer
}  // namespace paddle