mixed_vector.h 11.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

   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. */

#pragma once

17
#include <algorithm>
D
dzhwinter 已提交
18
#include <initializer_list>
19
#include <memory>
D
dzhwinter 已提交
20
#include <vector>
21

Y
Yi Wang 已提交
22 23
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/tensor_util.h"
Y
Yu Yang 已提交
24 25

#include "glog/logging.h"
D
dzhwinter 已提交
26 27 28 29

namespace paddle {
namespace framework {

30
#if defined(PADDLE_WITH_CUDA)
Y
Yu Yang 已提交
31 32
// Vector<T> implements the std::vector interface, and can get Data or
// MutableData from any place. The data will be synced implicitly inside.
D
dzhwinter 已提交
33
template <typename T>
Y
Yu Yang 已提交
34
class Vector {
D
dzhwinter 已提交
35
 public:
Y
Yu Yang 已提交
36
  using value_type = T;
C
chengduoZH 已提交
37 38

  // Default ctor. Create empty Vector
39
  Vector() { InitEmpty(); }
C
chengduoZH 已提交
40 41

  // Fill vector with value. The vector size is `count`.
42 43 44 45 46 47 48 49 50 51
  explicit Vector(size_t count, const T &value = T()) {
    InitEmpty();
    if (count != 0) {
      resize(count);
      T *ptr = begin();
      for (size_t i = 0; i < count; ++i) {
        ptr[i] = value;
      }
    }
  }
C
chengduoZH 已提交
52 53

