cpu_context.cc 2.4 KB
Newer Older
W
Wilber 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
//   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"

// NOTE: The paddle framework should add WITH_EIGEN option to support compile
// without eigen.
#include "unsupported/Eigen/CXX11/Tensor"

namespace pten {

struct CPUContext::CPUImpl {
  CPUImpl() { device_ = new Eigen::DefaultDevice(); }

  // Users need to manage external resources.
  explicit CPUImpl(const CPUContextResource& ctx_res) : res_(ctx_res) {
    device_ = res_.device;
  }

  ~CPUImpl() {
W
Wilber 已提交
34
    if (res_.device == nullptr && device_ != nullptr) {
W
Wilber 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
      delete device_;
      device_ = nullptr;
    }
  }

  Eigen::DefaultDevice* GetEigenDevice() const {
    PD_CHECK(device_ != nullptr, "the eigen_device is nullptr.");
    return device_;
  }

  void SetEigenDevice(Eigen::DefaultDevice* device) {
    if (device == nullptr) {
      return;
    }
    res_.device = device;
    device_ = device;
  }

  Place GetPlace() const { return place_; }
W
Wilber 已提交
54 55 56 57

  Eigen::DefaultDevice* device_{nullptr};
  CPUContextResource res_;
  CPUPlace place_;
W
Wilber 已提交
58 59
};

W
Wilber 已提交
60
CPUContext::CPUContext() : DeviceContext() {
W
Wilber 已提交
61 62 63
  cpu_impl_ = std::make_unique<CPUImpl>();
}

W
Wilber 已提交
64
CPUContext::CPUContext(const CPUContext& other) : DeviceContext() {
W
Wilber 已提交
65 66 67 68
  cpu_impl_ = std::make_unique<CPUImpl>();
  cpu_impl_->SetEigenDevice(other.eigen_device());
}

W
Wilber 已提交
69
CPUContext::CPUContext(CPUContext&& other) : DeviceContext() {
W
Wilber 已提交
70 71 72 73 74
  cpu_impl_ = std::move(other.cpu_impl_);
}

CPUContext::~CPUContext() = default;

W
Wilber 已提交
75
CPUContext::CPUContext(const CPUContextResource& ctx_res) : DeviceContext() {
W
Wilber 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89
  cpu_impl_ = std::make_unique<CPUImpl>(ctx_res);
}

Eigen::DefaultDevice* CPUContext::eigen_device() const {
  return cpu_impl_->GetEigenDevice();
}

void CPUContext::SetEigenDevice(Eigen::DefaultDevice* device) {
  cpu_impl_->SetEigenDevice(device);
}

Place CPUContext::GetPlace() const { return cpu_impl_->GetPlace(); }

}  // namespace pten