allocator_facade.cc 44.5 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 "gflags/gflags.h"
18
#include "paddle/fluid/memory/allocation/aligned_allocator.h"
19
#include "paddle/fluid/memory/allocation/allocator.h"
Y
Yu Yang 已提交
20
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
21
#include "paddle/fluid/memory/allocation/auto_growth_best_fit_allocator.h"
22
#include "paddle/fluid/memory/allocation/cpu_allocator.h"
23
#include "paddle/fluid/memory/allocation/naive_best_fit_allocator.h"
S
sneaxiy 已提交
24
#include "paddle/fluid/memory/allocation/retry_allocator.h"
25
#include "paddle/fluid/memory/allocation/stat_allocator.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/fluid/platform/device_context.h"
40
#include "paddle/phi/backends/gpu/gpu_context.h"
41 42

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

46 47 48 49 50
#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
51
#endif
52

53
#ifdef PADDLE_WITH_XPU
54
#include "paddle/fluid/platform/device/xpu/xpu_info.h"
55
#endif
56 57 58 59

#ifdef PADDLE_WITH_ASCEND_CL
#include "paddle/fluid/memory/allocation/npu_pinned_allocator.h"
#endif
60

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

F
fwenguang 已提交
65 66 67 68
#ifdef PADDLE_WITH_MLU
#include "paddle/fluid/platform/device/mlu/mlu_info.h"
#endif

69 70 71 72 73
#ifdef PADDLE_WITH_CUSTOM_DEVICE
#include "paddle/fluid/memory/allocation/custom_allocator.h"
#include "paddle/fluid/platform/device/device_wrapper.h"
#endif

Z
Zeng Jinle 已提交
74
PADDLE_DEFINE_EXPORTED_int64(
75 76
    gpu_allocator_retry_time,
    10000,
S
sneaxiy 已提交
77 78 79
    "The retry time (milliseconds) when allocator fails "
    "to allocate memory. No retry if this value is not greater than 0");

Z
Zeng Jinle 已提交
80
PADDLE_DEFINE_EXPORTED_bool(
81 82
    use_system_allocator,
    false,
Z
Zeng Jinle 已提交
83 84
    "Whether to use system allocator to allocate CPU and GPU memory. "
    "Only used for unittests.");
85

86 87
PADDLE_DEFINE_EXPORTED_bool(use_virtual_memory_auto_growth,
                            false,
88 89
                            "Use VirtualMemoryAutoGrowthBestFitAllocator.");

90 91 92
// 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.
93 94
PADDLE_DEFINE_EXPORTED_bool(use_stream_safe_cuda_allocator,
                            true,
95 96
                            "Enable StreamSafeCUDAAllocator");

97 98
PADDLE_DEFINE_EXPORTED_bool(use_cuda_managed_memory,
                            false,
99 100 101 102
                            "Whether to use CUDAManagedAllocator to allocate "
                            "managed memory, only available for auto_growth "
                            "strategy");

103
DECLARE_string(allocator_strategy);
104
DECLARE_uint64(auto_growth_chunk_size_in_mb);
105

106 107 108 109
namespace paddle {
namespace memory {
namespace allocation {

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

   private:
    std::shared_ptr<Allocator> allocator_;
128
    DecoratedAllocationPtr underlying_allocation_;
129 130 131 132 133 134
  };

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

 public:
135 136
  ~CUDAGraphAllocator() { VLOG(10) << "CUDAGraphAllocator destructed"; }

137 138 139 140 141 142
  static std::shared_ptr<Allocator> Create(
      const std::shared_ptr<Allocator>& allocator) {
    return std::shared_ptr<Allocator>(new CUDAGraphAllocator(allocator));
  }

