mixed_vector.h 15.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2

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
D
dzhwinter 已提交
6

7
    http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8

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. */
D
dzhwinter 已提交
14 15 16

#pragma once

17
#include <algorithm>
D
dzhwinter 已提交
18
#include <initializer_list>
19
#include <memory>
Y
Yu Yang 已提交
20
#include <mutex>  // NOLINT
21
#include <utility>
D
dzhwinter 已提交
22
#include <vector>
W
wanghuancoder 已提交
23 24

#include "glog/logging.h"
25
#include "paddle/fluid/framework/details/cow_ptr.h"
Y
Yi Wang 已提交
26 27
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/tensor_util.h"
28
#include "paddle/fluid/memory/malloc.h"
29
#include "paddle/fluid/memory/memcpy.h"
30 31
#include "paddle/utils/none.h"
#include "paddle/utils/optional.h"
Y
Yu Yang 已提交
32

D
dzhwinter 已提交
33 34 35
namespace paddle {
namespace framework {

36
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
Y
Yu Yang 已提交
37 38
// 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 已提交
39
template <typename T>
Y
Yu Yang 已提交
40
class Vector {
D
dzhwinter 已提交
41
 public:
Y
Yu Yang 已提交
42
  using value_type = T;
43 44
  using iterator = typename std::vector<T>::iterator;
  using const_iterator = typename std::vector<T>::const_iterator;
C
chengduoZH 已提交
45

46 47 48 49 50 51 52 53 54 55 56
 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) {}
Y
Yu Yang 已提交
57
    ~VectorData() {}
58 59 60 61 62 63

    VectorData(const VectorData &o) {
      o.ImmutableCPU();
      cpu_ = o.cpu_;
      flag_ = kDataInCPU;
    }
C
chengduoZH 已提交
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 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
    VectorData &operator=(const VectorData &o) {
      o.ImmutableCPU();
      cpu_ = o.cpu_;
      flag_ = kDataInCPU;
      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();
      auto out_it = std::back_inserter<std::vector<T>>(this->cpu_);
      std::copy(begin, end, out_it);
    }

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

    // get cuda ptr. immutable
    const T *CUDAData(platform::Place place) const {
160 161 162 163
      PADDLE_ENFORCE_EQ(
          platform::is_gpu_place(place), true,
          platform::errors::Unavailable(
              "Place mismatch, CUDA Data must be on CUDA place."));
164
      ImmutableCUDA(place);
165
      return reinterpret_cast<T *>(gpu_->ptr());
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    }

    // 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
Y
Yu Yang 已提交
184
    void reserve(size_t size) const { cpu_.reserve(size); }
185 186 187 188 189 190 191 192 193 194 195 196 197

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

Y
Yu Yang 已提交
198 199
    std::mutex &Mutex() const { return mtx_; }

200
    paddle::optional<platform::CUDAPlace> CUDAPlace() const {
201
      return gpu_ == nullptr
202 203
                 ? paddle::none
                 : paddle::optional<platform::CUDAPlace>(
204
                       BOOST_GET_CONST(platform::CUDAPlace, gpu_->place()));
Y
Yu Yang 已提交
205 206
    }

207 208 209 210 211 212 213 214 215 216
   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
Y
Yu Yang 已提交
217
      auto *dev_ctx = static_cast<platform::CUDADeviceContext *>(
218
          platform::DeviceContextPool::Instance().Get(gpu_->place()));
Y
Yu Yang 已提交
219
      auto stream = dev_ctx->stream();
220
      void *src = gpu_->ptr();
221
      void *dst = cpu_.data();
P
peizhilin 已提交
222
      paddle::memory::Copy(platform::CPUPlace(), dst, CUDAPlace().get(), src,
223
                           gpu_memory_size_, stream);
Y
Yu Yang 已提交
224
      dev_ctx->Wait();
225 226 227 228 229
    }

    void MutableCPU() {
      if (IsInCUDA() && IsDirty()) {
        CopyToCPU();
230
      }
231
      flag_ = kDirty | kDataInCPU;
232
    }
C
chengduoZH 已提交
233

234 235 236 237 238 239
    void ImmutableCUDA(platform::Place place) const {
      if (IsDirty()) {
        if (IsInCPU()) {
          CopyCPUDataToCUDA(place);
          UnsetFlag(kDirty);
          SetFlag(kDataInCUDA);
240
        } else if (IsInCUDA() && !(place == gpu_->place())) {
241 242
          PADDLE_THROW(
              platform::errors::Unavailable("Unexpected data place mismatch."));
243 244 245 246 247 248 249 250 251 252
          // 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);
253
        } else if (!(place == gpu_->place())) {
254 255
          PADDLE_THROW(
              platform::errors::Unavailable("Unexpected data place mismatch."));
256 257 258 259 260
        } else {
          // Not Dirty && DataInCUDA && Device is same
          // Do nothing.
        }
      }
261
    }
262 263 264