  // Ctor with init_list
54 55 56 57 58 59 60
  Vector(std::initializer_list<T> init) {
    if (init.size() == 0) {
      InitEmpty();
    } else {
      InitByIter(init.size(), init.begin(), init.end());
    }
  }
Y
Yu Yang 已提交
61

Y
Yu Yang 已提交
62
  // implicit cast from std::vector.
Y
Yu Yang 已提交
63
  template <typename U>
64 65 66 67 68 69
  Vector(const std::vector<U> &dat) {  // NOLINT
    if (dat.size() == 0) {
      InitEmpty();
    } else {
      InitByIter(dat.size(), dat.begin(), dat.end());
    }
Y
Yu Yang 已提交
70 71
  }

Y
Yu Yang 已提交
72
  // Copy ctor
73
  Vector(const Vector<T> &other) { this->operator=(other); }
Y
Yu Yang 已提交
74

Y
Yu Yang 已提交
75
  // Copy operator
76
  Vector<T> &operator=(const Vector<T> &other) {
77 78 79 80 81
    if (other.size() != 0) {
      this->InitByIter(other.size(), other.begin(), other.end());
    } else {
      InitEmpty();
    }
Y
Yu Yang 已提交
82 83 84
    return *this;
  }

Y
Yu Yang 已提交
85
  // Move ctor
86 87 88 89 90 91 92 93 94 95
  Vector(Vector<T> &&other) {
    this->size_ = other.size_;
    this->flag_ = other.flag_;
    if (other.cuda_vec_.memory_size()) {
      this->cuda_vec_.ShareDataWith(other.cuda_vec_);
    }
    if (other.cpu_vec_.memory_size()) {
      this->cpu_vec_.ShareDataWith(other.cpu_vec_);
    }
  }
D
dzhwinter 已提交
96

Y
Yu Yang 已提交
97
  // CPU data access method. Mutable.
98 99 100 101
  T &operator[](size_t i) {
    MutableCPU();
    return const_cast<T *>(cpu_vec_.data<T>())[i];
  }
Y
Yu Yang 已提交
102

Y
Yu Yang 已提交
103
  // CPU data access method. Immutable.
104 105 106 107
  const T &operator[](size_t i) const {
    ImmutableCPU();
    return cpu_vec_.data<T>()[i];
  }
Y
Yu Yang 已提交
108

Y
Yu Yang 已提交
109
  // std::vector iterator methods. Based on CPU data access method
110
  size_t size() const { return size_; }
Y
Yu Yang 已提交
111

112
  T *begin() { return capacity() == 0 ? &EmptyDummy() : &this->operator[](0); }
Y
Yu Yang 已提交
113

114 115 116
  T *end() {
    return capacity() == 0 ? &EmptyDummy() : &this->operator[](size());
  }
Y
Yu Yang 已提交
117

118
  T &front() { return *begin(); }
Y
Yu Yang 已提交
119

120 121 122 123 124
  T &back() {
    auto it = end();
    --it;
    return *it;
  }
Y
Yu Yang 已提交
125

126 127 128
  const T *begin() const {
    return capacity() == 0 ? &EmptyDummy() : &this->operator[](0);
  }
Y
Yu Yang 已提交
129

130 131 132
  const T *end() const {
    return capacity() == 0 ? &EmptyDummy() : &this->operator[](size());
  }
133

134
  const T *cbegin() const { return begin(); }
Y
Yu Yang 已提交
135

136
  const T *cend() const { return end(); }
Y
Yu Yang 已提交
137

138 139 140 141 142
  const T &back() const {
    auto it = end();
    --it;
    return *it;
  }
Y
Yu Yang 已提交
143

144
  T *data() { return begin(); }
Y
Yu Yang 已提交
145

146
  const T *data() const { return begin(); }
Y
Yu Yang 已提交
147

148
  const T &front() const { return *begin(); }
Y
Yu Yang 已提交
149
  // end of std::vector iterator methods
Y
Yu Yang 已提交
150

Y
Yu Yang 已提交
151 152
  // assign this from iterator.
  // NOTE: the iterator must support `end-begin`
Y
Yu Yang 已提交
153 154
  template <typename Iter>
  void assign(Iter begin, Iter end) {
155
    InitByIter(end - begin, begin, end);
Y
Yu Yang 已提交
156 157
  }

Y
Yu Yang 已提交
158 159
  // push_back. If the previous capacity is not enough, the memory will
  // double.
160 161 162 163 164 165 166
  void push_back(T elem) {
    if (size_ + 1 > capacity()) {
      reserve((size_ + 1) << 1);
    }
    *end() = elem;
    ++size_;
  }
D
dzhwinter 已提交
167

Y
Yu Yang 已提交
168 169 170 171
  // extend a vector by iterator.
  // NOTE: the iterator must support end-begin
  template <typename It>
  void Extend(It begin, It end) {
172 173 174 175 176 177
    size_t pre_size = size_;
    resize(pre_size + (end - begin));
    T *ptr = this->begin() + pre_size;
    for (; begin < end; ++begin, ++ptr) {
      *ptr = *begin;
    }
Y
Yu Yang 已提交
178 179 180
  }

