cpu_context.cc 2.0 KB
Newer Older
W
Wilber 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//   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.

#include "paddle/pten/backends/cpu/cpu_context.h"

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

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

namespace pten {

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 54
CPUContext::CPUContext()
    : DeviceContext(), impl_(std::make_unique<CPUContext::Impl>()) {}
W
Wilber 已提交
55

W
Wilber 已提交
56 57
CPUContext::CPUContext(const Place& place)
    : DeviceContext(), impl_(std::make_unique<CPUContext::Impl>(place)) {}
W
Wilber 已提交
58 59 60

CPUContext::~CPUContext() = default;

W
Wilber 已提交
61
void CPUContext::Init() { impl_->Init(); }
W
Wilber 已提交
62 63

Eigen::DefaultDevice* CPUContext::eigen_device() const {
W
Wilber 已提交
64
  return impl_->GetEigenDevice();
W
Wilber 已提交
65 66
}

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

W
Wilber 已提交
69
void CPUContext::SetEigenDevice(Eigen::DefaultDevice* device) {
W
Wilber 已提交
70
  impl_->eigen_device_ = device;
W
Wilber 已提交
71 72 73
}

}  // namespace pten