mixed_vector.h 13.3 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>
C
chengduoZH 已提交
20
#include <utility>
D
dzhwinter 已提交
21
#include <vector>
C
chengduoZH 已提交
22
#include "paddle/fluid/framework/details/cow_ptr.h"
Y
Yi Wang 已提交
23 24
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/tensor_util.h"
C
chengduoZH 已提交
25
#include "paddle/fluid/memory/memcpy.h"
Y
Yu Yang 已提交
26 27

#include "glog/logging.h"
D
dzhwinter 已提交
28 29 30 31

namespace paddle {
namespace framework {

32
#if defined(PADDLE_WITH_CUDA)
C
chengduoZH 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
namespace details {
struct CUDABuffer {
  void *data_{nullptr};
  size_t size_{0};
  platform::CUDAPlace place_;

  CUDABuffer() {}
  CUDABuffer(platform::Place place, size_t size)
      : size_(size), place_(boost::get<platform::CUDAPlace>(place)) {
    data_ = memory::Alloc(place_, size);
  }

  ~CUDABuffer() { ClearMemory(); }

  CUDABuffer(const CUDABuffer &o) = delete;
  CUDABuffer &operator=(const CUDABuffer &o) = delete;

  void Resize(platform::Place place, size_t size) {
    ClearMemory();
    place_ = boost::get<platform::CUDAPlace>(place);
    data_ = memory::Alloc(place_, size);
    size_ = size;
  }

  void Swap(CUDABuffer &o) {
    std::swap(data_, o.data_);
    std::swap(place_, o.place_);
    std::swap(size_, o.size_);
  }

 private:
  void ClearMemory() const {
    if (data_) {
      memory::Free(place_, data_);
    }
  }
};
}  // namespace details

Y
Yu Yang 已提交
72 73
// 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 已提交
74
template <typename T>
Y
Yu Yang 已提交
75
class Vector {
D
dzhwinter 已提交
76
 public:
Y
Yu Yang 已提交
77
  using value_type = T;
C
chengduoZH 已提交
78 79
  using iterator = typename std::vector<T>::iterator;
  using const_iterator = typename std::vector<T>::const_iterator;
Y
Yu Yang 已提交
80

C
chengduoZH 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
 private:
  // The actual class to implement vector logic
  class VectorData {
   public:
    VectorData() : flag_(kDataInCPU) {}
    VectorData(size_t count, const T &value)
        : cpu_(count, value), flag_(kDataInCPU) {}
    VectorData(std::initializer_list<T> init) : cpu_(init), flag_(kDataInCPU) {}
    template <typename U>
    explicit VectorData(const std::vector<U> &dat)
        : cpu_(dat), flag_(kDataInCPU) {}

    VectorData(const VectorData &o) {
      o.ImmutableCPU();
      cpu_ = o.cpu_;
      flag_ = kDataInCPU;
    }
Y
Yu Yang 已提交
98

C
chengduoZH 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    VectorData &operator=(const VectorData &o) {
      o.ImmutableCPU();
      cpu_ = o.cpu_;
      flag_ = kDataInCPU;
      details::CUDABuffer null;
      gpu_.Swap(null);
      return *this;
    }

    T &operator[](size_t i) {
      MutableCPU();
      return cpu_[i];
    }

    const T &operator[](size_t i) const {
      ImmutableCPU();
      return cpu_[i];
    }

    size_t size() const { return cpu_.size(); }

    iterator begin() {
      MutableCPU();
      return cpu_.begin();
    }

    iterator end() {
      MutableCPU();
      return cpu_.end();
    }

    T &front() {
      MutableCPU();
      return cpu_.front();
    }

    T &back() {
      MutableCPU();
      return cpu_.back();
    }

    const_iterator begin() const {
      ImmutableCPU();
      return cpu_.begin();
    }

    const_iterator end() const {
      ImmutableCPU();
      return cpu_.end();
    }

    const T &back() const {
      ImmutableCPU();
      return cpu_.back();
    }

    T *data() { return &(*this)[0]; }

    const T *data() const { return &(*this)[0]; }

    const T &front() const {
      ImmutableCPU();
      return cpu_.front();
    }

    // assign this from iterator.
    // NOTE: the iterator must support `end-begin`
    template <typename Iter>
    void assign(Iter begin, Iter end) {
      MutableCPU();
      cpu_.assign(begin, end);
    }