 protected:
143
  phi::Allocation* AllocateImpl(size_t size) {
144
    VLOG(10) << "Allocate " << size << " for CUDA Graph";
145 146 147
    return new PrivateAllocation(this,
                                 static_unique_ptr_cast<Allocation>(
                                     underlying_allocator_->Allocate(size)));
148 149
  }

150
  void FreeImpl(phi::Allocation* allocation) {
151 152 153 154 155 156 157 158 159
    VLOG(10) << "delete for CUDA Graph";
    delete allocation;
  }

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

160 161
static bool IsCUDAGraphCapturing() {
#ifdef PADDLE_WITH_CUDA
162
  return UNLIKELY(phi::backends::gpu::CUDAGraph::IsThisThreadCapturing());
163 164 165 166 167
#else
  return false;
#endif
}

Y
Yu Yang 已提交
168 169
class AllocatorFacadePrivate {
 public:
170 171
  using AllocatorMap = std::map<platform::Place, std::shared_ptr<Allocator>>;

172 173 174 175 176 177
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  using CUDAAllocatorMap =
      std::map<platform::CUDAPlace,
               std::map<gpuStream_t, std::shared_ptr<Allocator>>>;
#endif

178 179
  explicit AllocatorFacadePrivate(bool allow_free_idle_chunk = true) {
    strategy_ = GetAllocatorStrategy();
180 181
    is_stream_safe_cuda_allocator_used_ = false;

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

      case AllocatorStrategy::kAutoGrowth: {
        InitNaiveBestFitCPUAllocator();
228 229
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
        allow_free_idle_chunk_ = allow_free_idle_chunk;
230 231 232 233 234
        for (int dev_id = 0; dev_id < platform::GetGPUDeviceCount(); ++dev_id) {
          InitAutoGrowthCUDAAllocator(platform::CUDAPlace(dev_id),
                                      allow_free_idle_chunk_);
        }

235 236 237 238 239 240 241 242
        // 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
243
        // manner in GetAllocator function with 'create_if_not_found = true'.
244 245 246 247
        // 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.
248
        if (FLAGS_use_stream_safe_cuda_allocator) {
249 250 251 252
          if (LIKELY(!IsCUDAGraphCapturing())) {
            WrapStreamSafeCUDAAllocatorForDefault();
          }
          is_stream_safe_cuda_allocator_used_ = true;
253
        }
254

255 256
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
257 258 259 260 261 262
#ifdef PADDLE_WITH_ASCEND_CL
        for (int dev_id = 0; dev_id < platform::GetNPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitNPUAllocator(platform::NPUPlace(dev_id));
        }
        InitNaiveBestFitNPUPinnedAllocator();
#endif
263 264 265 266
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
J
jianghaicheng 已提交
267 268 269 270 271
#endif
#ifdef PADDLE_WITH_IPU
        for (int dev_id = 0; dev_id < platform::GetIPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitIPUAllocator(platform::IPUPlace(dev_id));
        }
F
fwenguang 已提交
272 273 274 275 276
#endif
#ifdef PADDLE_WITH_MLU
        for (int dev_id = 0; dev_id < platform::GetMLUDeviceCount(); ++dev_id) {
          InitNaiveBestFitMLUAllocator(platform::MLUPlace(dev_id));
        }
277 278
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
279
        auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
280 281
        for (const auto& dev_type : device_types) {
          for (size_t dev_id = 0;
282
               dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
283 284 285 286 287
               ++dev_id) {
            InitAutoGrowthCustomDeviceAllocator(
                platform::CustomPlace(dev_type, dev_id), allow_free_idle_chunk);
          }
        }
288
#endif
Z
Zeng Jinle 已提交
289 290
        break;
      }
291

292 293
      case AllocatorStrategy::kThreadLocal: {
        InitNaiveBestFitCPUAllocator();
294 295 296 297 298
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
J
jianghaicheng 已提交
299 300 301 302 303
#ifdef PADDLE_WITH_IPU
        for (int dev_id = 0; dev_id < platform::GetIPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitIPUAllocator(platform::IPUPlace(dev_id));
        }
#endif
304
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
305
        for (int dev_id = 0; dev_id < platform::GetGPUDeviceCount(); ++dev_id) {
306 307 308
          InitThreadLocalCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
F
fwenguang 已提交
309 310 311 312 313
#endif
#ifdef PADDLE_WITH_MLU
        for (int dev_id = 0; dev_id < platform::GetMLUDeviceCount(); ++dev_id) {
          InitNaiveBestFitMLUAllocator(platform::MLUPlace(dev_id));
        }
314 315 316 317
#endif
        break;
      }

Z
Zeng Jinle 已提交
318
      default: {
319
        PADDLE_THROW(platform::errors::InvalidArgument(
320
            "Unsupported allocator strategy: %d", static_cast<int>(strategy_)));
Z
Zeng Jinle 已提交
321
      }
Y
Yu Yang 已提交
322
    }
Z
Zeng Jinle 已提交
323
    InitZeroSizeAllocators();
324
    InitSystemAllocators();
325 326 327 328 329

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

330 331
    WrapStatAllocator();

332
    CheckAllocThreadSafe();
333 334

#ifdef PADDLE_WITH_CUDA
335 336 337
    // No need to wrap CUDAGraphAllocator for StreamSafeCUDAAllocator
    if (!is_stream_safe_cuda_allocator_used_ &&
        UNLIKELY(IsCUDAGraphCapturing())) {
338 339 340
      WrapCUDAGraphAllocator();
    }
#endif
Z
Zeng Jinle 已提交
341 342 343 344
  }

