allocator_facade.cc 55.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

15 16
#include "paddle/fluid/memory/allocation/allocator_facade.h"

17
#include "paddle/fluid/memory/allocation/aligned_allocator.h"
18
#include "paddle/fluid/memory/allocation/allocator.h"
Y
Yu Yang 已提交
19
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
20
#include "paddle/fluid/memory/allocation/auto_growth_best_fit_allocator.h"
21
#include "paddle/fluid/memory/allocation/cpu_allocator.h"
22
#include "paddle/fluid/memory/allocation/naive_best_fit_allocator.h"
S
sneaxiy 已提交
23
#include "paddle/fluid/memory/allocation/retry_allocator.h"
24
#include "paddle/fluid/memory/allocation/stat_allocator.h"
25
#include "paddle/fluid/platform/device_context.h"
S
sneaxiy 已提交
26
#include "paddle/fluid/platform/enforce.h"
27
#include "paddle/fluid/platform/place.h"
28
#include "paddle/phi/core/macros.h"
29

30
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
31
#include <shared_mutex>
32

33
#include "paddle/fluid/memory/allocation/cuda_allocator.h"
34
#include "paddle/fluid/memory/allocation/cuda_managed_allocator.h"
S
sneaxiy 已提交
35
#include "paddle/fluid/memory/allocation/pinned_allocator.h"
36
#include "paddle/fluid/memory/allocation/stream_safe_cuda_allocator.h"
37
#include "paddle/fluid/memory/allocation/thread_local_allocator.h"
38
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
39
#include "paddle/phi/backends/gpu/gpu_context.h"
40 41

#ifdef PADDLE_WITH_CUDA
42
#include "paddle/phi/backends/gpu/cuda/cuda_graph.h"
43
#endif
44

45 46 47 48 49
#if CUDA_VERSION >= 10020
#include "paddle/fluid/memory/allocation/cuda_virtual_mem_allocator.h"
#include "paddle/fluid/memory/allocation/virtual_memory_auto_growth_best_fit_allocator.h"
#include "paddle/fluid/platform/dynload/cuda_driver.h"
#endif
50
#endif
51

52
#ifdef PADDLE_WITH_XPU
53 54
#include "paddle/fluid/memory/allocation/stream_safe_xpu_allocator.h"
#include "paddle/fluid/memory/allocation/xpu_allocator.h"
55
#include "paddle/fluid/platform/device/xpu/xpu_info.h"
56
#include "paddle/phi/backends/xpu/xpu_context.h"
57
#endif
58

J
jianghaicheng 已提交
59 60 61 62
#ifdef PADDLE_WITH_IPU
#include "paddle/fluid/platform/device/ipu/ipu_info.h"
#endif

63
#ifdef PADDLE_WITH_CUSTOM_DEVICE
64
#include "paddle/fluid/memory/allocation/stream_safe_custom_device_allocator.h"
65
#endif
66

67
#include "paddle/fluid/platform/flags.h"
68

Z
Zeng Jinle 已提交
69
PADDLE_DEFINE_EXPORTED_int64(
70 71
    gpu_allocator_retry_time,
    10000,
S
sneaxiy 已提交
72 73 74
    "The retry time (milliseconds) when allocator fails "
    "to allocate memory. No retry if this value is not greater than 0");

Z
Zeng Jinle 已提交
75
PADDLE_DEFINE_EXPORTED_bool(
76 77
    use_system_allocator,
    false,
Z
Zeng Jinle 已提交
78 79
    "Whether to use system allocator to allocate CPU and GPU memory. "
    "Only used for unittests.");
80

81 82
PADDLE_DEFINE_EXPORTED_bool(use_virtual_memory_auto_growth,
                            false,
83 84
                            "Use VirtualMemoryAutoGrowthBestFitAllocator.");

85 86 87
// NOTE(Ruibiao): This FLAGS is just to be compatibled with
// the old single-stream CUDA allocator. It will be removed
// after StreamSafeCudaAllocator has been fully tested.
88 89
PADDLE_DEFINE_EXPORTED_bool(use_stream_safe_cuda_allocator,
                            true,
90 91
                            "Enable StreamSafeCUDAAllocator");

92 93
PADDLE_DEFINE_EXPORTED_bool(use_cuda_managed_memory,
                            false,
94 95 96 97
                            "Whether to use CUDAManagedAllocator to allocate "
                            "managed memory, only available for auto_growth "
                            "strategy");

98 99
PHI_DECLARE_string(allocator_strategy);
PHI_DECLARE_uint64(auto_growth_chunk_size_in_mb);
100