    // push_back. If the previous capacity is not enough, the memory will
    // double.
    void push_back(T elem) {
      MutableCPU();
      cpu_.push_back(elem);
    }

    // extend a vector by iterator.
    // NOTE: the iterator must support end-begin
    template <typename It>
    void Extend(It begin, It end) {
      MutableCPU();
C
refine  
chengduoZH 已提交
184 185
      auto out_it = std::back_inserter<std::vector<T>>(this->cpu_);
      std::copy(begin, end, out_it);
C
chengduoZH 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    }

    // resize the vector
    void resize(size_t size) {
      MutableCPU();
      cpu_.resize(size);
    }

    // get cuda ptr. immutable
    const T *CUDAData(platform::Place place) const {
      PADDLE_ENFORCE(platform::is_gpu_place(place),
                     "CUDA Data must on CUDA place");
      ImmutableCUDA(place);
      return reinterpret_cast<T *>(gpu_.data_);
    }

    // get cuda ptr. mutable
    T *CUDAMutableData(platform::Place place) {
      const T *ptr = CUDAData(place);
      flag_ = kDirty | kDataInCUDA;
      return const_cast<T *>(ptr);
    }

    // clear
    void clear() {
      cpu_.clear();
      flag_ = kDirty | kDataInCPU;
    }

    size_t capacity() const { return cpu_.capacity(); }

    // reserve data
    void reserve(size_t size) { cpu_.reserve(size); }

    // implicit cast operator. Vector can be cast to std::vector implicitly.
    operator std::vector<T>() const {
      ImmutableCPU();
      return cpu_;
    }

    bool operator==(const VectorData &other) const {
      ImmutableCPU();
      other.ImmutableCPU();
      return cpu_ == other.cpu_;
    }

   private:
    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
      void *src = gpu_.data_;
      void *dst = cpu_.data();
      memory::Copy(platform::CPUPlace(), dst, gpu_.place_, src, gpu_.size_,
                   nullptr);
    }

    void MutableCPU() {
      if (IsInCUDA() && IsDirty()) {
        CopyToCPU();
Y
Fix CI  
Yu Yang 已提交
251
      }
C
chengduoZH 已提交
252
      flag_ = kDirty | kDataInCPU;
Y
Yu Yang 已提交
253 254
    }

C
chengduoZH 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    void ImmutableCUDA(platform::Place place) const {
      if (IsDirty()) {
        if (IsInCPU()) {
          CopyCPUDataToCUDA(place);
          UnsetFlag(kDirty);
          SetFlag(kDataInCUDA);
        } else if (IsInCUDA() &&
                   !(boost::get<platform::CUDAPlace>(place) == gpu_.place_)) {
          CopyCUDADataToAnotherPlace(place);
          // 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.
          CopyCPUDataToCUDA(place);
          SetFlag(kDataInCUDA);
        } else if (!(boost::get<platform::CUDAPlace>(place) == gpu_.place_)) {
          CopyCUDADataToAnotherPlace(place);
        } else {
          // Not Dirty && DataInCUDA && Device is same
          // Do nothing.
        }
      }
Y
Fix CI  
Yu Yang 已提交
281
    }
C
chengduoZH 已提交
282 283 284 285 286 287 288 289 290 291 292 293
    void CopyCUDADataToAnotherPlace(const platform::Place &place) const {
      details::CUDABuffer tmp(place, gpu_.size_);
      const void *src = gpu_.data_;
      void *dst = tmp.data_;

      memory::Copy(tmp.place_, dst, gpu_.place_, src, gpu_.size_, nullptr);
      gpu_.Swap(tmp);
    }
    void CopyCPUDataToCUDA(const platform::Place &place) const {
      void *src = cpu_.data();
      gpu_.Resize(place, cpu_.size() * sizeof(T));
      void *dst = gpu_.data_;
C
refine  
chengduoZH 已提交
294 295 296 297 298
      auto stream = static_cast<platform::CUDADeviceContext *>(
                        platform::DeviceContextPool::Instance().Get(place))
                        ->stream();
      memory::Copy(gpu_.place_, dst, platform::CPUPlace(), src, gpu_.size_,
                   stream);
C
chengduoZH 已提交
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
    }

    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; }