  inline const std::shared_ptr<Allocator>& GetAllocator(
      const platform::Place& place, size_t size) {
345
    VLOG(6) << "GetAllocator"
L
Leo Chen 已提交
346
            << " " << place << " " << size;
347 348
    const auto& allocators =
        (size > 0 ? (UNLIKELY(FLAGS_use_system_allocator) ? system_allocators_
349
                                                          : GetAllocatorMap())
350
                  : zero_size_allocators_);
Z
Zeng Jinle 已提交
351
    auto iter = allocators.find(place);
352 353
    PADDLE_ENFORCE_NE(iter,
                      allocators.end(),
354 355
                      platform::errors::NotFound(
                          "No allocator found for the place, %s", place));
Z
Zeng Jinle 已提交
356
    return iter->second;
357 358
  }

359
  void* GetBasePtr(const std::shared_ptr<phi::Allocation>& allocation) {
360 361 362
    return static_cast<Allocation*>(allocation.get())->base_ptr();
  }

363 364 365 366 367
  bool IsStreamSafeCUDAAllocatorUsed() {
    return is_stream_safe_cuda_allocator_used_ &&
           LIKELY(FLAGS_use_system_allocator == false);
  }

368
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
369
  bool HasCUDAAllocator(const platform::CUDAPlace& place, gpuStream_t stream) {
370 371 372 373 374 375 376 377 378
    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();
  }

379
  const std::shared_ptr<Allocator>& GetAllocator(
380 381
      const platform::CUDAPlace& place,
      gpuStream_t stream,
382
      bool create_if_not_found = false) {
383 384 385 386 387
    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);
      }
388 389 390
    }

    /* shared_lock_guard */ {
391 392 393
      std::shared_lock<std::shared_timed_mutex> lock_guard(
          cuda_allocator_mutex_);
      if (LIKELY(HasCUDAAllocator(place, stream))) {
394 395
        return cuda_allocators_[place][stream];
      } else {
396 397
        PADDLE_ENFORCE_NE(create_if_not_found,
                          false,
398 399 400
                          platform::errors::NotFound(
                              "No allocator found for stream %s in place %s "
                              "with create_if_not_found = false",
401 402
                              stream,
                              place));
403 404 405
      }
    }

406
    /* unique_lock_guard */ {
407 408 409 410
      std::unique_lock<std::shared_timed_mutex> lock_guard(
          cuda_allocator_mutex_);
      InitStreamSafeCUDAAllocator(place, stream);
      return cuda_allocators_[place][stream];
411
    }
412 413
  }

414 415 416 417
  const std::shared_ptr<StreamSafeCUDAAllocator>
  GetDefaultStreamSafeCUDAAllocator(const platform::CUDAPlace& place) const {
    const auto iter = default_stream_safe_cuda_allocators_.find(place);
    PADDLE_ENFORCE_NE(
418 419
        iter,
        default_stream_safe_cuda_allocators_.end(),
420 421 422 423 424
        platform::errors::NotFound(
            "No StreamSafeCUDAAllocator found for the place, %s", place));
    return iter->second;
  }

425
  gpuStream_t GetDefaultStream(const platform::CUDAPlace& place) const {
426 427 428 429 430
    const std::shared_ptr<StreamSafeCUDAAllocator>& allocator =
        GetDefaultStreamSafeCUDAAllocator(place);
    return allocator->GetDefaultStream();
  }

431
  void SetDefaultStream(const platform::CUDAPlace& place, gpuStream_t stream) {
432 433
    const std::shared_ptr<StreamSafeCUDAAllocator>& allocator =
        GetDefaultStreamSafeCUDAAllocator(place);
434

435
    PADDLE_ENFORCE_EQ(
436 437
        allocator->GetDefaultStream(),
        nullptr,
438 439 440
        platform::errors::Unavailable(
            "The default stream for StreamSafeCUDAAllocator(%p) in %s has been "
            "set to %p, not allow to change it to %p.",
441 442 443 444
            allocator.get(),
            place,
            allocator->GetDefaultStream(),
            stream));
445

446 447 448 449 450 451
    allocator->SetDefaultStream(stream);
    VLOG(8) << "Set default stream to " << stream
            << " for StreamSafeCUDAAllocator(" << allocator.get() << ") in "
            << place;
  }