101 102 103 104
namespace paddle {
namespace memory {
namespace allocation {

105 106 107 108 109 110 111 112
#ifdef PADDLE_WITH_CUDA
class CUDAGraphAllocator
    : public Allocator,
      public std::enable_shared_from_this<CUDAGraphAllocator> {
 private:
  class PrivateAllocation : public Allocation {
   public:
    PrivateAllocation(CUDAGraphAllocator* allocator,
113
                      DecoratedAllocationPtr underlying_allocation)
114 115 116 117
        : Allocation(underlying_allocation->ptr(),
                     underlying_allocation->base_ptr(),
                     underlying_allocation->size(),
                     underlying_allocation->place()),
118 119 120 121 122
          allocator_(allocator->shared_from_this()),
          underlying_allocation_(std::move(underlying_allocation)) {}

   private:
    std::shared_ptr<Allocator> allocator_;
123
    DecoratedAllocationPtr underlying_allocation_;
124 125 126 127 128 129
  };

  explicit CUDAGraphAllocator(const std::shared_ptr<Allocator>& allocator)
      : underlying_allocator_(allocator) {}

 public:
130
  ~CUDAGraphAllocator() override {}
131

132 133 134 135 136 137
  static std::shared_ptr<Allocator> Create(
      const std::shared_ptr<Allocator>& allocator) {
    return std::shared_ptr<Allocator>(new CUDAGraphAllocator(allocator));
  }

 protected:
138
  phi::Allocation* AllocateImpl(size_t size) override {
139
    VLOG(10) << "Allocate " << size << " for CUDA Graph";
140 141 142
    return new PrivateAllocation(this,
                                 static_unique_ptr_cast<Allocation>(
                                     underlying_allocator_->Allocate(size)));
143 144
  }

145
  void FreeImpl(phi::Allocation* allocation) override {
146 147 148 149 150 151 152 153 154
    VLOG(10) << "delete for CUDA Graph";
    delete allocation;
  }

 private:
  std::shared_ptr<Allocator> underlying_allocator_;
};
#endif

155 156
static bool IsCUDAGraphCapturing() {
#ifdef PADDLE_WITH_CUDA
157
  return UNLIKELY(phi::backends::gpu::CUDAGraph::IsThisThreadCapturing());
158 159 160 161 162
#else
  return false;
#endif
}

Y
Yu Yang 已提交
163 164
class AllocatorFacadePrivate {
 public:
165 166
  using AllocatorMap = std::map<platform::Place, std::shared_ptr<Allocator>>;

167 168 169 170 171
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  using CUDAAllocatorMap =
      std::map<platform::CUDAPlace,
               std::map<gpuStream_t, std::shared_ptr<Allocator>>>;
#endif
172 173 174 175 176
#ifdef PADDLE_WITH_XPU
  using XPUAllocatorMap =
      std::map<platform::XPUPlace,
               std::map<XPUStream, std::shared_ptr<Allocator>>>;
#endif
177 178 179 180 181
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  using CustomDeviceAllocatorMap =
      std::map<platform::CustomPlace,
               std::map<phi::stream::stream_t, std::shared_ptr<Allocator>>>;
#endif
182

183 184
  explicit AllocatorFacadePrivate(bool allow_free_idle_chunk = true) {
    strategy_ = GetAllocatorStrategy();
185 186
    is_stream_safe_cuda_allocator_used_ = false;

187
    switch (strategy_) {
188 189
      case AllocatorStrategy::kNaiveBestFit: {
        InitNaiveBestFitCPUAllocator();
J
jianghaicheng 已提交
190 191 192 193 194
#ifdef PADDLE_WITH_IPU
        for (int dev_id = 0; dev_id < platform::GetIPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitIPUAllocator(platform::IPUPlace(dev_id));
        }
#endif
195
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
196
        for (int dev_id = 0; dev_id < platform::GetGPUDeviceCount(); ++dev_id) {
197 198 199
          InitNaiveBestFitCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
200
#endif
201 202 203 204 205
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
206
#ifdef PADDLE_WITH_CUSTOM_DEVICE
207
        auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
208 209
        for (const auto& dev_type : device_types) {
          for (size_t dev_id = 0;
210
               dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
211 212 213 214 215
               ++dev_id) {
            InitNaiveBestFitCustomDeviceAllocator(
                platform::CustomPlace(dev_type, dev_id));
          }
        }
216
#endif
Z
Zeng Jinle 已提交
217 218
        break;
      }
219 220 221

      case AllocatorStrategy::kAutoGrowth: {
        InitNaiveBestFitCPUAllocator();
222 223
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
        allow_free_idle_chunk_ = allow_free_idle_chunk;
224 225 226 227 228
        for (int dev_id = 0; dev_id < platform::GetGPUDeviceCount(); ++dev_id) {
          InitAutoGrowthCUDAAllocator(platform::CUDAPlace(dev_id),
                                      allow_free_idle_chunk_);
        }

229 230 231 232 233 234 235 236
        // Note(Ruibiao): For GPU multi-stream case without CUDA graph
        // capturing, the 'allocators_' map(place -> Allocator) hold the
        // StreamSafeCUDAAllocator releate to defaultstream (i.e., the stream
        // directly got from DeviceContex), while the 'cuda_allocators_' map
        // (place -> map(stream -> Allocator)) hold the StreamSafeCUDAAllocator
        // releate to non-default stream (i.e., the stream users pass in). The
        // default stream Allocator is built in the structure of
        // AllocatorFacadePrivate, while the non-default stream is build in a
237
        // manner in GetAllocator function with 'create_if_not_found = true'.
238 239 240 241
        // We make special treatment for the default stream for performance
        // reasons. Since most Alloc calls are for default stream in
        // application, treating it separately can avoid lots of overhead of
        // acquiring default stream and applying read-write lock.
242
        if (FLAGS_use_stream_safe_cuda_allocator) {
243 244 245 246
          if (LIKELY(!IsCUDAGraphCapturing())) {
            WrapStreamSafeCUDAAllocatorForDefault();
          }
          is_stream_safe_cuda_allocator_used_ = true;
247
        }
248

249 250
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
251
#ifdef PADDLE_WITH_XPU
252
        allow_free_idle_chunk_ = allow_free_idle_chunk;
253
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
254 255 256 257 258 259
          InitAutoGrowthXPUAllocator(platform::XPUPlace(dev_id),
                                     allow_free_idle_chunk_);
        }
        if (FLAGS_use_stream_safe_cuda_allocator) {
          WrapStreamSafeXPUAllocatorForDefault();
          is_stream_safe_cuda_allocator_used_ = true;
260
        }
261

J
jianghaicheng 已提交
262 263 264 265 266
#endif
#ifdef PADDLE_WITH_IPU
        for (int dev_id = 0; dev_id < platform::GetIPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitIPUAllocator(platform::IPUPlace(dev_id));
        }
F
fwenguang 已提交
267
#endif
268
#ifdef PADDLE_WITH_CUSTOM_DEVICE
269
        auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
270 271
        for (const auto& dev_type : device_types) {
          for (size_t dev_id = 0;
272
               dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
273 274 275 276 277
               ++dev_id) {
            InitAutoGrowthCustomDeviceAllocator(
                platform::CustomPlace(dev_type, dev_id), allow_free_idle_chunk);
          }
        }
278
#endif
Z
Zeng Jinle 已提交
279 280
        break;
      }
281

282 283
      case AllocatorStrategy::kThreadLocal: {
        InitNaiveBestFitCPUAllocator();
284 285 286 287 288
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
J
jianghaicheng 已提交
289 290 291 292 293
#ifdef PADDLE_WITH_IPU
        for (int dev_id = 0; dev_id < platform::GetIPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitIPUAllocator(platform::IPUPlace(dev_id));
        }
#endif
294
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
295
        for (int dev_id = 0; dev_id < platform::GetGPUDeviceCount(); ++dev_id) {
296 297 298 299 300 301 302
          InitThreadLocalCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
        break;
      }

Z
Zeng Jinle 已提交
303
      default: {
304
        PADDLE_THROW(platform::errors::InvalidArgument(
305
            "Unsupported allocator strategy: %d", static_cast<int>(strategy_)));
Z
Zeng Jinle 已提交
306
      }
Y
Yu Yang 已提交
307
    }
Z
Zeng Jinle 已提交
308
    InitZeroSizeAllocators();
309
    InitSystemAllocators();
310 311 312 313 314

    if (FLAGS_gpu_allocator_retry_time > 0) {
      WrapCUDARetryAllocator(FLAGS_gpu_allocator_retry_time);
    }

315 316
    WrapStatAllocator();

317
    CheckAllocThreadSafe();
318 319

#ifdef PADDLE_WITH_CUDA
320 321 322
    // No need to wrap CUDAGraphAllocator for StreamSafeCUDAAllocator
    if (!is_stream_safe_cuda_allocator_used_ &&
        UNLIKELY(IsCUDAGraphCapturing())) {
323 324 325
      WrapCUDAGraphAllocator();
    }
#endif
Z
Zeng Jinle 已提交
326 327 328 329
  }

  inline const std::shared_ptr<Allocator>& GetAllocator(
      const platform::Place& place, size_t size) {
330
    VLOG(6) << "GetAllocator"
L
Leo Chen 已提交
331
            << " " << place << " " << size;
332 333
    const auto& allocators =
        (size > 0 ? (UNLIKELY(FLAGS_use_system_allocator) ? system_allocators_
334
                                                          : GetAllocatorMap())
335
                  : zero_size_allocators_);
Z
Zeng Jinle 已提交
336
    auto iter = allocators.find(place);
337 338
    PADDLE_ENFORCE_NE(iter,
                      allocators.end(),
339 340
                      platform::errors::NotFound(
                          "No allocator found for the place, %s", place));
Z
Zeng Jinle 已提交
341
    return iter->second;
342 343
  }

344
  void* GetBasePtr(const std::shared_ptr<phi::Allocation>& allocation) {
345 346 347
    return static_cast<Allocation*>(allocation.get())->base_ptr();
  }

348 349 350 351 352
  bool IsStreamSafeCUDAAllocatorUsed() {
    return is_stream_safe_cuda_allocator_used_ &&
           LIKELY(FLAGS_use_system_allocator == false);
  }

353
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
354
  bool HasCUDAAllocator(const platform::CUDAPlace& place, gpuStream_t stream) {
355 356 357 358 359 360 361 362 363
    auto it = cuda_allocators_.find(place);
    if (it == cuda_allocators_.end()) {
      return false;
    }
    const std::map<gpuStream_t, std::shared_ptr<Allocator>>& allocator_map =
        it->second;
    return allocator_map.find(stream) != allocator_map.end();
  }

364
  const std::shared_ptr<Allocator>& GetAllocator(
365 366
      const platform::CUDAPlace& place,
      gpuStream_t stream,
367
      bool create_if_not_found = false) {
368 369 370 371 372
    if (LIKELY(!IsCUDAGraphCapturing())) {
      if (stream == GetDefaultStream(place)) {
        VLOG(7) << "Get Allocator by passing in a default stream";
        return GetAllocator(place, /* A non-zero num to choose allocator_ */ 1);
      }
373 374 375
    }

    /* shared_lock_guard */ {
376 377 378
      std::shared_lock<std::shared_timed_mutex> lock_guard(
          cuda_allocator_mutex_);
      if (LIKELY(HasCUDAAllocator(place, stream))) {
379 380
        return cuda_allocators_[place][stream];
      } else {
381 382
        PADDLE_ENFORCE_NE(create_if_not_found,
                          false,
383 384 385
                          platform::errors::NotFound(
                              "No allocator found for stream %s in place %s "
                              "with create_if_not_found = false",
386 387
                              stream,
                              place));
388 389 390
      }
    }

391
    /* unique_lock_guard */ {
392 393 394 395
      std::unique_lock<std::shared_timed_mutex> lock_guard(
          cuda_allocator_mutex_);
      InitStreamSafeCUDAAllocator(place, stream);
      return cuda_allocators_[place][stream];
396
    }
397 398
  }

399 400 401 402
  const std::shared_ptr<StreamSafeCUDAAllocator>
  GetDefaultStreamSafeCUDAAllocator(const platform::CUDAPlace& place) const {
    const auto iter = default_stream_safe_cuda_allocators_.find(place);
    PADDLE_ENFORCE_NE(
403 404
        iter,
        default_stream_safe_cuda_allocators_.end(),
405 406 407 408 409
        platform::errors::NotFound(
            "No StreamSafeCUDAAllocator found for the place, %s", place));
    return iter->second;
  }

410
  gpuStream_t GetDefaultStream(const platform::CUDAPlace& place) const {
411 412 413 414 415
    const std::shared_ptr<StreamSafeCUDAAllocator>& allocator =
        GetDefaultStreamSafeCUDAAllocator(place);
    return allocator->GetDefaultStream();
  }

416
  void SetDefaultStream(const platform::CUDAPlace& place, gpuStream_t stream) {
417 418
    const std::shared_ptr<StreamSafeCUDAAllocator>& allocator =
        GetDefaultStreamSafeCUDAAllocator(place);
419

420
    PADDLE_ENFORCE_EQ(
421 422
        allocator->GetDefaultStream(),
        nullptr,
423 424 425
        platform::errors::Unavailable(
            "The default stream for StreamSafeCUDAAllocator(%p) in %s has been "
            "set to %p, not allow to change it to %p.",
426 427 428 429
            allocator.get(),
            place,
            allocator->GetDefaultStream(),
            stream));
430

431 432 433 434 435 436
    allocator->SetDefaultStream(stream);
    VLOG(8) << "Set default stream to " << stream
            << " for StreamSafeCUDAAllocator(" << allocator.get() << ") in "
            << place;
  }

437
  void RecordStream(std::shared_ptr<phi::Allocation> allocation,
438
                    gpuStream_t stream) {
439 440 441 442 443 444
    std::shared_ptr<StreamSafeCUDAAllocation> stream_safe_cuda_allocation =
        std::dynamic_pointer_cast<StreamSafeCUDAAllocation>(allocation);
    if (stream_safe_cuda_allocation != nullptr) {
      stream_safe_cuda_allocation->RecordStream(stream);
    } else {
      VLOG(6) << "RecordStream for a non-StreamSafeCUDAAllocation";
445
    }
446 447
  }

448
  gpuStream_t GetStream(
449
      const std::shared_ptr<phi::Allocation>& allocation) const {
450 451 452 453 454 455 456 457 458 459 460
    const std::shared_ptr<StreamSafeCUDAAllocation>
        stream_safe_cuda_allocation =
            std::dynamic_pointer_cast<StreamSafeCUDAAllocation>(allocation);
    if (stream_safe_cuda_allocation != nullptr) {
      return stream_safe_cuda_allocation->GetOwningStream();
    }

    VLOG(6) << "GetStream for a non-StreamSafeCUDAAllocation";
    return static_cast<phi::GPUContext*>(
               platform::DeviceContextPool::Instance().Get(allocation->place()))
        ->stream();
461 462 463
  }
#endif

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
#ifdef PADDLE_WITH_XPU
  bool HasXPUAllocator(const platform::XPUPlace& place, XPUStream stream) {
    auto it = xpu_allocators_.find(place);
    if (it == xpu_allocators_.end()) {
      return false;
    }
    const std::map<XPUStream, std::shared_ptr<Allocator>>& allocator_map =
        it->second;
    return allocator_map.find(stream) != allocator_map.end();
  }

  const std::shared_ptr<Allocator>& GetAllocator(
      const platform::XPUPlace& place,
      XPUStream stream,
      bool create_if_not_found = false) {
    if (stream == GetDefaultStream(place)) {
      VLOG(7) << "Get Allocator by passing in a default stream";
      return GetAllocator(place, /* A non-zero num to choose allocator_ */ 1);
    }

    /* shared_lock_guard */ {
      std::shared_lock<std::shared_timed_mutex> lock_guard(
          xpu_allocator_mutex_);
      if (LIKELY(HasXPUAllocator(place, stream))) {
        return xpu_allocators_[place][stream];
      } else {
        PADDLE_ENFORCE_NE(create_if_not_found,
                          false,
                          platform::errors::NotFound(
                              "No allocator found for stream %s in place %s "
                              "with create_if_not_found = false",
                              stream,
                              place));
      }
    }

    /* unique_lock_guard */ {
      std::unique_lock<std::shared_timed_mutex> lock_guard(
          xpu_allocator_mutex_);
      InitStreamSafeXPUAllocator(place, stream);
      return xpu_allocators_[place][stream];
    }
  }

  const std::shared_ptr<StreamSafeXPUAllocator>
  GetDefaultStreamSafeXPUAllocator(const platform::XPUPlace& place) const {
    const auto iter = default_stream_safe_xpu_allocators_.find(place);
    PADDLE_ENFORCE_NE(
        iter,
        default_stream_safe_xpu_allocators_.end(),
        platform::errors::NotFound(
            "No StreamSafeXPUAllocator found for the place, %s", place));
    return iter->second;
  }

  XPUStream GetDefaultStream(const platform::XPUPlace& place) const {
    const std::shared_ptr<StreamSafeXPUAllocator>& allocator =
        GetDefaultStreamSafeXPUAllocator(place);
    return allocator->GetDefaultStream();
  }

  void SetDefaultStream(const platform::XPUPlace& place, XPUStream stream) {
    const std::shared_ptr<StreamSafeXPUAllocator>& allocator =
        GetDefaultStreamSafeXPUAllocator(place);

    PADDLE_ENFORCE_EQ(
        allocator->GetDefaultStream(),
        nullptr,
        platform::errors::Unavailable(
            "The default stream for StreamSafeXPUAllocator(%p) in %s has been "
            "set to %p, not allow to change it to %p.",
            allocator.get(),
            place,
            allocator->GetDefaultStream(),
            stream));

    allocator->SetDefaultStream(stream);
    VLOG(8) << "Set default stream to " << stream
            << " for StreamSafeXPUAllocator(" << allocator.get() << ") in "
            << place;
  }

  void RecordStream(std::shared_ptr<phi::Allocation> allocation,
                    XPUStream stream) {
    std::shared_ptr<StreamSafeXPUAllocation> stream_safe_xpu_allocation =
        std::dynamic_pointer_cast<StreamSafeXPUAllocation>(allocation);
    if (stream_safe_xpu_allocation != nullptr) {
      stream_safe_xpu_allocation->RecordStream(stream);
    } else {
      VLOG(6) << "RecordStream for a non-StreamSafeXPUAllocation";
    }
  }

  XPUStream GetStream(
      const std::shared_ptr<phi::Allocation>& allocation) const {
    const std::shared_ptr<StreamSafeXPUAllocation> stream_safe_xpu_allocation =
        std::dynamic_pointer_cast<StreamSafeXPUAllocation>(allocation);
    if (stream_safe_xpu_allocation != nullptr) {
      return stream_safe_xpu_allocation->GetOwningStream();
    }

    VLOG(6) << "GetStream for a non-StreamSafeXPUAllocation";
    return static_cast<phi::XPUContext*>(
               platform::DeviceContextPool::Instance().Get(allocation->place()))
        ->stream();
  }
#endif

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  bool HasCustomDevice(const platform::CustomPlace& place,
                       phi::stream::stream_t stream) {
    auto it = custom_device_allocators_.find(place);
    if (it == custom_device_allocators_.end()) {
      return false;
    }
    auto& allocator_map = it->second;
    return allocator_map.find(stream) != allocator_map.end();
  }

  const std::shared_ptr<Allocator>& GetAllocator(
      const platform::CustomPlace& place,
      phi::stream::stream_t stream,
      bool create_if_not_found = false) {
    /* shared_lock_guard */ {
      std::shared_lock<std::shared_timed_mutex> lock_guard(
          custom_device_allocator_mutex_);
      if (LIKELY(HasCustomDevice(place, stream))) {
        return custom_device_allocators_[place][stream];
      } else {
        PADDLE_ENFORCE_NE(create_if_not_found,
                          false,
                          platform::errors::NotFound(
                              "No allocator found for stream %s in place %s "
                              "with create_if_not_found = false",
                              stream,
                              place));
      }
    }

    /* unique_lock_guard */ {
      std::unique_lock<std::shared_timed_mutex> lock_guard(
          custom_device_allocator_mutex_);
      InitStreamSafeCustomDeviceAllocator(place, stream);
      return custom_device_allocators_[place][stream];
    }
  }
#endif

612 613 614 615 616 617 618
 private:
  class ZeroSizeAllocator : public Allocator {
   public:
    explicit ZeroSizeAllocator(platform::Place place) : place_(place) {}
    bool IsAllocThreadSafe() const override { return true; }

   protected:
619
    phi::Allocation* AllocateImpl(size_t size) override {
620 621
      return new Allocation(nullptr, 0, place_);
    }
622
    void FreeImpl(phi::Allocation* allocation) override { delete allocation; }
623 624 625 626 627

   private:
    platform::Place place_;
  };

628
  const AllocatorMap& GetAllocatorMap() { return allocators_; }
629

630
  void InitNaiveBestFitCPUAllocator() {
631 632 633 634 635 636 637
#if defined(__APPLE__) && defined(__arm64__)
    // NOTE(wuweilong): It is more efficient to use CPUAllocator directly,
    // but it wll cause some problem in Mac OS m1 chip, so we use
    // NaiveBestFitAllocator instead.
    allocators_[platform::CPUPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CPUPlace());
#else
638
    allocators_[platform::CPUPlace()] = std::make_shared<CPUAllocator>();
639
#endif
Y
Yu Yang 已提交
640 641
  }

642
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
643 644 645
  void InitNaiveBestFitCUDAPinnedAllocator() {
    allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CUDAPinnedPlace());
646 647
  }

648 649 650 651 652 653 654 655
  void InitNaiveBestFitCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }

  // Create a new CUDAAllocator or CUDAManagedAllocator for the given device
  std::shared_ptr<Allocator> CreateCUDAAllocator(platform::CUDAPlace p) {
    if (FLAGS_use_cuda_managed_memory) {
      PADDLE_ENFORCE_EQ(
656 657
          strategy_,
          AllocatorStrategy::kAutoGrowth,
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
          platform::errors::InvalidArgument(
              "CUDA managed memory is only implemented for auto_growth "
              "strategy, not support %s strategy.\n"
              "Please use auto_growth strategy by command `export "
              "FLAGS_allocator_strategy=\"auto_growth\"`, or disable managed "
              "memory by command `export FLAGS_use_cuda_managed_memory=false`",
              FLAGS_allocator_strategy));

      if (!platform::IsGPUManagedMemorySupported(p.device)) {
        PADDLE_THROW(platform::errors::Unavailable(
            "Failed to create CUDAManagedAllocator on GPU %d.\n\n"
            "You have enabled CUDA managed memory, but the gpu device does not "
            "support allocating managed memory.\n"
            "If you don't actually need to use managed memory, please disable "
            "it with command `export FLAGS_use_cuda_managed_memory=false`.\n"
673 674
            "Or you must use the gpu device that supports managed memory.",
            p.device));
675 676 677 678 679 680
      }
      return std::make_shared<CUDAManagedAllocator>(p);
    }
    return std::make_shared<CUDAAllocator>(p);
  }

681 682
  void InitStreamSafeCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
    PADDLE_ENFORCE_EQ(
683 684
        strategy_,
        AllocatorStrategy::kAutoGrowth,
685 686 687 688
        platform::errors::Unimplemented(
            "Only support auto-growth strategey for StreamSafeCUDAAllocator, "
            "the allocator strategy %d is unsupported for multi-stream",
            static_cast<int>(strategy_)));
689 690 691
    if (LIKELY(!HasCUDAAllocator(p, stream))) {
      VLOG(8) << "Init CUDA allocator for stream " << stream << " in place "
              << p;
692 693 694
      InitAutoGrowthCUDAAllocator(p, stream);
      WrapStreamSafeCUDAAllocator(p, stream);
      WrapCUDARetryAllocator(p, stream, FLAGS_gpu_allocator_retry_time);
695
      WrapStatAllocator(p, stream);
696 697 698 699
    }
  }