  // resize the vector
C
refine  
chengduoZH 已提交
181
  void resize(size_t size) {
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    if (size + 1 <= capacity()) {
      size_ = size;
    } else {
      MutableCPU();
      Tensor cpu_tensor;
      platform::Place cpu = platform::CPUPlace();
      T *ptr = cpu_tensor.mutable_data<T>(
          framework::make_ddim({static_cast<int64_t>(size)}), cpu);
      const T *old_ptr =
          cpu_vec_.memory_size() == 0 ? nullptr : cpu_vec_.data<T>();
      if (old_ptr != nullptr) {
        std::copy(old_ptr, old_ptr + size_, ptr);
      }
      size_ = size;
      cpu_vec_.ShareDataWith(cpu_tensor);
C
refine  
chengduoZH 已提交
197 198
    }
  }
D
dzhwinter 已提交
199

Y
Yu Yang 已提交
200
  // get cuda ptr. immutable
C
refine  
chengduoZH 已提交
201
  const T *CUDAData(platform::Place place) const {
202 203 204 205
    PADDLE_ENFORCE(platform::is_gpu_place(place),
                   "CUDA Data must on CUDA place");
    ImmutableCUDA(place);
    return cuda_vec_.data<T>();
C
refine  
chengduoZH 已提交
206
  }
D
dzhwinter 已提交
207

Y
Yu Yang 已提交
208
  // get cuda ptr. mutable
209
  T *CUDAMutableData(platform::Place place) {
210 211 212
    const T *ptr = CUDAData(place);
    flag_ = kDirty | kDataInCUDA;
    return const_cast<T *>(ptr);
Y
Yu Yang 已提交
213 214
  }

Y
Yu Yang 已提交
215
  // clear
216 217 218 219
  void clear() {
    size_ = 0;
    flag_ = kDirty | kDataInCPU;
  }
Y
Yu Yang 已提交
220

221 222 223
  size_t capacity() const {
    return cpu_vec_.memory_size() / SizeOfType(typeid(T));
  }
Y
Yu Yang 已提交
224

Y
Yu Yang 已提交
225
  // reserve data
226 227 228 229 230
  void reserve(size_t size) {
    size_t pre_size = size_;
    resize(size);
    resize(pre_size);
  }
Y
Yu Yang 已提交
231

Y
Yu Yang 已提交
232
  // the unify method to access CPU or CUDA data. immutable.
233
  const T *Data(platform::Place place) const {
Y
Yu Yang 已提交
234 235 236
    if (platform::is_gpu_place(place)) {
      return CUDAData(place);
    } else {
237
      return data();
Y
Yu Yang 已提交
238 239 240
    }
  }

Y
Yu Yang 已提交
241
  // the unify method to access CPU or CUDA data. mutable.
242
  T *MutableData(platform::Place place) {
Y
Yu Yang 已提交
243 244
    if (platform::is_gpu_place(place)) {
      return CUDAMutableData(place);
245
    } else {
Y
Yu Yang 已提交
246
      return data();
247 248 249
    }
  }

Y
Yu Yang 已提交
250
  // implicit cast operator. Vector can be cast to std::vector implicitly.
251 252 253 254 255 256
  operator std::vector<T>() const {
    std::vector<T> result;
    result.resize(size());
    std::copy(begin(), end(), result.begin());
    return result;
  }
Y
Yu Yang 已提交
257

258
  bool operator==(const Vector<T> &other) const {
Y
Yu Yang 已提交
259
    if (size() != other.size()) return false;
260 261 262
    auto it1 = cbegin();
    auto it2 = other.cbegin();
    for (; it1 < cend(); ++it1, ++it2) {
Y
Yu Yang 已提交
263 264 265 266 267 268
      if (*it1 != *it2) {
        return false;
      }
    }
    return true;
  }
D
dzhwinter 已提交
269 270

 private:
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  void InitEmpty() {
    size_ = 0;
    flag_ = kDataInCPU;
  }

  template <typename Iter>
  void InitByIter(size_t size, Iter begin, Iter end) {
    platform::Place cpu = platform::CPUPlace();
    T *ptr = this->cpu_vec_.template mutable_data<T>(
        framework::make_ddim({static_cast<int64_t>(size)}), cpu);
    for (size_t i = 0; i < size; ++i) {
      *ptr++ = *begin++;
    }
    flag_ = kDataInCPU | kDirty;
    size_ = size;
  }

  enum DataFlag {
    kDataInCPU = 0x01,
    kDataInCUDA = 0x02,
    // kDirty means the data has been changed in one device.
    kDirty = 0x10
  };

  void CopyToCPU() const {
    // COPY GPU Data To CPU
    TensorCopy(cuda_vec_, platform::CPUPlace(), &cpu_vec_);
    WaitPlace(cuda_vec_.place());
  }

  void MutableCPU() {
    if (IsInCUDA() && IsDirty()) {
      CopyToCPU();
    }
    flag_ = kDirty | kDataInCPU;
  }

