retry_allocator.h 2.1 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 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.

#pragma once

17
#include <atomic>              // NOLINT
S
sneaxiy 已提交
18 19 20 21
#include <chrono>              // NOLINT
#include <condition_variable>  // NOLINT
#include <memory>
#include <mutex>  // NOLINT
S
sneaxiy 已提交
22
#include <utility>
23

S
sneaxiy 已提交
24
#include "paddle/fluid/memory/allocation/allocator.h"
25
#include "paddle/fluid/platform/enforce.h"
S
sneaxiy 已提交
26 27 28 29 30

namespace paddle {
namespace memory {
namespace allocation {

Y
Yu Yang 已提交
31
class RetryAllocator : public Allocator {
Y
Yu Yang 已提交
32
 public:
Z
Zeng Jinle 已提交
33
  RetryAllocator(std::shared_ptr<Allocator> allocator, size_t retry_ms)
Y
Yu Yang 已提交
34
      : underlying_allocator_(std::move(allocator)), retry_time_(retry_ms) {
S
sneaxiy 已提交
35
    PADDLE_ENFORCE_NOT_NULL(
Z
Zeng Jinle 已提交
36
        underlying_allocator_,
37 38 39 40 41 42
        platform::errors::InvalidArgument(
            "Underlying allocator of RetryAllocator is NULL"));
    PADDLE_ENFORCE_EQ(
        underlying_allocator_->IsAllocThreadSafe(), true,
        platform::errors::PreconditionNotMet(
            "Underlying allocator of RetryAllocator is not thread-safe"));
S
sneaxiy 已提交
43 44
  }

Z
Zeng Jinle 已提交
45 46
  bool IsAllocThreadSafe() const override { return true; }

Y
Yu Yang 已提交
47
 protected:
48 49
  void FreeImpl(pten::Allocation* allocation) override;
  pten::Allocation* AllocateImpl(size_t size) override;
W
Wilber 已提交
50 51
  uint64_t ReleaseImpl(const platform::Place& place) override {
    return underlying_allocator_->Release(place);
52
  }
Y
Yu Yang 已提交
53 54

 private:
Z
Zeng Jinle 已提交
55
  std::shared_ptr<Allocator> underlying_allocator_;
S
sneaxiy 已提交
56 57 58 59
  std::chrono::milliseconds retry_time_;
  std::mutex mutex_;
  std::condition_variable cv_;

60
  std::atomic<size_t> waited_allocate_size_{0};
S
sneaxiy 已提交
61 62 63 64 65
};

}  // namespace allocation
}  // namespace memory
}  // namespace paddle