  void InitAutoGrowthCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
700 701 702
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 20;
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;
703
#if defined(PADDLE_WITH_HIP)
704
    auto cuda_allocator = CreateCUDAAllocator(p);
705
    cuda_allocators_[p][stream] = std::make_shared<AutoGrowthBestFitAllocator>(
706 707 708 709
        cuda_allocator,
        platform::GpuMinChunkSize(),
        chunk_size,
        allow_free_idle_chunk_);
710 711 712 713 714 715 716
#endif

#if defined(PADDLE_WITH_CUDA)
#if CUDA_VERSION >= 10020
    CUdevice device;
    int val;
    try {
717
      PADDLE_ENFORCE_GPU_SUCCESS(
718 719
          paddle::platform::dynload::cuDeviceGet(&device, p.GetDeviceId()));

720
      PADDLE_ENFORCE_GPU_SUCCESS(
721
          paddle::platform::dynload::cuDeviceGetAttribute(
722 723
              &val,
              CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED,
724 725 726 727 728 729 730 731 732 733 734
              device));
    } catch (...) {
      val = 0;
    }

    if (val > 0 && FLAGS_use_virtual_memory_auto_growth) {
      auto cuda_allocator = std::make_shared<CUDAVirtualMemAllocator>(p);
      cuda_allocators_[p][stream] =
          std::make_shared<VirtualMemoryAutoGrowthBestFitAllocator>(
              cuda_allocator, platform::GpuMinChunkSize(), p);
    } else {
735
      auto cuda_allocator = CreateCUDAAllocator(p);
736 737
      cuda_allocators_[p][stream] =
          std::make_shared<AutoGrowthBestFitAllocator>(
738 739
              cuda_allocator,
              platform::GpuMinChunkSize(),
740
              /*chunk_size=*/chunk_size,
741 742 743
              allow_free_idle_chunk_);
    }
#else
744
    auto cuda_allocator = CreateCUDAAllocator(p);
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    auto alignment = platform::GpuMinChunkSize();
    bool need_addr_align = true;
    // NOTE: sometimes, since cuda runtime can not be forked, calling any cuda
    // API in that case may got cuda error(3), i.e.,
    // cudaErrorInitializationError. And, the CUDAAllocator is only initialized
    // but not really used.
    // Here, the try-catch block is added to handle the case that
    // GetDeviceProperties() may failed in the multiple process(for example, in
    // dataloader with num_worker > 0)
    try {
      const auto& prop = platform::GetDeviceProperties(p.GetDeviceId());
      need_addr_align = prop.textureAlignment < alignment;
      VLOG(4) << "GetDeviceProperties ok, textureAlignment: "
              << prop.textureAlignment
              << ", set need_addr_align=" << need_addr_align;
    } catch (...) {
      need_addr_align = true;
      VLOG(4) << "GetDeviceProperties failed, set need_addr_align=true";
    }
    // The address returned is aligned already,
    // ref:
    // https://stackoverflow.com/questions/14082964/cuda-alignment-256bytes-seriously/14083295#14083295
    std::shared_ptr<Allocator> underlying_allocator{nullptr};
    if (need_addr_align) {
      VLOG(10) << "use AlignedAllocator with alignment: " << alignment;
      underlying_allocator =
          std::make_shared<AlignedAllocator>(underlying_allocator, alignment);
    } else {
      VLOG(10) << "not use AlignedAllocator with alignment: " << alignment;
      underlying_allocator = cuda_allocator;
    }