  void ImmutableCUDA(platform::Place place) const {
    if (IsDirty()) {
      if (IsInCPU()) {
        TensorCopy(cpu_vec_, boost::get<platform::CUDAPlace>(place),
                   &cuda_vec_);
        WaitPlace(place);
        UnsetFlag(kDirty);
        SetFlag(kDataInCUDA);
      } else if (IsInCUDA() && !(place == cuda_vec_.place())) {
        framework::Tensor tmp;
        TensorCopy(cuda_vec_, boost::get<platform::CUDAPlace>(place), &tmp);
        WaitPlace(cuda_vec_.place());
        cuda_vec_.ShareDataWith(tmp);
        // Still dirty
      } else {
        // Dirty && DataInCUDA && Device is same
        // Do nothing
      }
    } else {
      if (!IsInCUDA()) {
        // Even data is not dirty. However, data is not in CUDA. Copy data.
        TensorCopy(cpu_vec_, boost::get<platform::CUDAPlace>(place),
                   &cuda_vec_);
        WaitPlace(place);
        SetFlag(kDataInCUDA);
      } else if (!(place == cuda_vec_.place())) {
        framework::Tensor tmp;
        WaitPlace(cuda_vec_.place());
        TensorCopy(cuda_vec_, boost::get<platform::CUDAPlace>(place), &tmp);
        WaitPlace(cuda_vec_.place());
        WaitPlace(place);
        cuda_vec_.ShareDataWith(tmp);
      } else {
        // Not Dirty && DataInCUDA && Device is same
        // Do nothing.
      }
    }
  }

  void ImmutableCPU() const {
    if (IsDirty() &&
        !IsInCPU()) {  // If data has been changed in CUDA, or CPU has no data.
      CopyToCPU();
      UnsetFlag(kDirty);
    }
    SetFlag(kDataInCPU);
  }

  void UnsetFlag(int flag) const { flag_ &= ~flag; }
  void SetFlag(int flag) const { flag_ |= flag; }

  bool IsDirty() const { return flag_ & kDirty; }

  bool IsInCUDA() const { return flag_ & kDataInCUDA; }

  bool IsInCPU() const { return flag_ & kDataInCPU; }

  static void WaitPlace(const platform::Place place) {
    if (platform::is_gpu_place(place)) {
      platform::DeviceContextPool::Instance()
          .Get(boost::get<platform::CUDAPlace>(place))
          ->Wait();
    }
  }

  static T &EmptyDummy() {
    static T dummy = T();
    return dummy;
  }

  mutable int flag_;
  mutable Tensor cpu_vec_;
  mutable Tensor cuda_vec_;
  size_t size_;
Y
Yu Yang 已提交
382
};
D
dzhwinter 已提交
383

384 385 386 387 388 389
#else  // PADDLE_WITH_CUDA

template <typename T>
class CPUVector : public std::vector<T, std::allocator<T>> {
 public:
  CPUVector() : std::vector<T>() {}
390
  CPUVector(size_t count, const T &value = T())  // NOLINT
391 392
      : std::vector<T>(count, value) {}
  CPUVector(std::initializer_list<T> init) : std::vector<T>(init) {}
393 394
  CPUVector(const std::vector<T> &other) : std::vector<T>(other) {}  // NOLINT
  CPUVector(const CPUVector<T> &other) : std::vector<T>(other) {}
395
  CPUVector(CPUVector<T> &&other) : std::vector<T>(std::move(other)) {}
396
  CPUVector(std::vector<T> &&other)  // NOLINT
397
      : std::vector<T>(std::move(other)) {}
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  CPUVector &operator=(const CPUVector &other) {
    this->assign(other.begin(), other.end());
    return *this;
  }
  CPUVector &operator=(const std::vector<T> &other) {
    this->assign(other.begin(), other.end());
    return *this;
  }

  friend std::ostream &operator<<(std::ostream &os, const CPUVector<T> &other) {
    std::stringstream ss;
    for (auto v : other) {
      os << v << " ";
    }
    return os;
  }

  T &operator[](size_t id) { return this->at(id); }

  const T &operator[](size_t id) const { return this->at(id); }

  template <typename D>
  void Extend(const D &begin, const D &end) {
    this->reserve(this->size() + size_t(end - begin));
    this->insert(this->end(), begin, end);
  }
};

template <typename T>
using Vector = CPUVector<T>;

#endif  // PADDLE_WITH_CUDA

};  // namespace framework
D
dzhwinter 已提交
432
}  // namespace paddle