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_ = new T[size]; }
  TensorT(T* data, size_t size) : height_(1), width_(size), data_(data) {}
  TensorT(T* data, size_t h, size_t w) : height_(h), width_(w), data_(data_) {}
D
dzhwinter 已提交
20
  TensorT(const TensorT& t)
D
dzhwinter 已提交
21
      : TensorT(1, t.size(), 0, t.get_buffer(), false, false) {}
D
dzhwinter 已提交
22 23 24 25
  ~TensorT() {
    if (data_) delete data_;
  }

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

protected:
  size_t height_;
  size_t width_;
  T* data_;
46 47
};

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

51 52
}  // namespace optimizer
}  // namespace paddle