    cuda_allocators_[p][stream] = std::make_shared<AutoGrowthBestFitAllocator>(
778
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk_);
779 780
#endif
#endif
781 782
  }

783
  // NOTE(Ruibiao): Old single-stream version, will be removed later
784 785
  void InitAutoGrowthCUDAAllocator(platform::CUDAPlace p,
                                   bool allow_free_idle_chunk) {
786 787 788
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 20;
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;
789
#if defined(PADDLE_WITH_HIP)
790
    auto cuda_allocator = CreateCUDAAllocator(p);
791
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
792 793
        cuda_allocator,
        platform::GpuMinChunkSize(),
794
        /*chunk_size=*/chunk_size,
795
        allow_free_idle_chunk);
796 797 798 799 800 801 802
#endif

#if defined(PADDLE_WITH_CUDA)
#if CUDA_VERSION >= 10020
    CUdevice device;
    int val;
    try {
803
      PADDLE_ENFORCE_GPU_SUCCESS(
804 805
          paddle::platform::dynload::cuDeviceGet(&device, p.GetDeviceId()));

806
      PADDLE_ENFORCE_GPU_SUCCESS(
807
          paddle::platform::dynload::cuDeviceGetAttribute(
808 809
              &val,
              CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED,
810 811 812 813 814 815 816 817 818 819 820
              device));
    } catch (...) {
      val = 0;
    }

    if (val > 0 && FLAGS_use_virtual_memory_auto_growth) {
      auto cuda_allocator = std::make_shared<CUDAVirtualMemAllocator>(p);
      allocators_[p] =
          std::make_shared<VirtualMemoryAutoGrowthBestFitAllocator>(
              cuda_allocator, platform::GpuMinChunkSize(), p);
    } else {
821
      auto cuda_allocator = CreateCUDAAllocator(p);
822
      allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
823 824
          cuda_allocator,
          platform::GpuMinChunkSize(),
825
          /*chunk_size=*/chunk_size,
826
          allow_free_idle_chunk);
827 828 829
    }

#else
830
    auto cuda_allocator = CreateCUDAAllocator(p);
L
Leo Chen 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    auto alignment = platform::GpuMinChunkSize();
    bool need_addr_align = true;
    // NOTE: sometimes, since cuda runtime can not be forked, calling any cuda
    // API in that case may got cuda error(3), i.e.,
    // cudaErrorInitializationError. And, the CUDAAllocator is only initialized
    // but not really used.
    // Here, the try-catch block is added to handle the case that
    // GetDeviceProperties() may failed in the multiple process(for example, in
    // dataloader with num_worker > 0)
    try {
      const auto& prop = platform::GetDeviceProperties(p.GetDeviceId());
      need_addr_align = prop.textureAlignment < alignment;
      VLOG(4) << "GetDeviceProperties ok, textureAlignment: "
              << prop.textureAlignment
              << ", set need_addr_align=" << need_addr_align;
    } catch (...) {
      need_addr_align = true;
      VLOG(4) << "GetDeviceProperties failed, set need_addr_align=true";
    }
    // The address returned is aligned already,
    // ref:
    // https://stackoverflow.com/questions/14082964/cuda-alignment-256bytes-seriously/14083295#14083295
    std::shared_ptr<Allocator> underlying_allocator{nullptr};
    if (need_addr_align) {
      VLOG(10) << "use AlignedAllocator with alignment: " << alignment;
      underlying_allocator =
          std::make_shared<AlignedAllocator>(underlying_allocator, alignment);
    } else {
      VLOG(10) << "not use AlignedAllocator with alignment: " << alignment;
      underlying_allocator = cuda_allocator;
    }
862
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
863
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk);
864 865
#endif
#endif
S
sneaxiy 已提交
866
  }
867 868 869 870 871 872

  void InitThreadLocalCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<ThreadLocalCUDAAllocator>(p);
  }

  void WrapStreamSafeCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
873 874
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
    allocator = std::make_shared<StreamSafeCUDAAllocator>(
875 876 877
        allocator,
        p,
        stream,
878
        /* in_cuda_graph_capturing = */ !allow_free_idle_chunk_);
879 880
  }

881 882 883 884 885 886
  void WrapStreamSafeCUDAAllocatorForDefault() {
    for (auto& pair : allocators_) {
      auto& place = pair.first;
      if (platform::is_gpu_place(place)) {
        std::shared_ptr<StreamSafeCUDAAllocator>&& allocator =
            std::make_shared<StreamSafeCUDAAllocator>(
887 888
                pair.second,
                place,
889
                /* default_stream = */ nullptr,
890 891 892 893 894 895 896 897 898 899 900 901 902
                /* in_cuda_graph_capturing = */ !allow_free_idle_chunk_);
        pair.second = allocator;

        // NOTE(Ruibiao): A tricky implement to give StreamSafeCUDAAllocator an
        // ability to interact with the outside world, i.e., change default
        // stream from outside
        default_stream_safe_cuda_allocators_[place] = allocator;
        VLOG(8) << "WrapStreamSafeCUDAAllocator for " << place
                << ", allocator address = " << pair.second.get();
      }
    }
  }

