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

   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

#include <initializer_list>
#include <vector>

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

#include "glog/logging.h"
D
dzhwinter 已提交
24 25 26 27

namespace paddle {
namespace framework {

Y
Yu Yang 已提交
28 29
// 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 已提交
30
template <typename T>
Y
Yu Yang 已提交
31
class Vector {
D
dzhwinter 已提交
32
 public:
Y
Yu Yang 已提交
33 34
  using value_type = T;

Y
Yu Yang 已提交
35
  // Default ctor. Create empty Vector
Y
Fix CI  
Yu Yang 已提交
36
  Vector() { InitEmpty(); }
Y
Yu Yang 已提交
37

Y
Yu Yang 已提交
38
  // Fill vector with value. The vector size is `count`.
Y
Yu Yang 已提交
39
  explicit Vector(size_t count, const T& value = T()) {
40 41
    InitEmpty();
    if (count != 0) {
Y
Fix CI  
Yu Yang 已提交
42 43 44 45 46
      resize(count);
      T* ptr = begin();
      for (size_t i = 0; i < count; ++i) {
        ptr[i] = value;
      }
Y
Yu Yang 已提交
47 48 49
    }
  }

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

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

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

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

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

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

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

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

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

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

  T& front() { return *begin(); }

  T& back() {
    auto it = end();
    --it;
    return *it;
  }

Y
Yu Yang 已提交
121 122 123
  const T* begin() const {
    return size() == 0 ? &EmptyDummy() : &this->operator[](0);
  }
Y
Yu Yang 已提交
124

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

Y
Yu Yang 已提交
129 130 131 132
  const T* cbegin() const { return begin(); }

  const T* cend() const { return end(); }

Y
Yu Yang 已提交
133 134 135 136 137 138
  const T& back() const {
    auto it = end();
    --it;
    return *it;
  }

Y
Yu Yang 已提交
139 140 141 142
  T* data() { return begin(); }

  const T* data() const { return begin(); }

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

Y
Yu Yang 已提交
146 147
  // assign this from iterator.
  // NOTE: the iterator must support `end-begin`
Y
Yu Yang 已提交
148 149 150 151 152
  template <typename Iter>
  void assign(Iter begin, Iter end) {
    InitByIter(end - begin, begin, end);
  }

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

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

  // resize the vector
Y
Yu Yang 已提交
176 177 178 179 180 181 182 183 184 185
  void resize(size_t size) {
    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 =
Y
Yu Yang 已提交
186
          cpu_vec_.memory_size() == 0 ? nullptr : cpu_vec_.data<T>();
Y
Yu Yang 已提交
187 188 189 190 191 192
      if (old_ptr != nullptr) {
        std::copy(old_ptr, old_ptr + size_, ptr);
      }
      size_ = size;
      cpu_vec_.ShareDataWith(cpu_tensor);
    }
D
dzhwinter 已提交
193 194
  }

Y
Yu Yang 已提交
195
  // get cuda ptr. immutable
Y
Yu Yang 已提交
196 197 198 199 200 201
  const T* CUDAData(platform::Place place) const {
    PADDLE_ENFORCE(platform::is_gpu_place(place),
                   "CUDA Data must on CUDA place");
    ImmutableCUDA(place);
    return cuda_vec_.data<T>();
  }
D
dzhwinter 已提交
202

Y
Yu Yang 已提交
203
  // get cuda ptr. mutable
Y
Yu Yang 已提交
204 205 206 207 208 209
  T* CUDAMutableData(platform::Place place) {
    const T* ptr = CUDAData(place);
    flag_ = kDirty | kDataInCUDA;
    return const_cast<T*>(ptr);
  }

Y
Yu Yang 已提交
210
  // clear
Y
Yu Yang 已提交
211 212 213 214 215 216
  void clear() {
    size_ = 0;
    flag_ = kDirty | kDataInCPU;
  }

  size_t capacity() const {
Y
Yu Yang 已提交
217
    return cpu_vec_.memory_size() / SizeOfType(typeid(T));
Y
Yu Yang 已提交
218 219
  }

Y
Yu Yang 已提交
220
  // reserve data
Y
Yu Yang 已提交
221 222 223 224 225 226
  void reserve(size_t size) {
    size_t pre_size = size_;
    resize(size);
    resize(pre_size);
  }

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

Y
Yu Yang 已提交
236
  // the unify method to access CPU or CUDA data. mutable.
Y
Yu Yang 已提交
237 238 239
  T* MutableData(platform::Place place) {
    if (platform::is_gpu_place(place)) {
      return CUDAMutableData(place);
240
    } else {
Y
Yu Yang 已提交
241
      return data();
242 243 244
    }
  }

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

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

