lod_tensor.h 5.4 KB
Newer Older
1 2
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

L
Luo Tao 已提交
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
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. */
14 15 16 17

#pragma once

#include <memory>
18
#ifdef PADDLE_WITH_CUDA
19 20
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
21
#include <thrust/system/cuda/experimental/pinned_allocator.h>
22 23
#endif

24
#include <glog/logging.h>
25 26
#include "paddle/framework/ddim.h"
#include "paddle/framework/tensor.h"
D
dzhwinter 已提交
27
#include "paddle/framework/tensor_util.h"
28
#include "paddle/platform/enforce.h"
29
#include "paddle/platform/place.h"
30 31 32 33

namespace paddle {
namespace framework {

34
#ifndef PADDLE_WITH_CUDA
Q
qijun 已提交
35 36 37 38
template <typename T>
using Vector = std::vector<T>;
#else
template <typename T>
39 40
using Vector = thrust::host_vector<
    T, thrust::system::cuda::experimental::pinned_allocator<T>>;
Q
qijun 已提交
41 42
#endif

43
/*
44
 * LoD is short for Level of Details.
45
 *
46
 * - in a level, each element indicates relative offset of the lower level
47 48 49
 * - the first element should be 0 and that indicates that this sequence start
 * from 0
 * - each sequence's begin and end(no-inclusive) is level[id, id+1]
50 51 52 53 54 55 56
 *
 * For example:
 *    3-level LoD stores
 *
 *    0 2 3
 *    0 2 4 7
 *    0 2 5 7 10 12 15 20
57
 */
58
using LoD = std::vector<Vector<size_t>>;
Q
qijun 已提交
59

60
std::ostream& operator<<(std::ostream& os, const LoD& lod);
Y
Yang Yang 已提交
61
std::ostream& operator<<(std::ostream& os, const LoDTensor& t);
62

Q
Qiao Longfei 已提交
63 64
std::string LoDToString(const LoD& lod);

65
LoD SliceInLevel(const LoD& in, size_t level, size_t elem_begin,
Q
qijun 已提交
66
                 size_t elem_end);
67 68 69 70
/*
 * Transform an LoD from relative offsets to absolute offsets.
 */
LoD ToAbsOffset(const LoD& in);
Q
qijun 已提交
71

72
bool operator==(const LoD& a, const LoD& b);
Q
qijun 已提交
73

74
/*
75
 * LoDTensor (Level of details Tensor)
76 77
 * see https://en.wikipedia.org/wiki/Level_of_details for reference.
 */
78
class LoDTensor : public Tensor {
79
 public:
80
  LoDTensor() {}
81

82
  explicit LoDTensor(const LoD& lod) : lod_(lod) {}
Q
qijun 已提交
83

84
  void set_lod(const LoD& lod) { lod_ = lod; }
Q
qijun 已提交
85

Y
Yu Yang 已提交
86 87 88
  const LoD& lod() const { return lod_; }

  LoD* mutable_lod() { return &lod_; }
Q
qijun 已提交
89

90
  /*
W
wanghaoshuang 已提交
91
   * Get the start offset and end offset of an  element from LoD.
92
   */
W
wanghaoshuang 已提交
93
  std::pair<size_t, size_t> lod_element(size_t level, size_t elem) const {
94
    PADDLE_ENFORCE_LT(level, NumLevels());
W
wanghaoshuang 已提交
95 96
    PADDLE_ENFORCE_LT(elem, NumElements(level));
    return std::make_pair((lod_)[level][elem], (lod_)[level][elem + 1]);
97 98 99
  }

  /*
100
   * Number of LoDTensor's levels, each level has units of data, for example,
101 102
   * in the sentence's view, article, paragraph, sentence are 3 levels.
   */
103
  size_t NumLevels() const { return lod_.size(); }
104 105 106 107
  /*
   * Number of elements in a level.
   */
  size_t NumElements(size_t level = 0) const {
108
    PADDLE_ENFORCE_LT(level, NumLevels());
109
    // the last offset is the end of last element
Q
qijun 已提交
110
    return (lod_)[level].size() - 1;
111 112
  }

Y
Yang Yang 已提交
113 114 115
  std::vector<LoDTensor> SplitLoDTensor(
      const std::vector<platform::Place> places) const;

Y
Yang Yang 已提交
116 117 118
  void MergeLoDTensor(const std::vector<const LoDTensor*>& lod_tensors,
                      platform::Place place);

Q
qijun 已提交
119
 private:
120
  LoD lod_;
121
};
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

/*
 * Expand the `source` to fit the LoD of `lod`. For example, a `source`
 * LoDTensor is
 *  - LoD: [0, 2]
 *  - tensor: [a0, a1]
 * a `lod` is
 *  - LoD: [0 3 5]
 * returns a new LoDTensor
 *  - [a0 a0 a0 a1 a1]
 */
template <typename T>
LoDTensor LodExpand(const LoDTensor& source, const LoD& lod, size_t level,
                    const platform::Place& place) {
  LoD abs_lod = ToAbsOffset(lod);
  const auto& lod_level = lod[level];
  size_t num_instances = source.dims()[0];

  // new tensor
  LoDTensor tensor;
  tensor.set_lod(lod);
  auto dims = source.dims();
  dims[0] = lod_level.back();
  tensor.Resize(dims);
  tensor.mutable_data<T>(place);

  PADDLE_ENFORCE_EQ(num_instances, lod_level.size() - 1);
  for (size_t ins = 0; ins < num_instances; ins++) {
    for (size_t elem = lod_level[ins]; elem < lod_level[ins + 1]; elem++) {
D
dzhwinter 已提交
151
      auto slice = tensor.Slice(elem, elem + 1);
152 153
      Copy(source.Slice(ins, ins + 1), platform::CPUPlace(),
           platform::CPUDeviceContext(), &slice);
154 155 156 157 158
    }
  }
  return tensor;
}

159 160 161 162 163 164 165 166 167 168 169 170
// Get the absolute offset of a lod[start_level][start_idx:end_idx] and
// relative length of details for every levels(i.e., [start_level: ]).
//
// For example,
//   lod = [[0, 3, 4, 8], [0, 9, 10, 11, 13, 17, 19, 22, 24]]
//   start_level = 0
//   start_idx = 1
//   end_idx = 3
//
// Returns:
//  LoD = [[1, 4], [2, 4, 2, 3, 2]]
//  pair<size_t, size_t> = {11, 24}
171 172
std::pair<LoD, std::pair<size_t, size_t>> GetSubLoDAndAbsoluteOffset(
    const LoD& lod, size_t start_idx, size_t end_idx, size_t start_level);
173

174
void AppendLoD(LoD* lod, const LoD& lod_length);
175

武毅 已提交
176 177 178 179 180 181 182
/*
 * Serialize/Desiralize LoDTensor to std::ostream
 * You can pass ofstream or ostringstream to serilize to file
 * or to a in memory string. GPU tensor will be copied to CPU.
 */
void SerializeToStream(std::ostream& os, const LoDTensor& tensor,
                       const platform::DeviceContext& dev_ctx);
Y
Yancey 已提交
183 184
void DeserializeFromStream(std::istream& is, LoDTensor* tensor,
                           const platform::DeviceContext& dev_ctx);
武毅 已提交
185

186 187
}  // namespace framework
}  // namespace paddle