903 904
  void WrapCUDARetryAllocator(platform::CUDAPlace p,
                              gpuStream_t stream,
905 906
                              size_t retry_time) {
    PADDLE_ENFORCE_GT(
907 908
        retry_time,
        0,
909 910
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
911
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
912 913 914
    allocator = std::make_shared<RetryAllocator>(allocator, retry_time);
  }

915 916 917 918 919
  void WrapStatAllocator(platform::CUDAPlace p, gpuStream_t stream) {
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
    allocator = std::make_shared<StatAllocator>(allocator);
  }

920 921 922 923 924 925 926 927 928
#ifdef PADDLE_WITH_CUDA
  void WrapCUDAGraphAllocator() {
    for (auto& item : allocators_) {
      auto& allocator = item.second;
      allocator = CUDAGraphAllocator::Create(allocator);
    }
  }
#endif

929 930 931
  static void CheckCUDAAllocThreadSafe(const CUDAAllocatorMap& allocators) {
    for (auto& place_pair : allocators) {
      for (auto& stream_pair : place_pair.second) {
932 933
        PADDLE_ENFORCE_EQ(stream_pair.second->IsAllocThreadSafe(),
                          true,
934 935 936 937 938
                          platform::errors::InvalidArgument(
                              "Public allocators must be thread safe"));
      }
    }
  }
939
#endif
S
sneaxiy 已提交
940

941 942 943 944
#ifdef PADDLE_WITH_XPU
  void InitNaiveBestFitXPUAllocator(platform::XPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

  // Create a new XPUAllocator or XPUManagedAllocator for the given device
  std::shared_ptr<Allocator> CreateXPUAllocator(platform::XPUPlace p) {
    return std::make_shared<XPUAllocator>(p);
  }

  void InitStreamSafeXPUAllocator(platform::XPUPlace p, XPUStream stream) {
    PADDLE_ENFORCE_EQ(
        strategy_,
        AllocatorStrategy::kAutoGrowth,
        platform::errors::Unimplemented(
            "Only support auto-growth strategey for StreamSafeXPUAllocator, "
            "the allocator strategy %d is unsupported for multi-stream",
            static_cast<int>(strategy_)));
    if (LIKELY(!HasXPUAllocator(p, stream))) {
      VLOG(8) << "Init XPU allocator for stream " << stream << " in place "
              << p;
      InitAutoGrowthXPUAllocator(p, stream);

      WrapStreamSafeXPUAllocator(p, stream);

      WrapXPURetryAllocator(p, stream, FLAGS_gpu_allocator_retry_time);
      WrapStatAllocator(p, stream);
    }
  }

  void InitAutoGrowthXPUAllocator(platform::XPUPlace p, XPUStream stream) {
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 6;
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;
    auto xpu_allocator = CreateXPUAllocator(p);
    auto alignment = platform::XPUMinChunkSize();

    std::shared_ptr<Allocator> underlying_allocator{nullptr};

    VLOG(10) << "not use AlignedAllocator with alignment: " << alignment;
    underlying_allocator = xpu_allocator;

    xpu_allocators_[p][stream] = std::make_shared<AutoGrowthBestFitAllocator>(
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk_);
  }

  void InitAutoGrowthXPUAllocator(platform::XPUPlace p,
                                  bool allow_free_idle_chunk) {
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 6;
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;
    auto xpu_allocator = CreateXPUAllocator(p);
    auto alignment = platform::XPUMinChunkSize();

    std::shared_ptr<Allocator> underlying_allocator{nullptr};

    VLOG(10) << "not use AlignedAllocator with alignment: " << alignment;
    underlying_allocator = xpu_allocator;

    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk);
  }

  void WrapStreamSafeXPUAllocator(platform::XPUPlace p, XPUStream stream) {
    std::shared_ptr<Allocator>& allocator = xpu_allocators_[p][stream];
    allocator = std::make_shared<StreamSafeXPUAllocator>(allocator, p, stream);
  }

  void WrapStreamSafeXPUAllocatorForDefault() {
    for (auto& pair : allocators_) {
      auto& place = pair.first;
      if (platform::is_xpu_place(place)) {
        std::shared_ptr<StreamSafeXPUAllocator>&& allocator =
            std::make_shared<StreamSafeXPUAllocator>(
                pair.second,
                place,
                /* default_stream = */ nullptr);
        pair.second = allocator;
        default_stream_safe_xpu_allocators_[place] = allocator;
        VLOG(8) << "WrapStreamSafeXPUAllocator for " << place
                << ", allocator address = " << pair.second.get();
      }
    }
  }

  void WrapXPURetryAllocator(platform::XPUPlace p,
                             XPUStream stream,
                             size_t retry_time) {
    PADDLE_ENFORCE_GT(
        retry_time,
        0,
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
    std::shared_ptr<Allocator>& allocator = xpu_allocators_[p][stream];
    allocator = std::make_shared<RetryAllocator>(allocator, retry_time);
  }

  void WrapStatAllocator(platform::XPUPlace p, XPUStream stream) {
    std::shared_ptr<Allocator>& allocator = xpu_allocators_[p][stream];
    allocator = std::make_shared<StatAllocator>(allocator);
  }

1043 1044
#endif

J
jianghaicheng 已提交
1045 1046 1047 1048 1049 1050
#ifdef PADDLE_WITH_IPU
  void InitNaiveBestFitIPUAllocator(platform::IPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
#endif

1051 1052 1053 1054 1055
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  void InitNaiveBestFitCustomDeviceAllocator(platform::CustomPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }

1056 1057 1058 1059 1060 1061
  void InitNaiveBestFitCustomDeviceAllocator(platform::CustomPlace p,
                                             phi::stream::stream_t stream) {
    custom_device_allocators_[p][stream] =
        std::make_shared<NaiveBestFitAllocator>(p);
  }

1062 1063
  void InitAutoGrowthCustomDeviceAllocator(platform::CustomPlace p,
                                           bool allow_free_idle_chunk) {
1064
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 20;
1065 1066
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;
1067 1068 1069
    auto custom_allocator =
        std::make_shared<paddle::memory::allocation::CustomAllocator>(p);
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
1070 1071
        custom_allocator,
        phi::DeviceManager::GetMinChunkSize(p),
1072
        /*chunk_size=*/chunk_size,
1073 1074
        allow_free_idle_chunk);
  }
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

  void InitAutoGrowthCustomDeviceAllocator(platform::CustomPlace p,
                                           phi::stream::stream_t stream) {
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 20;
    VLOG(4) << "FLAGS_auto_growth_chunk_size_in_mb is "
            << FLAGS_auto_growth_chunk_size_in_mb;

    auto custom_allocator =
        std::make_shared<paddle::memory::allocation::CustomAllocator>(p);
    auto alignment = phi::DeviceManager::GetMinChunkSize(p);
    custom_device_allocators_[p][stream] =
        std::make_shared<AutoGrowthBestFitAllocator>(
            custom_allocator, alignment, chunk_size, allow_free_idle_chunk_);
  }

  void WrapStreamSafeCustomDeviceAllocator(platform::CustomPlace p,
                                           phi::stream::stream_t stream) {
    std::shared_ptr<Allocator>& allocator =
        custom_device_allocators_[p][stream];
    allocator =
        std::make_shared<StreamSafeCustomDeviceAllocator>(allocator, p, stream);
  }

  void InitStreamSafeCustomDeviceAllocator(platform::CustomPlace p,
                                           phi::stream::stream_t stream) {
    VLOG(8) << "Init CustomDevice allocator for stream " << stream
            << " in place " << p;
    if (strategy_ == AllocatorStrategy::kAutoGrowth) {
      InitAutoGrowthCustomDeviceAllocator(p, stream);
    } else {
      InitNaiveBestFitCustomDeviceAllocator(p, stream);
    }
    WrapStreamSafeCustomDeviceAllocator(p, stream);
  }
1109 1110
#endif

1111 1112 1113 1114 1115 1116 1117
  void InitSystemAllocators() {
    if (!system_allocators_.empty()) return;
    system_allocators_[platform::CPUPlace()] = std::make_shared<CPUAllocator>();
#ifdef PADDLE_WITH_XPU
    int device_count = platform::GetXPUDeviceCount();
    for (int i = 0; i < device_count; ++i) {
      platform::XPUPlace p(i);
1118
      system_allocators_[p] = CreateXPUAllocator(p);
Z
Zeng Jinle 已提交
1119
    }
1120
#endif
J
jianghaicheng 已提交
1121 1122 1123 1124 1125 1126 1127
#ifdef PADDLE_WITH_IPU
    int device_count = platform::GetIPUDeviceCount();
    for (int i = 0; i < device_count; ++i) {
      platform::IPUPlace p(i);
      system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
    }
#endif
1128 1129 1130
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    system_allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<CPUPinnedAllocator>();
1131
    int device_count = platform::GetGPUDeviceCount();
1132 1133
    for (int i = 0; i < device_count; ++i) {
      platform::CUDAPlace p(i);
1134
      system_allocators_[p] = CreateCUDAAllocator(p);
1135
    }
F
fwenguang 已提交
1136
#endif
1137 1138 1139 1140
#ifdef PADDLE_WITH_CUSTOM_DEVICE
    auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
    for (const auto& dev_type : device_types) {
      for (size_t dev_id = 0;
1141 1142
           dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
           dev_id++) {
1143 1144 1145 1146
        platform::CustomPlace p(dev_type, dev_id);
        system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
      }
    }
1147 1148
#endif
  }
Z
Zeng Jinle 已提交
1149 1150

  void InitZeroSizeAllocators() {
1151
    if (!zero_size_allocators_.empty()) return;
Z
Zeng Jinle 已提交
1152 1153
    std::vector<platform::Place> places;
    places.emplace_back(platform::CPUPlace());
1154
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1155
    int device_count = platform::GetGPUDeviceCount();
Z
Zeng Jinle 已提交
1156 1157 1158 1159 1160
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::CUDAPlace(dev_id));
    }
    places.emplace_back(platform::CUDAPinnedPlace());
#endif
1161 1162 1163 1164 1165 1166
#ifdef PADDLE_WITH_XPU
    int device_count = platform::GetXPUDeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::XPUPlace(dev_id));
    }
