tensor.h 1.9 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
//  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
//
// 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.
D
dzhwinter 已提交
14
#pragma once
15 16 17 18 19
/**
 * @brief tensor used by optimizer
 */

#include <string.h>
D
dzhwinter 已提交
20
#include <memory>
D
dzhwinter 已提交
21 22
#include "paddle/utils/Common.h"
#include "paddle/utils/Logging.h"
23 24 25 26 27

namespace paddle {
namespace optimizer {

template <class T>
D
dzhwinter 已提交
28
class TensorT {
29
public:
D
dzhwinter 已提交
30
  TensorT(size_t size) : height_(1), width_(size) {
31 32
    // new T[size]() initializes all element to zero value.
    data_ptr_ = std::shared_ptr<T>(new T[size](), std::default_delete<T[]>());
D
dzhwinter 已提交
33
    data_ = data_ptr_.get();
34
  }
D
dzhwinter 已提交
35

D
dzhwinter 已提交
36 37
  TensorT(T* data, size_t size)
      : height_(1), width_(size), data_ptr_(nullptr), data_(data) {}
D
dzhwinter 已提交
38

D
dzhwinter 已提交
39 40
  TensorT(T* data, size_t h, size_t w)
      : height_(h), width_(w), data_ptr_(nullptr), data_(data) {}
D
dzhwinter 已提交
41

42
  virtual ~TensorT() {}
D
dzhwinter 已提交
43

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

46
  T& operator[](const size_t idx) {
D
dzhwinter 已提交
47
    CHECK(idx >= 0 && idx < this->width_) << "out of index range";
D
dzhwinter 已提交
48 49
    return data_[idx];
  }
50
  T& operator[](const size_t idx) const {
D
dzhwinter 已提交
51 52
    CHECK(idx >= 0 && idx < this->width_) << "out of index range";
    return data_[idx];
53
  }
54
  // TODO: replace with tensorshape
D
dzhwinter 已提交
55
  size_t size() const { return this->width_ * this->height_; }
D
dzhwinter 已提交
56 57 58 59

protected:
  size_t height_;
  size_t width_;
D
dzhwinter 已提交
60
  std::shared_ptr<T> data_ptr_;
D
dzhwinter 已提交
61
  T* data_;
62 63
};

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

67 68
}  // namespace optimizer
}  // namespace paddle