452
  void RecordStream(std::shared_ptr<phi::Allocation> allocation,
453
                    gpuStream_t stream) {
454 455 456 457 458 459
    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";
460
    }
461 462
  }

463
  gpuStream_t GetStream(
464
      const std::shared_ptr<phi::Allocation>& allocation) const {
465 466 467 468 469 470 471 472 473 474 475
    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();
476 477 478 479 480 481 482 483 484 485
  }
#endif

 private:
  class ZeroSizeAllocator : public Allocator {
   public:
    explicit ZeroSizeAllocator(platform::Place place) : place_(place) {}
    bool IsAllocThreadSafe() const override { return true; }

   protected:
486
    phi::Allocation* AllocateImpl(size_t size) override {
487 488
      return new Allocation(nullptr, 0, place_);
    }
489
    void FreeImpl(phi::Allocation* allocation) override { delete allocation; }
490 491 492 493 494

   private:
    platform::Place place_;
  };

495
  const AllocatorMap& GetAllocatorMap() { return allocators_; }
496

497
  void InitNaiveBestFitCPUAllocator() {
498 499 500 501 502 503 504
#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
505
    allocators_[platform::CPUPlace()] = std::make_shared<CPUAllocator>();
506
#endif
Y
Yu Yang 已提交
507 508
  }

509
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
510 511 512
  void InitNaiveBestFitCUDAPinnedAllocator() {
    allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CUDAPinnedPlace());
513 514
  }

515 516 517 518 519 520 521 522
  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(
523 524
          strategy_,
          AllocatorStrategy::kAutoGrowth,
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
          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"
540 541
            "Or you must use the gpu device that supports managed memory.",
            p.device));
542 543 544 545 546 547
      }
      return std::make_shared<CUDAManagedAllocator>(p);
    }
    return std::make_shared<CUDAAllocator>(p);
  }

548 549
  void InitStreamSafeCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
    PADDLE_ENFORCE_EQ(
550 551
        strategy_,
        AllocatorStrategy::kAutoGrowth,
552 553 554 555
        platform::errors::Unimplemented(
            "Only support auto-growth strategey for StreamSafeCUDAAllocator, "
            "the allocator strategy %d is unsupported for multi-stream",
            static_cast<int>(strategy_)));
556 557 558
    if (LIKELY(!HasCUDAAllocator(p, stream))) {
      VLOG(8) << "Init CUDA allocator for stream " << stream << " in place "
              << p;
559 560 561
      InitAutoGrowthCUDAAllocator(p, stream);
      WrapStreamSafeCUDAAllocator(p, stream);
      WrapCUDARetryAllocator(p, stream, FLAGS_gpu_allocator_retry_time);
562
      WrapStatAllocator(p, stream);
563 564 565 566
    }
  }

  void InitAutoGrowthCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
567 568 569
    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;
570
#if defined(PADDLE_WITH_HIP)
571
    auto cuda_allocator = CreateCUDAAllocator(p);
572
    cuda_allocators_[p][stream] = std::make_shared<AutoGrowthBestFitAllocator>(
573 574 575 576
        cuda_allocator,
        platform::GpuMinChunkSize(),
        chunk_size,
        allow_free_idle_chunk_);
577 578 579 580 581 582 583
#endif

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

587
      PADDLE_ENFORCE_GPU_SUCCESS(
588
          paddle::platform::dynload::cuDeviceGetAttribute(
589 590
              &val,
              CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED,
591 592 593 594 595 596 597 598 599 600 601
              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 {
602
      auto cuda_allocator = CreateCUDAAllocator(p);
603 604
      cuda_allocators_[p][stream] =
          std::make_shared<AutoGrowthBestFitAllocator>(
605 606
              cuda_allocator,
              platform::GpuMinChunkSize(),
607
              /*chunk_size=*/chunk_size,
608 609 610
              allow_free_idle_chunk_);
    }
#else
611
    auto cuda_allocator = CreateCUDAAllocator(p);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    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>(
645
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk_);
646 647
#endif
#endif
648 649
  }

650
  // NOTE(Ruibiao): Old single-stream version, will be removed later
651 652
  void InitAutoGrowthCUDAAllocator(platform::CUDAPlace p,
                                   bool allow_free_idle_chunk) {
653 654 655
    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;
656
#if defined(PADDLE_WITH_HIP)
657
    auto cuda_allocator = CreateCUDAAllocator(p);
658
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
659 660
        cuda_allocator,
        platform::GpuMinChunkSize(),
661
        /*chunk_size=*/chunk_size,
662
        allow_free_idle_chunk);
663 664 665 666 667 668 669
#endif

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

673
      PADDLE_ENFORCE_GPU_SUCCESS(
674
          paddle::platform::dynload::cuDeviceGetAttribute(
675 676
              &val,
              CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED,
677 678 679 680 681 682 683 684 685 686 687
              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 {
688
      auto cuda_allocator = CreateCUDAAllocator(p);
689
      allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
690 691
          cuda_allocator,
          platform::GpuMinChunkSize(),
692
          /*chunk_size=*/chunk_size,
693
          allow_free_idle_chunk);
694 695 696
    }

#else
697
    auto cuda_allocator = CreateCUDAAllocator(p);
L
Leo Chen 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    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;
    }
729
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
730
        underlying_allocator, alignment, chunk_size, allow_free_idle_chunk);
