cpu_context.cc 2.1 KB
Newer Older
W
Wilber 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//   Copyright (c) 2022 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
#include "paddle/phi/backends/cpu/cpu_context.h"
W
Wilber 已提交
16

17 18
#include "paddle/phi/api/ext/exception.h"
#include "paddle/phi/common/place.h"
W
Wilber 已提交
19 20 21

// NOTE: The paddle framework should add WITH_EIGEN option to support compile
// without eigen.
22
#include "paddle/phi/core/device_context.h"
W
Wilber 已提交
23 24
#include "unsupported/Eigen/CXX11/Tensor"

25
namespace phi {
W
Wilber 已提交
26

W
Wilber 已提交
27 28
struct CPUContext::Impl {
  Impl() : place_(CPUPlace()) {}
W
Wilber 已提交
29

W
Wilber 已提交
30
  explicit Impl(const Place& place) : place_(place) {}
W
Wilber 已提交
31

W
Wilber 已提交
32 33 34
  ~Impl() {
    if (owned_) {
      delete eigen_device_;
W
Wilber 已提交
35 36 37
    }
  }

W
Wilber 已提交
38 39 40
  void Init() {
    owned_ = true;
    eigen_device_ = new Eigen::DefaultDevice();
W
Wilber 已提交
41 42
  }

W
Wilber 已提交
43 44 45
  Eigen::DefaultDevice* GetEigenDevice() const {
    PD_CHECK(eigen_device_ != nullptr, "the cpu eigen_device is nullptr.");
    return eigen_device_;
W
Wilber 已提交
46 47
  }

W
Wilber 已提交
48 49 50
  bool owned_{false};
  Eigen::DefaultDevice* eigen_device_{nullptr};
  Place place_;
W
Wilber 已提交
51 52
};

W
Wilber 已提交
53
CPUContext::CPUContext()
L
Leo Chen 已提交
54 55 56
    : DeviceContext(), impl_(std::make_unique<CPUContext::Impl>()) {
  impl_->Init();
}
W
Wilber 已提交
57

W
Wilber 已提交
58
CPUContext::CPUContext(const Place& place)
L
Leo Chen 已提交
59 60 61
    : DeviceContext(), impl_(std::make_unique<CPUContext::Impl>(place)) {
  impl_->Init();
}
W
Wilber 已提交
62 63 64

CPUContext::~CPUContext() = default;

65 66 67 68
CPUContext::CPUContext(CPUContext&&) = default;

CPUContext& CPUContext::operator=(CPUContext&&) = default;

W
Wilber 已提交
69
Eigen::DefaultDevice* CPUContext::eigen_device() const {
W
Wilber 已提交
70
  return impl_->GetEigenDevice();
W
Wilber 已提交
71 72
}

W
Wilber 已提交
73 74
const Place& CPUContext::GetPlace() const { return impl_->place_; }

W
Wilber 已提交
75
void CPUContext::SetEigenDevice(Eigen::DefaultDevice* device) {
W
Wilber 已提交
76
  impl_->eigen_device_ = device;
W
Wilber 已提交
77 78
}

79
}  // namespace phi