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

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>
F
fengjiayi 已提交
18 19 20
#include <string>
#include <utility>
#include <vector>
21
#ifdef PADDLE_WITH_CUDA
22 23 24 25
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#endif

26
#include <glog/logging.h>
W
wanghuancoder 已提交
27

Y
Yi Wang 已提交
28 29 30 31 32 33
#include "paddle/fluid/framework/ddim.h"
#include "paddle/fluid/framework/mixed_vector.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/place.h"
34

W
wanghuancoder 已提交
35 36 37 38 39 40 41 42 43
namespace paddle {
namespace framework {
class LoDTensor;
}  // namespace framework
namespace platform {
class DeviceContext;
}  // namespace platform
}  // namespace paddle

44 45 46
namespace paddle {
namespace framework {

47
/*
48
 * LoD is short for Level of Details.
49
 *
50
 * - in a level, each element indicates relative offset of the lower level
51 52 53
 * - 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]
54 55 56 57 58 59 60
 *
 * For example:
 *    3-level LoD stores
 *
 *    0 2 3
 *    0 2 4 7
 *    0 2 5 7 10 12 15 20
61
 */
Y
Yu Yang 已提交
62
using LoD = std::vector<Vector<size_t>>;
Q
qijun 已提交
63

64
std::ostream& operator<<(std::ostream& os, const LoD& lod);
Y
Yang Yang 已提交
65
std::ostream& operator<<(std::ostream& os, const LoDTensor& t);
66

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

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

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

Y
Yan Chunwei 已提交
78 79 80 81 82 83 84 85
/*
 * Check whether this lod's format is valid.
 *
 * ATTENTION:
 *   - Empty lod is treated as valid.
 *
 * It will check two things:
 *
86
 *  1. all the offsets in a level should be non-descending.
Y
Yan Chunwei 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
 *  2. there should be more than 2 offsets existing in each level.
 *  3. the higher level's last offset should equals the lower level's size-1.
 *  4. the first offset(the begin offset) of each level should be 0.
 *  5. the lowest level's last offset should equals `tensor_height` if
 * tensor_height>0.
 */

bool CheckLoD(const LoD& in, int tensor_height = -1);
/*
 * Check whether this absolute lod's format is valid.
 *
 * ATTENTION:
 *   - Empty lod is treated as valid.
 *
 * It will check two things:
102
 *  1. all the offsets in a level should be ascending(no same items allowed).
Y
Yan Chunwei 已提交
103 104 105 106 107 108 109
 *  2. there should be more than 2 offsets existing in each level.
 *  3. the first offset of each level should be 0, and the last should be the
 *     same(the height of underlying tensor) or `tensor_height` if
 *     tensor_height>0.
 */
bool CheckAbsLoD(const LoD& in, int tensor_height = -1);

110
/*
111
 * LoDTensor (Level of details Tensor)
112 113
 * see https://en.wikipedia.org/wiki/Level_of_details for reference.
 */
114
class LoDTensor : public Tensor {
115
 public:
D
dzhwinter 已提交
116 117
  LoDTensor() : Tensor() {}

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

D
dzhwinter 已提交
120
  void set_lod(const LoD& lod) { lod_ = lod; }
Q
qijun 已提交
121

Y
Yu Yang 已提交
122 123 124
  const LoD& lod() const { return lod_; }

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

126
  /*
W
wanghaoshuang 已提交
127
   * Get the start offset and end offset of an  element from LoD.
128
   */
W
wanghaoshuang 已提交
129
  std::pair<size_t, size_t> lod_element(size_t level, size_t elem) const {
130 131 132 133 134 135 136 137 138 139 140 141 142
    PADDLE_ENFORCE_LT(
        level, NumLevels(),
        platform::errors::InvalidArgument(
            "The input level of LoD is invalid, it should be less than LoD "
            "size. The input level is %zu, the LoD size is %zu.",
            level, NumLevels()));
    PADDLE_ENFORCE_LT(elem, NumElements(level),
                      platform::errors::InvalidArgument(
                          "The input element of LoD is invalid, it should be "
                          "less than the number of elements in its level."
                          "The input element is %zu, the number of elements in "
                          "its level is %zu.",
                          elem, NumElements(level)));
W
wanghaoshuang 已提交
143
    return std::make_pair((lod_)[level][elem], (lod_)[level][elem + 1]);
144 145 146
  }

  /*
147
   * Number of LoDTensor's levels, each level has units of data, for example,
148 149
   * in the sentence's view, article, paragraph, sentence are 3 levels.
   */
150
  size_t NumLevels() const { return lod_.size(); }
151 152 153 154
  /*
   * Number of elements in a level.
   */
  size_t NumElements(size_t level = 0) const {
155 156 157 158 159 160
    PADDLE_ENFORCE_LT(
        level, NumLevels(),
        platform::errors::InvalidArgument(
            "The input level of LoD is invalid, it should be less than LoD "
            "size. The input level is %zu, the LoD size is %zu.",
            level, NumLevels()));
161
    // the last offset is the end of last element
Q
qijun 已提交
162
    return (lod_)[level].size() - 1;
163 164
  }

X
Xin Pan 已提交
165
  // Split LoDTensor and copy to each place specified in places.
Y
Yang Yang 已提交
166 167 168
  std::vector<LoDTensor> SplitLoDTensor(
      const std::vector<platform::Place> places) const;

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

Q
qijun 已提交
172
 private:
173
  LoD lod_;
174
};
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

/*
 * 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);

201 202 203 204 205 206 207
  PADDLE_ENFORCE_EQ(
      num_instances, lod_level.size() - 1,
      platform::errors::InvalidArgument(
          "The input LoDTensor instance number should be equal to the LoD "
          "level size minus 1."
          "The input instance number is %zu, LoD level size is %zu.",
          num_instances, lod_level.size()));
208 209
  for (size_t ins = 0; ins < num_instances; ins++) {
    for (size_t elem = lod_level[ins]; elem < lod_level[ins + 1]; elem++) {
D
dzhwinter 已提交
210
      auto slice = tensor.Slice(elem, elem + 1);
Y
Yi Wang 已提交
211 212
      TensorCopy(source.Slice(ins, ins + 1), platform::CPUPlace(),
                 platform::CPUDeviceContext(), &slice);
213 214 215 216 217
    }
  }
  return tensor;
}

218 219 220 221 222 223 224 225 226 227 228 229
// 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}
230 231
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);
232

233
void AppendLoD(LoD* lod, const LoD& lod_length);
234

武毅 已提交
235 236 237 238 239 240 241
/*
 * 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 已提交
242 243
void DeserializeFromStream(std::istream& is, LoDTensor* tensor,
                           const platform::DeviceContext& dev_ctx);
T
tangwei12 已提交
244 245 246 247
void DeserializeFromStream(std::istream& is, LoDTensor* tensor,
                           const platform::DeviceContext& dev_ctx,
                           const size_t& seek,
                           const std::vector<int64_t>& shape);
武毅 已提交
248

249 250 251 252 253 254 255 256 257 258 259 260 261 262
/*
 * Convert between length-based LoD and offset-based LoD.
 * The implementation of LoDTensor class use offset-based LoD.
 * However, we want to expose the more user-friendly length-based
 * LoD to the Python side instead.
 *
 * Example:
 * If offset_lod = [[0, 2, 3],[0, 3, 5, 9]]
 * then length_lod = [[2, 1], [3, 2, 4]]
 */
LoD ConvertToLengthBasedLoD(const LoD& offset_lod);

LoD ConvertToOffsetBasedLoD(const LoD& length_lod);

263 264
}  // namespace framework
}  // namespace paddle