731 732
#endif
#endif
S
sneaxiy 已提交
733
  }
734 735 736 737 738 739

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

  void WrapStreamSafeCUDAAllocator(platform::CUDAPlace p, gpuStream_t stream) {
740 741
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
    allocator = std::make_shared<StreamSafeCUDAAllocator>(
742 743 744
        allocator,
        p,
        stream,
745
        /* in_cuda_graph_capturing = */ !allow_free_idle_chunk_);
746 747
  }

748 749 750 751 752 753
  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>(
754 755
                pair.second,
                place,
756
                /* default_stream = */ nullptr,
757 758 759 760 761 762 763 764 765 766 767 768 769
                /* 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();
      }
    }
  }

770 771
  void WrapCUDARetryAllocator(platform::CUDAPlace p,
                              gpuStream_t stream,
772 773
                              size_t retry_time) {
    PADDLE_ENFORCE_GT(
774 775
        retry_time,
        0,
776 777
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
778
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
779 780 781
    allocator = std::make_shared<RetryAllocator>(allocator, retry_time);
  }

782 783 784 785 786
  void WrapStatAllocator(platform::CUDAPlace p, gpuStream_t stream) {
    std::shared_ptr<Allocator>& allocator = cuda_allocators_[p][stream];
    allocator = std::make_shared<StatAllocator>(allocator);
  }

787 788 789 790 791 792 793 794 795
#ifdef PADDLE_WITH_CUDA
  void WrapCUDAGraphAllocator() {
    for (auto& item : allocators_) {
      auto& allocator = item.second;
      allocator = CUDAGraphAllocator::Create(allocator);
    }
  }
#endif

796 797 798
  static void CheckCUDAAllocThreadSafe(const CUDAAllocatorMap& allocators) {
    for (auto& place_pair : allocators) {
      for (auto& stream_pair : place_pair.second) {
799 800
        PADDLE_ENFORCE_EQ(stream_pair.second->IsAllocThreadSafe(),
                          true,
801 802 803 804 805
                          platform::errors::InvalidArgument(
                              "Public allocators must be thread safe"));
      }
    }
  }
806
#endif
S
sneaxiy 已提交
807

808 809 810 811 812 813
#ifdef PADDLE_WITH_XPU
  void InitNaiveBestFitXPUAllocator(platform::XPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
#endif

J
jianghaicheng 已提交
814 815 816 817 818 819
#ifdef PADDLE_WITH_IPU
  void InitNaiveBestFitIPUAllocator(platform::IPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
#endif

F
fwenguang 已提交
820 821 822 823 824 825
#ifdef PADDLE_WITH_MLU
  void InitNaiveBestFitMLUAllocator(platform::MLUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
#endif

826 827 828 829
#ifdef PADDLE_WITH_ASCEND_CL
  void InitNaiveBestFitNPUAllocator(platform::NPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
830 831 832 833 834

  void InitNaiveBestFitNPUPinnedAllocator() {
    allocators_[platform::NPUPinnedPlace()] =
        std::make_shared<paddle::memory::allocation::NPUPinnedAllocator>();
  }
835 836
#endif

837 838 839 840 841 842 843
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  void InitNaiveBestFitCustomDeviceAllocator(platform::CustomPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }

  void InitAutoGrowthCustomDeviceAllocator(platform::CustomPlace p,
                                           bool allow_free_idle_chunk) {
844
    auto chunk_size = FLAGS_auto_growth_chunk_size_in_mb << 20;
845 846 847
    auto custom_allocator =
        std::make_shared<paddle::memory::allocation::CustomAllocator>(p);
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
848 849
        custom_allocator,
        phi::DeviceManager::GetMinChunkSize(p),
850
        /*chunk_size=*/chunk_size,
851 852 853 854
        allow_free_idle_chunk);
  }