#endif
J
jianghaicheng 已提交
1167 1168 1169 1170 1171 1172
#ifdef PADDLE_WITH_IPU
    int device_count = platform::GetIPUDeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::IPUPlace(dev_id));
    }
#endif
1173
#ifdef PADDLE_WITH_CUSTOM_DEVICE
1174
    auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
1175 1176
    for (const auto& dev_type : device_types) {
      for (size_t dev_id = 0;
1177 1178
           dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
           dev_id++) {
1179 1180 1181 1182
        places.emplace_back(platform::CustomPlace(dev_type, dev_id));
      }
    }
#endif
Z
Zeng Jinle 已提交
1183 1184 1185

    for (auto& p : places) {
      zero_size_allocators_[p] = std::make_shared<ZeroSizeAllocator>(p);
Y
Yu Yang 已提交
1186 1187
    }
  }
Z
Zeng Jinle 已提交
1188

1189 1190
  static void CheckAllocThreadSafe(const AllocatorMap& allocators) {
    for (auto& pair : allocators) {
1191 1192
      PADDLE_ENFORCE_EQ(pair.second->IsAllocThreadSafe(),
                        true,
1193 1194
                        platform::errors::InvalidArgument(
                            "Public allocators must be thread safe"));
1195
    }
1196
  }
1197

1198 1199 1200 1201
  void CheckAllocThreadSafe() const {
    CheckAllocThreadSafe(allocators_);
    CheckAllocThreadSafe(zero_size_allocators_);
    CheckAllocThreadSafe(system_allocators_);
1202
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1203
    if (is_stream_safe_cuda_allocator_used_) {
1204 1205 1206
      CheckCUDAAllocThreadSafe(cuda_allocators_);
    }
#endif
1207 1208 1209
  }

  void WrapCUDARetryAllocator(size_t retry_time) {
1210
    PADDLE_ENFORCE_GT(
1211 1212
        retry_time,
        0,
1213 1214
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
1215
    for (auto& pair : allocators_) {
1216 1217
      if (platform::is_gpu_place(pair.first) ||
          platform::is_xpu_place(pair.first)) {
1218 1219 1220 1221 1222
        pair.second = std::make_shared<RetryAllocator>(pair.second, retry_time);
      }
    }
  }

1223 1224
  void WrapStatAllocator() {
    for (auto& pair : allocators_) {
1225 1226 1227 1228 1229 1230 1231
      // Now memory stats is only supported for CPU and GPU
      const platform::Place& place = pair.first;
      if (platform::is_cpu_place(place) ||
          platform::is_cuda_pinned_place(place) ||
          platform::is_gpu_place(place)) {
        pair.second = std::make_shared<StatAllocator>(pair.second);
      }
1232 1233 1234
    }
  }

1235 1236
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  // a standalone CUDA allocator to support multi-stream GC in new executor
1237 1238
  std::map<platform::Place, std::shared_ptr<StreamSafeCUDAAllocator>>
      default_stream_safe_cuda_allocators_;
1239
  CUDAAllocatorMap cuda_allocators_;
1240
  std::shared_timed_mutex cuda_allocator_mutex_;
1241
#endif
1242 1243 1244 1245 1246 1247 1248 1249 1250

#ifdef PADDLE_WITH_XPU
  // a standalone XPU allocator to support multi-stream GC in new executor
  std::map<platform::Place, std::shared_ptr<StreamSafeXPUAllocator>>
      default_stream_safe_xpu_allocators_;
  XPUAllocatorMap xpu_allocators_;
  std::shared_timed_mutex xpu_allocator_mutex_;
#endif

1251 1252 1253 1254 1255 1256 1257 1258 1259
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  // a standalone custom device allocator to support multi-stream GC in new
  // executor
  std::map<platform::Place, std::shared_ptr<StreamSafeCustomDeviceAllocator>>
      default_stream_safe_custom_device_allocators_;
  CustomDeviceAllocatorMap custom_device_allocators_;
  std::shared_timed_mutex custom_device_allocator_mutex_;
#endif

1260
  AllocatorStrategy strategy_;
1261
  AllocatorMap allocators_;
1262 1263
  static AllocatorMap zero_size_allocators_;
  static AllocatorMap system_allocators_;
1264
  bool allow_free_idle_chunk_;
1265
  bool is_stream_safe_cuda_allocator_used_;
1266
};
1267 1268 1269 1270
AllocatorFacadePrivate::AllocatorMap
    AllocatorFacadePrivate::zero_size_allocators_;
AllocatorFacadePrivate::AllocatorMap AllocatorFacadePrivate::system_allocators_;

Y
Refine  
Yu Yang 已提交
1271
// Pimpl. Make interface clean.
1272
AllocatorFacade::AllocatorFacade() : m_(new AllocatorFacadePrivate()) {}
1273 1274 1275
// delete m_ may cause core dump when the destructor of python in conflict with
// cpp.
AllocatorFacade::~AllocatorFacade() {}
1276 1277

AllocatorFacade& AllocatorFacade::Instance() {
1278 1279 1280 1281 1282 1283
  static AllocatorFacade* instance = new AllocatorFacade;
  return *instance;
}

AllocatorFacadePrivate* AllocatorFacade::GetPrivate() const {
#ifdef PADDLE_WITH_CUDA
1284
  if (UNLIKELY(IsCUDAGraphCapturing())) {
1285
    auto id = phi::backends::gpu::CUDAGraph::CapturingPoolID();
1286 1287
    auto iter = cuda_graph_map_.find(id);
    PADDLE_ENFORCE_NE(
1288 1289
        iter,
        cuda_graph_map_.end(),
1290 1291 1292 1293 1294 1295 1296
        platform::errors::PermissionDenied(
            "No memory pool is prepared for CUDA Graph capturing."));
    VLOG(10) << "Choose CUDA Graph memory pool";
    return iter->second.get();
  }
#endif
  return m_;
1297 1298
}

1299 1300
const std::shared_ptr<Allocator>& AllocatorFacade::GetAllocator(
    const platform::Place& place) {
1301 1302
  return GetPrivate()->GetAllocator(
      place, /* A non-zero num to choose allocator_ */ 1);
1303 1304
}

1305
void* AllocatorFacade::GetBasePtr(
1306
    const std::shared_ptr<phi::Allocation>& allocation) {
1307 1308
  PADDLE_ENFORCE_EQ(GetAllocatorStrategy(),
                    AllocatorStrategy::kAutoGrowth,
1309 1310 1311 1312
                    paddle::platform::errors::Unimplemented(
                        "GetBasePtr() is only implemented for auto_growth "
                        "strategy, not support allocator strategy: %d",
                        static_cast<int>(GetAllocatorStrategy())));
1313 1314
  PADDLE_ENFORCE_EQ(platform::is_gpu_place(allocation->place()),
                    true,
1315 1316 1317 1318
                    paddle::platform::errors::Unimplemented(
                        "GetBasePtr() is only implemented for CUDAPlace(), not "
                        "suppot place: %s",
                        allocation->place()));
1319
  return GetPrivate()->GetBasePtr(allocation);
1320 1321
}

1322 1323
const std::shared_ptr<Allocator>& AllocatorFacade::GetZeroAllocator(
    const platform::Place& place) {
1324
  return GetPrivate()->GetAllocator(place, /* zero size */ 0);
1325 1326
}