 private:
Y
Fix CI  
Yu Yang 已提交
266 267 268 269 270
  void InitEmpty() {
    size_ = 0;
    flag_ = kDataInCPU;
  }

Y
Yu Yang 已提交
271 272 273 274 275 276 277 278 279 280 281
  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;
  }
D
dzhwinter 已提交
282

Y
Yu Yang 已提交
283 284 285 286 287 288
  enum DataFlag {
    kDataInCPU = 0x01,
    kDataInCUDA = 0x02,
    // kDirty means the data has been changed in one device.
    kDirty = 0x10
  };
Y
Yu Yang 已提交
289

Y
Fix CI  
Yu Yang 已提交
290 291 292 293 294 295
  void CopyToCPU() const {
    // COPY GPU Data To CPU
    Copy(cuda_vec_, platform::CPUPlace(), &cpu_vec_);
    WaitPlace(cuda_vec_.place());
  }

Y
Yu Yang 已提交
296 297
  void MutableCPU() {
    if (IsInCUDA() && IsDirty()) {
Y
Fix CI  
Yu Yang 已提交
298
      CopyToCPU();
D
dzhwinter 已提交
299
    }
Y
Yu Yang 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    flag_ = kDirty | kDataInCPU;
  }

  void ImmutableCUDA(platform::Place place) const {
    if (IsDirty()) {
      if (IsInCPU()) {
        Copy(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;
        Copy(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
      }
D
dzhwinter 已提交
320
    } else {
Y
Yu Yang 已提交
321 322 323 324 325 326 327
      if (!IsInCUDA()) {
        // Even data is not dirty. However, data is not in CUDA. Copy data.
        Copy(cpu_vec_, boost::get<platform::CUDAPlace>(place), &cuda_vec_);
        WaitPlace(place);
        SetFlag(kDataInCUDA);
      } else if (!(place == cuda_vec_.place())) {
        framework::Tensor tmp;
Y
Fix CI  
Yu Yang 已提交
328
        WaitPlace(cuda_vec_.place());
Y
Yu Yang 已提交
329 330
        Copy(cuda_vec_, boost::get<platform::CUDAPlace>(place), &tmp);
        WaitPlace(cuda_vec_.place());
Y
Fix CI  
Yu Yang 已提交
331
        WaitPlace(place);
Y
Yu Yang 已提交
332 333 334 335 336
        cuda_vec_.ShareDataWith(tmp);
      } else {
        // Not Dirty && DataInCUDA && Device is same
        // Do nothing.
      }
D
dzhwinter 已提交
337 338 339
    }
  }

Y
Yu Yang 已提交
340 341 342
  void ImmutableCPU() const {
    if (IsDirty() &&
        !IsInCPU()) {  // If data has been changed in CUDA, or CPU has no data.
Y
Fix CI  
Yu Yang 已提交
343
      CopyToCPU();
Y
Yu Yang 已提交
344
      UnsetFlag(kDirty);
D
dzhwinter 已提交
345
    }
Y
Yu Yang 已提交
346 347
    SetFlag(kDataInCPU);
  }
D
dzhwinter 已提交
348

Y
Yu Yang 已提交
349 350
  void UnsetFlag(int flag) const { flag_ &= ~flag; }
  void SetFlag(int flag) const { flag_ |= flag; }
D
dzhwinter 已提交
351

Y
Yu Yang 已提交
352
  bool IsDirty() const { return flag_ & kDirty; }
D
dzhwinter 已提交
353

Y
Yu Yang 已提交
354 355 356 357 358 359 360 361 362 363 364 365
  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();
    }
  }

Y
Yu Yang 已提交
366 367 368 369 370
  static T& EmptyDummy() {
    static T dummy = T();
    return dummy;
  }

Y
Yu Yang 已提交
371 372 373 374 375
  mutable int flag_;
  mutable Tensor cpu_vec_;
  mutable Tensor cuda_vec_;
  size_t size_;
};
D
dzhwinter 已提交
376 377 378

}  // namespace framework
}  // namespace paddle