    void CopyCPUDataToCUDA(const platform::Place &place) const {
      void *src = cpu_.data();
265 266
      gpu_memory_size_ = cpu_.size() * sizeof(T);
      gpu_ = memory::Alloc(place, gpu_memory_size_);
267
      void *dst = gpu_->ptr();
Y
Yu Yang 已提交
268 269 270
      auto *dev_ctx = static_cast<platform::CUDADeviceContext *>(
          platform::DeviceContextPool::Instance().Get(place));
      auto stream = dev_ctx->stream();
P
peizhilin 已提交
271
      paddle::memory::Copy(CUDAPlace().get(), dst, platform::CPUPlace(), src,
272
                           gpu_memory_size_, stream);
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    }

    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_;
P
peizhilin 已提交
294
    mutable paddle::memory::AllocationPtr gpu_;
295
    mutable size_t gpu_memory_size_{0};
296
    mutable int flag_;
Y
Yu Yang 已提交
297 298

    mutable std::mutex mtx_;
299 300 301 302 303 304 305 306 307 308 309 310
  };

 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 已提交
311

Y
Yu Yang 已提交
312
  // implicit cast from std::vector.
Y
Yu Yang 已提交
313
  template <typename U>
314
  Vector(const std::vector<U> &dat) : m_(new VectorData(dat)) {  // NOLINT
Y
Yu Yang 已提交
315 316
  }

Y
Yu Yang 已提交
317
  // Copy ctor
318
  Vector(const Vector<T> &other) { m_ = other.m_; }
Y
Yu Yang 已提交
319

Y
Yu Yang 已提交
320
  // Copy operator
321
  Vector<T> &operator=(const Vector<T> &other) {
322
    m_ = other.m_;
Y
Yu Yang 已提交
323 324 325
    return *this;
  }

Y
Yu Yang 已提交
326
  // Move ctor
327
  Vector(Vector<T> &&other) { m_ = std::move(other.m_); }
D
dzhwinter 已提交
328

Y
Yu Yang 已提交
329
  // CPU data access method. Mutable.
Y
Yu Yang 已提交
330
  T &operator[](size_t i) { return (*m_.MutableData())[i]; }
Y
Yu Yang 已提交
331

Y
Yu Yang 已提交
332
  // CPU data access method. Immutable.
Y
Yu Yang 已提交
333
  const T &operator[](size_t i) const { return m_.Data()[i]; }
Y
Yu Yang 已提交
334

Y
Yu Yang 已提交
335
  // std::vector iterator methods. Based on CPU data access method
Y
Yu Yang 已提交
336
  size_t size() const { return m_.Data().size(); }
Y
Yu Yang 已提交
337

Y
Yu Yang 已提交
338
  iterator begin() { return m_.MutableData()->begin(); }
Y
Yu Yang 已提交
339

Y
Yu Yang 已提交
340
  iterator end() { return m_.MutableData()->end(); }
Y
Yu Yang 已提交
341

Y
Yu Yang 已提交
342
  T &front() { return m_.MutableData()->front(); }
Y
Yu Yang 已提交
343

Y
Yu Yang 已提交
344
  T &back() { return m_.MutableData()->back(); }
Y
Yu Yang 已提交
345

Y
Yu Yang 已提交
346
  const_iterator begin() const { return m_.Data().begin(); }
Y
Yu Yang 已提交
347

Y
Yu Yang 已提交
348
  const_iterator end() const { return m_.Data().end(); }
349

350
  const_iterator cbegin() const { return begin(); }
Y
Yu Yang 已提交
351

352
  const_iterator cend() const { return end(); }
Y
Yu Yang 已提交
353

Y
Yu Yang 已提交
354
  const T &back() const { return m_.Data().back(); }
Y
Yu Yang 已提交
355

Y
Yu Yang 已提交
356
  T *data() { return m_.MutableData()->data(); }
Y
Yu Yang 已提交
357

Y
Yu Yang 已提交
358
  const T *data() const { return m_.Data().data(); }
Y
Yu Yang 已提交
359

Y
Yu Yang 已提交
360
  const T &front() const { return m_.Data().front(); }
Y
Yu Yang 已提交
361
  // end of std::vector iterator methods
Y
Yu Yang 已提交
362

Y
Yu Yang 已提交
363 364
  // assign this from iterator.
  // NOTE: the iterator must support `end-begin`
Y
Yu Yang 已提交
365 366
  template <typename Iter>
  void assign(Iter begin, Iter end) {
Y
Yu Yang 已提交
367
    m_.MutableData()->assign(begin, end);
Y
Yu Yang 已提交
368 369
  }

Y
Yu Yang 已提交
370 371
  // push_back. If the previous capacity is not enough, the memory will
  // double.
Y
Yu Yang 已提交
372
  void push_back(T elem) { m_.MutableData()->push_back(elem); }
D
dzhwinter 已提交
373

Y
Yu Yang 已提交
374 375 376 377
  // extend a vector by iterator.
  // NOTE: the iterator must support end-begin
  template <typename It>
  void Extend(It begin, It end) {
Y
Yu Yang 已提交
378
    m_.MutableData()->Extend(begin, end);
Y
Yu Yang 已提交
379 380 381
  }

  // resize the vector