1327
std::shared_ptr<phi::Allocation> AllocatorFacade::AllocShared(
1328
    const platform::Place& place, size_t size) {
1329
  return std::shared_ptr<phi::Allocation>(Alloc(place, size));
1330 1331
}

1332 1333
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size) {
1334
  return GetPrivate()->GetAllocator(place, size)->Allocate(size);
1335 1336
}

W
Wilber 已提交
1337
uint64_t AllocatorFacade::Release(const platform::Place& place) {
1338 1339
  return GetPrivate()
      ->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1)
1340 1341 1342
      ->Release(place);
}

1343 1344
std::shared_ptr<phi::Allocation> AllocatorFacade::AllocShared(
    const platform::Place& place, size_t size, const phi::Stream& stream) {
1345
  return std::shared_ptr<phi::Allocation>(Alloc(place, size, stream));
1346 1347
}

1348 1349
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size,
1350
                                     const phi::Stream& stream) {
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  if (platform::is_custom_place(place)) {
    platform::CustomPlace p(place);
    phi::stream::stream_t s =
        reinterpret_cast<phi::stream::stream_t>(stream.id());
    return GetPrivate()
        ->GetAllocator(p, s, /* create_if_not_found = */ true)
        ->Allocate(size);
  }
#endif
1361
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1362 1363 1364 1365 1366
  AllocatorFacadePrivate* m = GetPrivate();
  if (!m->IsStreamSafeCUDAAllocatorUsed()) {
    VLOG(6) << "Warning: StreamSafeCUDAAllocator is not used!";
    return Alloc(place, size);
  }
1367

1368 1369 1370
  platform::CUDAPlace p(place.GetDeviceId());
  if (LIKELY(size > 0 && FLAGS_use_system_allocator == false)) {
    gpuStream_t s = reinterpret_cast<gpuStream_t>(stream.id());
1371
    return m->GetAllocator(p, s, /* create_if_not_found = */ true)
1372 1373
        ->Allocate(size);
  } else {
1374
    return m->GetAllocator(p, size)->Allocate(size);
1375
  }
1376
#elif defined(PADDLE_WITH_XPU)
1377
  return GetAllocator(place)->Allocate(size);
1378
#else
1379 1380
  PADDLE_THROW(platform::errors::PreconditionNotMet(
      "Not compiled with GPU or XPU or CustomDevice."));
1381 1382 1383
#endif
}

1384 1385 1386
bool AllocatorFacade::InSameStream(
    const std::shared_ptr<phi::Allocation>& allocation,
    const phi::Stream& stream) {
1387
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1388 1389 1390 1391
  gpuStream_t s = reinterpret_cast<gpuStream_t>(stream.id());
  return s == GetStream(allocation);
#else
  PADDLE_THROW(platform::errors::PreconditionNotMet("Not compiled with GPU."));
1392
#endif
1393 1394
}

1395 1396 1397 1398
bool AllocatorFacade::IsStreamSafeCUDAAllocatorUsed() {
  return GetPrivate()->IsStreamSafeCUDAAllocatorUsed();
}

1399
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1400
uint64_t AllocatorFacade::Release(const platform::CUDAPlace& place,
1401
                                  gpuStream_t stream) {
1402 1403 1404 1405 1406 1407 1408
  AllocatorFacadePrivate* m = GetPrivate();
  if (!m->IsStreamSafeCUDAAllocatorUsed()) {
    VLOG(6) << "Warning: StreamSafeCUDAAllocator is not used!";
    return Release(place);
  }

  return m->GetAllocator(place, stream)->Release(place);
1409 1410
}

1411
void AllocatorFacade::RecordStream(std::shared_ptr<phi::Allocation> allocation,
1412
                                   gpuStream_t stream) {
1413
  GetPrivate()->RecordStream(allocation, stream);
1414 1415
}

1416
const std::shared_ptr<Allocator>& AllocatorFacade::GetAllocator(
1417
    const platform::Place& place, gpuStream_t stream) {
1418 1419 1420 1421 1422
  AllocatorFacadePrivate* m = GetPrivate();

  if (!m->IsStreamSafeCUDAAllocatorUsed()) {
    VLOG(6) << "Warning: StreamSafeCUDAAllocator is not used!";
    return GetAllocator(place);
1423
  }
1424 1425

  if (platform::is_gpu_place(place) && FLAGS_use_system_allocator == false) {
1426 1427
    return m->GetAllocator(place,
                           stream,
1428 1429 1430
                           /*create_if_not_found=*/true);
  }
  return m->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1);
1431 1432
}

1433
gpuStream_t AllocatorFacade::GetStream(
1434
    const std::shared_ptr<phi::Allocation>& allocation) const {
1435
  return GetPrivate()->GetStream(allocation);
1436 1437
}

1438
void AllocatorFacade::SetDefaultStream(const platform::CUDAPlace& place,
1439
                                       gpuStream_t stream) {
1440 1441
  if (m_->IsStreamSafeCUDAAllocatorUsed()) {
    m_->SetDefaultStream(place, stream);
1442 1443 1444
  }
}

1445
#ifdef PADDLE_WITH_CUDA
1446
void AllocatorFacade::PrepareMemoryPoolForCUDAGraph(int64_t id) {
1447 1448
  PADDLE_ENFORCE_EQ(GetAllocatorStrategy(),
                    AllocatorStrategy::kAutoGrowth,
1449 1450 1451 1452 1453 1454
                    platform::errors::InvalidArgument(
                        "CUDA Graph is only supported when the "
                        "FLAGS_allocator_strategy=\"auto_growth\", but got "
                        "FLAGS_allocator_strategy=\"%s\"",
                        FLAGS_allocator_strategy));
  auto& allocator = cuda_graph_map_[id];
1455 1456
  auto& ref_cnt = cuda_graph_ref_cnt_[id];
  if (allocator.get() == nullptr) {
1457 1458
    allocator = std::make_unique<AllocatorFacadePrivate>(
        /*allow_free_idle_chunk=*/false);
1459 1460 1461 1462 1463
    VLOG(10) << "Create memory pool for CUDA Graph with memory ID " << id;
  } else {
    VLOG(10) << "Use created memory pool for CUDA Graph with memory ID " << id;
  }
  ++ref_cnt;
1464 1465
}

1466 1467
void AllocatorFacade::RemoveMemoryPoolOfCUDAGraph(int64_t id) {
  auto ref_cnt_iter = cuda_graph_ref_cnt_.find(id);
1468 1469
  PADDLE_ENFORCE_NE(ref_cnt_iter,
                    cuda_graph_ref_cnt_.end(),
1470
                    platform::errors::InvalidArgument(
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
                        "Cannot find CUDA Graph with memory ID = %d", id));
  auto& ref_cnt = ref_cnt_iter->second;
  --ref_cnt;
  if (ref_cnt == 0) {
    cuda_graph_map_.erase(id);
    cuda_graph_ref_cnt_.erase(ref_cnt_iter);
  } else {
    VLOG(10) << "Decrease memory pool ID " << id << " reference count to be "
             << ref_cnt;
  }
1481 1482
}
#endif
1483
#endif
1484

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
#ifdef PADDLE_WITH_CUSTOM_DEVICE
const std::shared_ptr<Allocator>& AllocatorFacade::GetAllocator(
    const platform::Place& place, phi::stream::stream_t stream) {
  AllocatorFacadePrivate* m = GetPrivate();
  if (!FLAGS_use_stream_safe_cuda_allocator) {
    return m->GetAllocator(place,
                           stream,
                           /*create_if_not_found=*/true);
  }
  return m->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1);
}
#endif

1498 1499 1500
UNUSED static std::shared_ptr<NaiveBestFitAllocator> unused_obj =
    std::make_shared<NaiveBestFitAllocator>(platform::CPUPlace());

1501 1502 1503
}  // namespace allocation
}  // namespace memory
}  // namespace paddle