#endif

855 856 857 858 859 860 861 862
  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);
      system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
Z
Zeng Jinle 已提交
863
    }
864
#endif
J
jianghaicheng 已提交
865 866 867 868 869 870 871
#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
872 873 874
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    system_allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<CPUPinnedAllocator>();
875
    int device_count = platform::GetGPUDeviceCount();
876 877
    for (int i = 0; i < device_count; ++i) {
      platform::CUDAPlace p(i);
878
      system_allocators_[p] = CreateCUDAAllocator(p);
879
    }
F
fwenguang 已提交
880 881 882 883
#endif
#ifdef PADDLE_WITH_MLU
    int device_count = platform::GetMLUDeviceCount();
    for (int i = 0; i < device_count; ++i) {
884
      platform::MLUPlace p(i);
F
fwenguang 已提交
885 886
      system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
    }
887 888 889 890 891
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
    auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
    for (const auto& dev_type : device_types) {
      for (size_t dev_id = 0;
892 893
           dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
           dev_id++) {
894 895 896 897
        platform::CustomPlace p(dev_type, dev_id);
        system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
      }
    }
898 899
#endif
  }
Z
Zeng Jinle 已提交
900 901

  void InitZeroSizeAllocators() {
902
    if (!zero_size_allocators_.empty()) return;
Z
Zeng Jinle 已提交
903 904
    std::vector<platform::Place> places;
    places.emplace_back(platform::CPUPlace());
905
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
906
    int device_count = platform::GetGPUDeviceCount();
Z
Zeng Jinle 已提交
907 908 909 910 911
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::CUDAPlace(dev_id));
    }
    places.emplace_back(platform::CUDAPinnedPlace());
#endif
912 913 914 915 916 917
#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
918 919 920 921 922 923
#ifdef PADDLE_WITH_ASCEND_CL
    int device_count = platform::GetNPUDeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::NPUPlace(dev_id));
    }
#endif
J
jianghaicheng 已提交
924 925 926 927 928 929
#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
F
fwenguang 已提交
930 931 932 933 934 935
#ifdef PADDLE_WITH_MLU
    int device_count = platform::GetMLUDeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::MLUPlace(dev_id));
    }
#endif
936
#ifdef PADDLE_WITH_CUSTOM_DEVICE
937
    auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
938 939
    for (const auto& dev_type : device_types) {
      for (size_t dev_id = 0;
940 941
           dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
           dev_id++) {
942 943 944 945
        places.emplace_back(platform::CustomPlace(dev_type, dev_id));
      }
    }
#endif
Z
Zeng Jinle 已提交
946 947 948

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

952 953
  static void CheckAllocThreadSafe(const AllocatorMap& allocators) {
    for (auto& pair : allocators) {
954 955
      PADDLE_ENFORCE_EQ(pair.second->IsAllocThreadSafe(),
                        true,
956 957
                        platform::errors::InvalidArgument(
                            "Public allocators must be thread safe"));
958
    }
959
  }
960

961 962 963 964
  void CheckAllocThreadSafe() const {
    CheckAllocThreadSafe(allocators_);
    CheckAllocThreadSafe(zero_size_allocators_);
    CheckAllocThreadSafe(system_allocators_);
965
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
966
    if (is_stream_safe_cuda_allocator_used_) {
967 968 969
      CheckCUDAAllocThreadSafe(cuda_allocators_);
    }
#endif
970 971 972
  }

  void WrapCUDARetryAllocator(size_t retry_time) {
973
    PADDLE_ENFORCE_GT(
974 975
        retry_time,
        0,
976 977
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
978 979 980 981 982 983 984
    for (auto& pair : allocators_) {
      if (platform::is_gpu_place(pair.first)) {
        pair.second = std::make_shared<RetryAllocator>(pair.second, retry_time);
      }
    }
  }

985 986
  void WrapStatAllocator() {
    for (auto& pair : allocators_) {
987 988 989 990 991 992 993
      // 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);
      }
994 995 996
    }
  }

997 998
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  // a standalone CUDA allocator to support multi-stream GC in new executor
999 1000
  std::map<platform::Place, std::shared_ptr<StreamSafeCUDAAllocator>>
      default_stream_safe_cuda_allocators_;
1001
  CUDAAllocatorMap cuda_allocators_;
1002
  std::shared_timed_mutex cuda_allocator_mutex_;
1003 1004
#endif
  AllocatorStrategy strategy_;
1005
  AllocatorMap allocators_;
1006 1007
  static AllocatorMap zero_size_allocators_;
  static AllocatorMap system_allocators_;