C
refine  
chengduoZH 已提交
382
  void resize(size_t size) {
383
    if (m_.Data().size() != size) {
Y
Yu Yang 已提交
384
      m_.MutableData()->resize(size);
C
refine  
chengduoZH 已提交
385 386
    }
  }
D
dzhwinter 已提交
387

Y
Yu Yang 已提交
388
  // get cuda ptr. immutable
C
refine  
chengduoZH 已提交
389
  const T *CUDAData(platform::Place place) const {
Y
Yu Yang 已提交
390 391 392 393
    {
      auto &mtx = m_.Data().Mutex();
      std::lock_guard<std::mutex> guard(mtx);
      auto cuda_place = m_.Data().CUDAPlace();
394
      if (cuda_place == paddle::none ||
395
          cuda_place == BOOST_GET(platform::CUDAPlace, place)) {
Y
Yu Yang 已提交
396 397 398 399 400 401
        return m_.Data().CUDAData(place);
      }
    }
    // If m_ contains CUDAData in a different place. Detach manually.
    m_.Detach();
    return CUDAData(place);
C
refine  
chengduoZH 已提交
402
  }
D
dzhwinter 已提交
403

Y
Yu Yang 已提交
404
  // get cuda ptr. mutable
405
  T *CUDAMutableData(platform::Place place) {
Y
Yu Yang 已提交
406 407 408 409
    {
      auto &mtx = m_.Data().Mutex();
      std::lock_guard<std::mutex> guard(mtx);
      auto cuda_place = m_.Data().CUDAPlace();
410
      if (cuda_place == paddle::none ||
411
          cuda_place == BOOST_GET(platform::CUDAPlace, place)) {
Y
Yu Yang 已提交
412 413 414 415 416 417
        return m_.MutableData()->CUDAMutableData(place);
      }
    }
    // If m_ contains CUDAData in a different place. Detach manually.
    m_.Detach();
    return CUDAMutableData(place);
Y
Yu Yang 已提交
418 419
  }

Y
Yu Yang 已提交
420
  // clear
Y
Yu Yang 已提交
421
  void clear() { m_.MutableData()->clear(); }
Y
Yu Yang 已提交
422

Y
Yu Yang 已提交
423
  size_t capacity() const { return m_.Data().capacity(); }
Y
Yu Yang 已提交
424

Y
Yu Yang 已提交
425
  // reserve data
Y
Yu Yang 已提交
426
  void reserve(size_t size) { m_.Data().reserve(size); }
Y
Yu Yang 已提交
427

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

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

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

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

461
  const void *Handle() const { return &m_.Data(); }
462

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

468 469 470 471 472 473
#else  // PADDLE_WITH_CUDA

template <typename T>
class CPUVector : public std::vector<T, std::allocator<T>> {
 public:
  CPUVector() : std::vector<T>() {}
474
  CPUVector(size_t count, const T &value = T())  // NOLINT
475 476
      : std::vector<T>(count, value) {}
  CPUVector(std::initializer_list<T> init) : std::vector<T>(init) {}
477 478
  CPUVector(const std::vector<T> &other) : std::vector<T>(other) {}  // NOLINT
  CPUVector(const CPUVector<T> &other) : std::vector<T>(other) {}
479
  CPUVector(CPUVector<T> &&other) : std::vector<T>(std::move(other)) {}
480
  CPUVector(std::vector<T> &&other)  // NOLINT
481
      : std::vector<T>(std::move(other)) {}
482 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
  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);
  }
S
sneaxiy 已提交
508 509

  const T *CUDAData(platform::Place place) const {
510 511
    PADDLE_THROW(platform::errors::Unavailable(
        "Vector::CUDAData() method is not supported in CPU-only version."));
S
sneaxiy 已提交
512 513 514
  }

  T *CUDAMutableData(platform::Place place) {
515
    PADDLE_THROW(platform::errors::Unavailable(
S
sneaxiy 已提交
516
        "Vector::CUDAMutableData() method is not supported in CPU-only "
517
        "version."));
S
sneaxiy 已提交
518 519 520
  }

  const T *Data(platform::Place place) const {
521 522 523 524
    PADDLE_ENFORCE_EQ(
        platform::is_cpu_place(place), true,
        platform::errors::Unavailable(
            "Vector::Data() method is not supported when not in CPUPlace."));
S
sneaxiy 已提交
525 526 527 528
    return this->data();
  }

  T *MutableData(platform::Place place) {
529 530 531 532
    PADDLE_ENFORCE_EQ(
        platform::is_cpu_place(place), true,
        platform::errors::Unavailable("Vector::MutableData() method is not "
                                      "supported when not in CPUPlace."));
S
sneaxiy 已提交
533 534 535 536
    return this->data();
  }

  const void *Handle() const { return static_cast<const void *>(this); }
537 538 539 540 541 542 543 544
};

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

#endif  // PADDLE_WITH_CUDA

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