fetch_op_handle.cc 6.6 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//   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.

#include "paddle/fluid/framework/details/fetch_op_handle.h"
16

17
#include <string>
18

19
#include "paddle/fluid/platform/profiler.h"
20

Y
Yu Yang 已提交
21 22 23 24
namespace paddle {
namespace framework {
namespace details {

Z
Zhen Wang 已提交
25 26 27 28
FetchOpHandle::FetchOpHandle(ir::Node *node, FetchResultType *data,
                             size_t offset, std::vector<Scope *> *local_scopes,
                             std::vector<Scope *> *local_exec_scopes,
                             bool return_merged)
X
Xin Pan 已提交
29 30 31
    : OpHandleBase(node),
      data_(data),
      offset_(offset),
32
      local_scopes_(local_scopes),
Z
Zhen Wang 已提交
33 34
      local_exec_scopes_(local_exec_scopes),
      return_merged_(return_merged) {}
Y
Yu Yang 已提交
35

X
Xin Pan 已提交
36
FetchOpHandle::~FetchOpHandle() {}
Y
Yu Yang 已提交
37

C
chengduoZH 已提交
38
void FetchOpHandle::RecordWaitEventOnCtx(platform::DeviceContext *waited_ctx) {
39 40
  PADDLE_THROW(platform::errors::PermissionDenied(
      "No nodes need to wait FetchOp. Unexpceted Error."));
Y
Yu Yang 已提交
41 42
}

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
static void CheckDims(const framework::DDim &tensor_dims,
                      const framework::DDim &ele_dims, const size_t offset) {
  PADDLE_ENFORCE_EQ(
      tensor_dims.size(), ele_dims.size(),
      platform::errors::Fatal("The dimension sizes of fetched Tensors or "
                              "the items of fetched LoDTensorArray are "
                              "different from each other on different "
                              "devices. And the error is caused by the %zu "
                              "(th) fetched variable. Please set the "
                              "parameter `return_merged = False` when you "
                              "call the `Executor.run()` method.",
                              offset));
  for (int j = 1; j < tensor_dims.size(); j++) {
    PADDLE_ENFORCE_EQ(
        tensor_dims[j], ele_dims[j],
        platform::errors::Fatal("The dimensions of fetched Tensors or "
                                "the items of fetched LoDTensorArray are "
                                "different from each other on different "
                                "devices. And the error is caused by the "
                                "%zu (th) fetched variable. Please set the "
                                "parameter `return_merged = False` when "
                                "you call the `Executor.run()` method.",
                                offset));
  }
}

void FetchOpHandle::WaitAndMergeCPUFetchVars() const {
Z
Zhen Wang 已提交
70
  if (return_merged_) {
71
    if (data_is_lod_tensor(tensors_[0])) {
72
      const auto &tensor_dims = BOOST_GET_CONST(LoDTensor, tensors_[0]).dims();
73
      for (size_t i = 1; i < tensors_.size(); i++) {
74
        const auto &ele_dims = BOOST_GET_CONST(LoDTensor, tensors_[i]).dims();
75
        CheckDims(tensor_dims, ele_dims, offset_);
Z
Zhen Wang 已提交
76
      }
77 78 79
      std::vector<const LoDTensor *> tensors_ptr;
      tensors_ptr.reserve(tensors_.size());
      for (auto &t : tensors_) {
80
        tensors_ptr.emplace_back(&BOOST_GET_CONST(LoDTensor, t));
81
      }
82
      auto &val = BOOST_GET(FetchList, *data_);
83 84 85 86
      LoDTensor var;
      var.MergeLoDTensor(tensors_ptr, platform::CPUPlace());
      val.at(offset_) = std::move(var);
    } else {
87
      auto &array = BOOST_GET_CONST(LoDTensorArray, tensors_[0]);
88 89 90 91 92 93 94 95
      LoDTensorArray tmp_array;
      tmp_array.reserve(array.size());
      for (size_t i = 0; i < array.size(); ++i) {
        const auto &tensor_dims = array[i].dims();
        std::vector<const LoDTensor *> tensors_ptr;
        tensors_ptr.reserve(tensors_.size());
        tensors_ptr.push_back(&array[i]);
        for (size_t j = 1; j < tensors_.size(); ++j) {
96
          auto &element = BOOST_GET_CONST(LoDTensorArray, tensors_[j]);
97 98 99 100 101 102 103
          const auto &ele_dims = element[i].dims();
          CheckDims(tensor_dims, ele_dims, offset_);
          tensors_ptr.push_back(&element[i]);
        }
        tmp_array.emplace_back();
        tmp_array.back().MergeLoDTensor(tensors_ptr, platform::CPUPlace());
      }
104
      auto &val = BOOST_GET(FetchList, *data_);
105
      val.at(offset_) = std::move(tmp_array);
Z
Zhen Wang 已提交
106 107
    }
  } else {
108
    auto &val = BOOST_GET(FetchUnmergedList, *data_);
Z
Zhen Wang 已提交
109
    val.at(offset_) = std::move(tensors_);
Y
Yu Yang 已提交
110 111 112
  }
}

113 114 115 116 117 118 119 120
static void TransData(const framework::LoDTensor &src_item,
                      framework::LoDTensor *dst_item) {
  if (src_item.IsInitialized() && src_item.numel() > 0) {
    if (platform::is_gpu_place(src_item.place())) {
#ifdef PADDLE_WITH_CUDA
      TensorCopy(src_item, platform::CPUPlace(), dst_item);
#endif
    } else {
121
      TensorCopy(src_item, platform::CPUPlace(), dst_item);
122 123 124 125 126 127 128 129
    }
  } else {
    dst_item->clear();
    dst_item->Resize({0});
  }
  dst_item->set_lod(src_item.lod());
}

Y
Yu Yang 已提交
130
void FetchOpHandle::RunImpl() {
131
  platform::RecordEvent record_event(Name());
C
chengduoZH 已提交
132 133
  WaitInputVarGenerated(platform::CPUPlace());

Y
Yu Yang 已提交
134
  tensors_.resize(inputs_.size());
135
  auto &scopes = *local_exec_scopes_;
Y
Yu Yang 已提交
136

C
chengduoZH 已提交
137 138
  for (size_t i = 0; i < inputs_.size(); ++i) {
    auto *var_handle = static_cast<VarHandle *>(inputs_[i]);
G
gongweibao 已提交
139
    auto &scope = scopes.at(var_handle->scope_idx());
140
    auto *var = scope->FindVar(var_handle->name());
141 142 143 144
    PADDLE_ENFORCE_NOT_NULL(
        var,
        platform::errors::NotFound(
            "Cannot find variable %s in execution scope.", var_handle->name()));
C
chengduoZH 已提交
145

146 147
    if (var->IsType<LoDTensor>()) {
      auto &t = var->Get<framework::LoDTensor>();
148
      auto &item = BOOST_GET(LoDTensor, tensors_[i]);
149
      TransData(t, &item);
Y
Yu Yang 已提交
150
    } else {
151 152 153
      auto &t = var->Get<framework::LoDTensorArray>();
      LoDTensorArray tmp(t.size());
      tensors_[i] = tmp;
154
      auto &item = BOOST_GET(LoDTensorArray, tensors_[i]);
155 156 157
      for (size_t j = 0; j < t.size(); ++j) {
        TransData(t[j], &item[j]);
      }
Y
Yu Yang 已提交
158 159
    }
  }
160
  this->WaitAndMergeCPUFetchVars();
Y
Yu Yang 已提交
161 162
}

C
chengduoZH 已提交
163 164 165
void FetchOpHandle::WaitInputVarGenerated(const platform::Place &place) {
  auto cpu_ctx = platform::DeviceContextPool::Instance().Get(place);
  for (auto *input : inputs_) {
X
Xin Pan 已提交
166 167
    if (input->GeneratedOp()) {
      input->GeneratedOp()->RecordWaitEventOnCtx(cpu_ctx);
C
chengduoZH 已提交
168 169 170 171
    }
  }
}

172 173
bool FetchOpHandle::IsMultiDeviceTransfer() { return true; }

Y
Yu Yang 已提交
174 175
std::string FetchOpHandle::Name() const { return "Fetch"; }

Y
Yu Yang 已提交
176 177 178
}  // namespace details
}  // namespace framework
}  // namespace paddle