1008
  bool allow_free_idle_chunk_;
1009
  bool is_stream_safe_cuda_allocator_used_;
1010
};
1011 1012 1013 1014
AllocatorFacadePrivate::AllocatorMap
    AllocatorFacadePrivate::zero_size_allocators_;
AllocatorFacadePrivate::AllocatorMap AllocatorFacadePrivate::system_allocators_;

Y
Refine  
Yu Yang 已提交
1015
// Pimpl. Make interface clean.
1016
AllocatorFacade::AllocatorFacade() : m_(new AllocatorFacadePrivate()) {}
1017 1018 1019
// delete m_ may cause core dump when the destructor of python in conflict with
// cpp.
AllocatorFacade::~AllocatorFacade() {}
1020 1021

AllocatorFacade& AllocatorFacade::Instance() {
1022 1023 1024 1025 1026 1027
  static AllocatorFacade* instance = new AllocatorFacade;
  return *instance;
}

AllocatorFacadePrivate* AllocatorFacade::GetPrivate() const {
#ifdef PADDLE_WITH_CUDA
1028
  if (UNLIKELY(IsCUDAGraphCapturing())) {
1029
    auto id = phi::backends::gpu::CUDAGraph::CapturingPoolID();
1030 1031
    auto iter = cuda_graph_map_.find(id);
    PADDLE_ENFORCE_NE(
1032 1033
        iter,
        cuda_graph_map_.end(),
1034 1035 1036 1037 1038 1039 1040
        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_;
1041 1042
}

1043 1044
const std::shared_ptr<Allocator>& AllocatorFacade::GetAllocator(
    const platform::Place& place) {
1045 1046
  return GetPrivate()->GetAllocator(
      place, /* A non-zero num to choose allocator_ */ 1);
1047 1048
}

1049
void* AllocatorFacade::GetBasePtr(
1050
    const std::shared_ptr<phi::Allocation>& allocation) {
1051 1052
  PADDLE_ENFORCE_EQ(GetAllocatorStrategy(),
                    AllocatorStrategy::kAutoGrowth,
1053 1054 1055 1056
                    paddle::platform::errors::Unimplemented(
                        "GetBasePtr() is only implemented for auto_growth "
                        "strategy, not support allocator strategy: %d",
                        static_cast<int>(GetAllocatorStrategy())));
1057 1058
  PADDLE_ENFORCE_EQ(platform::is_gpu_place(allocation->place()),
                    true,
1059 1060 1061 1062
                    paddle::platform::errors::Unimplemented(
                        "GetBasePtr() is only implemented for CUDAPlace(), not "
                        "suppot place: %s",
                        allocation->place()));
1063
  return GetPrivate()->GetBasePtr(allocation);
1064 1065
}

1066 1067
const std::shared_ptr<Allocator>& AllocatorFacade::GetZeroAllocator(
    const platform::Place& place) {
1068
  return GetPrivate()->GetAllocator(place, /* zero size */ 0);
1069 1070
}

1071
std::shared_ptr<phi::Allocation> AllocatorFacade::AllocShared(
1072
    const platform::Place& place, size_t size) {
1073
  return std::shared_ptr<phi::Allocation>(Alloc(place, size));
1074 1075
}

1076 1077
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size) {
1078
  return GetPrivate()->GetAllocator(place, size)->Allocate(size);
1079 1080
}

W
Wilber 已提交
1081
uint64_t AllocatorFacade::Release(const platform::Place& place) {
1082 1083
  return GetPrivate()
      ->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1)
1084 1085 1086
      ->Release(place);
}

1087 1088
std::shared_ptr<phi::Allocation> AllocatorFacade::AllocShared(
    const platform::Place& place, size_t size, const phi::Stream& stream) {
1089
  return std::shared_ptr<phi::Allocation>(Alloc(place, size, stream));
1090 1091
}

1092 1093
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size,
1094
                                     const phi::Stream& stream) {
1095
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1096 1097 1098 1099 1100
  AllocatorFacadePrivate* m = GetPrivate();
  if (!m->IsStreamSafeCUDAAllocatorUsed()) {
    VLOG(6) << "Warning: StreamSafeCUDAAllocator is not used!";
    return Alloc(place, size);
  }
1101

1102 1103 1104
  platform::CUDAPlace p(place.GetDeviceId());
  if (LIKELY(size > 0 && FLAGS_use_system_allocator == false)) {
    gpuStream_t s = reinterpret_cast<gpuStream_t>(stream.id());
1105
    return m->GetAllocator(p, s, /* create_if_not_found = */ true)
1106 1107
        ->Allocate(size);
  } else {
1108
    return m->GetAllocator(p, size)->Allocate(size);
1109
  }
1110
#elif defined(PADDLE_WITH_XPU) || defined(PADDLE_WITH_ASCEND_CL)
1111
  return GetAllocator(place)->Allocate(size);
1112
#else
1113 1114
  PADDLE_THROW(platform::errors::PreconditionNotMet(
      "Not compiled with GPU or XPU or NPU."));
1115 1116 1117
#endif
}