    mutable std::vector<T> cpu_;
    mutable details::CUDABuffer gpu_;
    mutable int flag_;
  };

 public:
  // Default ctor. Create empty Vector
  Vector() : m_(new VectorData()) {}

  // Fill vector with value. The vector size is `count`.
  explicit Vector(size_t count, const T &value = T())
      : m_(new VectorData(count, value)) {}

  // Ctor with init_list
  Vector(std::initializer_list<T> init) : m_(new VectorData(init)) {}
Y
Yu Yang 已提交
334

Y
Yu Yang 已提交
335
  // implicit cast from std::vector.
Y
Yu Yang 已提交
336
  template <typename U>
C
chengduoZH 已提交
337
  Vector(const std::vector<U> &dat) : m_(new VectorData(dat)) {  // NOLINT
Y
Yu Yang 已提交
338 339
  }

Y
Yu Yang 已提交
340
  // Copy ctor
C
chengduoZH 已提交
341
  Vector(const Vector<T> &other) { m_ = other.m_; }
Y
Yu Yang 已提交
342

Y
Yu Yang 已提交
343
  // Copy operator
344
  Vector<T> &operator=(const Vector<T> &other) {
C
chengduoZH 已提交
345
    m_ = other.m_;
Y
Yu Yang 已提交
346 347 348
    return *this;
  }

Y
Yu Yang 已提交
349
  // Move ctor
C
chengduoZH 已提交
350
  Vector(Vector<T> &&other) { m_ = std::move(other.m_); }
D
dzhwinter 已提交
351

Y
Yu Yang 已提交
352
  // CPU data access method. Mutable.
C
chengduoZH 已提交
353
  T &operator[](size_t i) { return (*m_)[i]; }
Y
Yu Yang 已提交
354

Y
Yu Yang 已提交
355
  // CPU data access method. Immutable.
C
chengduoZH 已提交
356
  const T &operator[](size_t i) const { return (*m_)[i]; }
Y
Yu Yang 已提交
357

Y
Yu Yang 已提交
358
  // std::vector iterator methods. Based on CPU data access method
C
chengduoZH 已提交
359
  size_t size() const { return m_->size(); }
Y
Yu Yang 已提交
360

C
chengduoZH 已提交
361
  iterator begin() { return m_->begin(); }
Y
Yu Yang 已提交
362

C
chengduoZH 已提交
363
  iterator end() { return m_->end(); }
Y
Yu Yang 已提交
364

C
chengduoZH 已提交
365
  T &front() { return m_->front(); }
Y
Yu Yang 已提交
366

C
chengduoZH 已提交
367
  T &back() { return m_->back(); }
Y
Yu Yang 已提交
368

C
chengduoZH 已提交
369
  const_iterator begin() const { return m_->begin(); }
Y
Yu Yang 已提交
370

C
chengduoZH 已提交
371
  const_iterator end() const { return m_->end(); }
372

C
chengduoZH 已提交
373
  const_iterator cbegin() const { return begin(); }
Y
Yu Yang 已提交
374

C
chengduoZH 已提交
375
  const_iterator cend() const { return end(); }
Y
Yu Yang 已提交
376

C
chengduoZH 已提交
377
  const T &back() const { return m_->back(); }
Y
Yu Yang 已提交
378

C
chengduoZH 已提交
379
  T *data() { return m_->data(); }
Y
Yu Yang 已提交
380

C
chengduoZH 已提交
381
  const T *data() const { return m_->data(); }
Y
Yu Yang 已提交
382

C
chengduoZH 已提交
383
  const T &front() const { return m_->front(); }
Y
Yu Yang 已提交
384
  // end of std::vector iterator methods
Y
Yu Yang 已提交
385

Y
Yu Yang 已提交
386 387
  // assign this from iterator.
  // NOTE: the iterator must support `end-begin`
Y
Yu Yang 已提交
388 389
  template <typename Iter>
  void assign(Iter begin, Iter end) {
C
chengduoZH 已提交
390
    m_->assign(begin, end);
Y
Yu Yang 已提交
391 392
  }

Y
Yu Yang 已提交
393 394
  // push_back. If the previous capacity is not enough, the memory will
  // double.
C
chengduoZH 已提交
395
  void push_back(T elem) { m_->push_back(elem); }
D
dzhwinter 已提交
396

Y
Yu Yang 已提交
397 398 399 400
  // extend a vector by iterator.
  // NOTE: the iterator must support end-begin
  template <typename It>
  void Extend(It begin, It end) {
C
chengduoZH 已提交
401
    m_->Extend(begin, end);
Y
Yu Yang 已提交
402 403 404
  }