1118 1119 1120
bool AllocatorFacade::InSameStream(
    const std::shared_ptr<phi::Allocation>& allocation,
    const phi::Stream& stream) {
1121
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1122 1123 1124 1125
  gpuStream_t s = reinterpret_cast<gpuStream_t>(stream.id());
  return s == GetStream(allocation);
#else
  PADDLE_THROW(platform::errors::PreconditionNotMet("Not compiled with GPU."));
1126
#endif
1127 1128
}

1129 1130 1131 1132
bool AllocatorFacade::IsStreamSafeCUDAAllocatorUsed() {
  return GetPrivate()->IsStreamSafeCUDAAllocatorUsed();
}

1133
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
1134
uint64_t AllocatorFacade::Release(const platform::CUDAPlace& place,
1135
                                  gpuStream_t stream) {
1136 1137 1138 1139 1140 1141 1142
  AllocatorFacadePrivate* m = GetPrivate();
  if (!m->IsStreamSafeCUDAAllocatorUsed()) {
    VLOG(6) << "Warning: StreamSafeCUDAAllocator is not used!";
    return Release(place);
  }

  return m->GetAllocator(place, stream)->Release(place);
1143 1144
}

1145
void AllocatorFacade::RecordStream(std::shared_ptr<phi::Allocation> allocation,
1146
                                   gpuStream_t stream) {
1147
  GetPrivate()->RecordStream(allocation, stream);
1148 1149
}

1150
const std::shared_ptr<Allocator>& AllocatorFacade::GetAllocator(
1151
    const platform::Place& place, gpuStream_t stream) {
1152 1153 1154 1155 1156
  AllocatorFacadePrivate* m = GetPrivate();

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

  if (platform::is_gpu_place(place) && FLAGS_use_system_allocator == false) {
1160 1161
    return m->GetAllocator(place,
                           stream,
1162 1163 1164
                           /*create_if_not_found=*/true);
  }
  return m->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1);
1165 1166
}

1167
gpuStream_t AllocatorFacade::GetStream(
1168
    const std::shared_ptr<phi::Allocation>& allocation) const {
1169
  return GetPrivate()->GetStream(allocation);
1170 1171
}

1172
void AllocatorFacade::SetDefaultStream(const platform::CUDAPlace& place,
1173
                                       gpuStream_t stream) {
1174 1175
  if (m_->IsStreamSafeCUDAAllocatorUsed()) {
    m_->SetDefaultStream(place, stream);
1176 1177 1178
  }
}

1179
#ifdef PADDLE_WITH_CUDA
1180
void AllocatorFacade::PrepareMemoryPoolForCUDAGraph(int64_t id) {
1181 1182
  PADDLE_ENFORCE_EQ(GetAllocatorStrategy(),
                    AllocatorStrategy::kAutoGrowth,
1183 1184 1185 1186 1187 1188
                    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];
1189 1190 1191 1192 1193 1194 1195 1196 1197
  auto& ref_cnt = cuda_graph_ref_cnt_[id];
  if (allocator.get() == nullptr) {
    allocator.reset(
        new AllocatorFacadePrivate(/*allow_free_idle_chunk=*/false));
    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;
1198 1199
}

1200 1201
void AllocatorFacade::RemoveMemoryPoolOfCUDAGraph(int64_t id) {
  auto ref_cnt_iter = cuda_graph_ref_cnt_.find(id);
1202 1203
  PADDLE_ENFORCE_NE(ref_cnt_iter,
                    cuda_graph_ref_cnt_.end(),
1204
                    platform::errors::InvalidArgument(
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                        "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);
    VLOG(10) << "Remove memory pool of CUDA Graph with memory ID " << id;
  } else {
    VLOG(10) << "Decrease memory pool ID " << id << " reference count to be "
             << ref_cnt;
  }
1216 1217
}
#endif
1218
#endif
1219 1220 1221 1222

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

1223 1224 1225
}  // namespace allocation
}  // namespace memory
}  // namespace paddle