  // resize the vector
C
refine  
chengduoZH 已提交
405 406 407 408 409
  void resize(size_t size) {
    if (m_.Data().size() != size) {
      m_->resize(size);
    }
  }
D
dzhwinter 已提交
410

Y
Yu Yang 已提交
411
  // get cuda ptr. immutable
C
refine  
chengduoZH 已提交
412 413 414
  const T *CUDAData(platform::Place place) const {
    return m_.Data().CUDAData(place);
  }
D
dzhwinter 已提交
415

Y
Yu Yang 已提交
416
  // get cuda ptr. mutable
417
  T *CUDAMutableData(platform::Place place) {
C
chengduoZH 已提交
418
    return m_->CUDAMutableData(place);
Y
Yu Yang 已提交
419 420
  }

Y
Yu Yang 已提交
421
  // clear
C
chengduoZH 已提交
422
  void clear() { m_->clear(); }
Y
Yu Yang 已提交
423

C
chengduoZH 已提交
424
  size_t capacity() const { return m_->capacity(); }
Y
Yu Yang 已提交
425

Y
Yu Yang 已提交
426
  // reserve data
C
chengduoZH 已提交
427
  void reserve(size_t size) { m_->reserve(size); }
Y
Yu Yang 已提交
428

Y
Yu Yang 已提交
429
  // the unify method to access CPU or CUDA data. immutable.
430
  const T *Data(platform::Place place) const {
Y
Yu Yang 已提交
431 432 433
    if (platform::is_gpu_place(place)) {
      return CUDAData(place);
    } else {
434
      return data();
Y
Yu Yang 已提交
435 436 437
    }
  }

Y
Yu Yang 已提交
438
  // the unify method to access CPU or CUDA data. mutable.
439
  T *MutableData(platform::Place place) {
Y
Yu Yang 已提交
440 441
    if (platform::is_gpu_place(place)) {
      return CUDAMutableData(place);
442
    } else {
Y
Yu Yang 已提交
443
      return data();
444 445 446
    }
  }

Y
Yu Yang 已提交
447
  // implicit cast operator. Vector can be cast to std::vector implicitly.
C
chengduoZH 已提交
448
  operator std::vector<T>() const { return *m_; }
Y
Yu Yang 已提交
449

450
  bool operator==(const Vector<T> &other) const {
Y
Yu Yang 已提交
451
    if (size() != other.size()) return false;
452 453 454
    auto it1 = cbegin();
    auto it2 = other.cbegin();
    for (; it1 < cend(); ++it1, ++it2) {
Y
Yu Yang 已提交
455 456 457 458 459 460
      if (*it1 != *it2) {
        return false;
      }
    }
    return true;
  }
D
dzhwinter 已提交
461

C
refine  
chengduoZH 已提交
462 463
  const void *Handle() const { return &m_.Data(); }

D
dzhwinter 已提交
464
 private:
C
chengduoZH 已提交
465 466
  // Vector is an COW object.
  details::COWPtr<VectorData> m_;
Y
Yu Yang 已提交
467
};
D
dzhwinter 已提交
468

469 470 471 472 473 474
#else  // PADDLE_WITH_CUDA

template <typename T>
class CPUVector : public std::vector<T, std::allocator<T>> {
 public:
  CPUVector() : std::vector<T>() {}
475
  CPUVector(size_t count, const T &value = T())  // NOLINT
476 477
      : std::vector<T>(count, value) {}
  CPUVector(std::initializer_list<T> init) : std::vector<T>(init) {}
478 479
  CPUVector(const std::vector<T> &other) : std::vector<T>(other) {}  // NOLINT
  CPUVector(const CPUVector<T> &other) : std::vector<T>(other) {}
480
  CPUVector(CPUVector<T> &&other) : std::vector<T>(std::move(other)) {}
481
  CPUVector(std::vector<T> &&other)  // NOLINT
482
      : std::vector<T>(std::move(other)) {}
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  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 已提交
517
}  // namespace paddle