fetch_async_op_handle.cc 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//   Copyright (c) 2020 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_async_op_handle.h"
16

17
#include <string>
18

19
#include "paddle/fluid/framework/convert_utils.h"
20
#include "paddle/fluid/platform/profiler.h"
21
#include "paddle/fluid/platform/profiler/event_tracing.h"
22 23 24 25 26

namespace paddle {
namespace framework {
namespace details {

27 28
FetchAsyncOpHandle::FetchAsyncOpHandle(ir::Node *node,
                                       FetchResultType *data,
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
                                       size_t offset,
                                       std::vector<Scope *> *local_scopes,
                                       std::vector<Scope *> *local_exec_scopes,
                                       bool return_merged)
    : OpHandleBase(node),
      data_(data),
      offset_(offset),
      local_scopes_(local_scopes),
      local_exec_scopes_(local_exec_scopes),
      return_merged_(return_merged) {}

FetchAsyncOpHandle::~FetchAsyncOpHandle() {}

void FetchAsyncOpHandle::RecordWaitEventOnCtx(
    platform::DeviceContext *waited_ctx) {
  PADDLE_THROW(platform::errors::PermissionDenied(
      "No nodes need to wait FetchAsyncOp. Unexpceted Error."));
}

static void CheckTensorAttrs(const LoDTensor *tensor,
                             const proto::VarType::Type &type,
50 51 52 53
                             const DataLayout &layout,
                             const DDim &dims,
                             const LoD &lod,
                             const size_t offset) {
54 55 56
  if (tensor->numel() && tensor->IsInitialized()) {
    // step1: check type
    PADDLE_ENFORCE_EQ(
57 58
        type,
        framework::TransToProtoVarType(tensor->dtype()),
59 60 61 62 63 64 65
        platform::errors::InvalidArgument(
            "The data type of fetched Tensors or the items of fetched "
            "LoDTensorArray are different from each other on different "
            "devices(%s vs %s). 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.",
66 67 68
            DataTypeToString(type),
            tensor->dtype(),
            offset));
69 70 71

    // step2: check layout
    PADDLE_ENFORCE_EQ(
72 73
        layout,
        tensor->layout(),
74 75 76 77 78 79 80
        platform::errors::InvalidArgument(
            "The layout of fetched Tensors or the items of fetched "
            "LoDTensorArray are different from each other on different "
            "devices(%s vs %s). 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.",
81 82
            DataLayoutToString(layout),
            DataLayoutToString(tensor->layout()),
83 84 85 86 87
            offset));
  }

  // step3: check dims
  auto tensor_dims = tensor->dims();
88 89
  PADDLE_ENFORCE_EQ(dims.size(),
                    tensor_dims.size(),
90 91 92 93 94 95 96 97
                    platform::errors::InvalidArgument(
                        "The dimension sizes of fetched Tensors or "
                        "the items of fetched LoDTensorArray are "
                        "different from each other on different "
                        "devices(%s vs %s). 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.",
98 99 100
                        dims,
                        tensor_dims,
                        offset));
101
  for (int j = 1; j < dims.size(); j++) {
102 103
    PADDLE_ENFORCE_EQ(dims[j],
                      tensor_dims[j],
104 105 106 107 108 109 110 111
                      platform::errors::InvalidArgument(
                          "The dimensions of fetched Tensors or "
                          "the items of fetched LoDTensorArray are "
                          "different from each other on different "
                          "devices(%s vs %s). 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.",
112 113 114
                          dims,
                          tensor_dims,
                          offset));
115 116 117 118
  }

  // step4: check lod
  PADDLE_ENFORCE_EQ(
119 120
      lod.size(),
      tensor->lod().size(),
121 122 123 124 125 126 127
      platform::errors::InvalidArgument(
          "The LoD information of fetched Tensors or the items of fetched "
          "LoDTensorArray are different from each other on different "
          "devices(%s vs %s). 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.",
128 129 130
          lod,
          tensor->lod(),
          offset));
131 132
}

133 134
static void TransData(const phi::DenseTensor *src_item,
                      phi::DenseTensor *dst_item,
135 136 137
                      const platform::DeviceContext &ctx) {
  if (src_item->IsInitialized() && src_item->numel() > 0) {
    if (platform::is_gpu_place(src_item->place())) {
138
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
      TensorCopy(*src_item, platform::CUDAPinnedPlace(), ctx, dst_item);
#endif
    } else {
      TensorCopy(*src_item, platform::CPUPlace(), dst_item);
    }
  }
}

void FetchAsyncOpHandle::FetchMergedLodTensor(
    const std::vector<const LoDTensor *> &src_lodtensors,
    LoDTensor *dst_lodtensor) {
  // calc dst type,layout,dim,lod and calc check dim
  proto::VarType::Type new_type = proto::VarType::FP32;
  framework::DataLayout new_layout;
  framework::DDim new_dim;
  LoD new_lod = src_lodtensors[0]->lod();

  framework::DDim check_dim;

  for (auto *t : src_lodtensors) {
    if (t->numel() && t->IsInitialized()) {
      check_dim = t->dims();
161
      new_type = paddle::framework::TransToProtoVarType(t->dtype());
162 163 164 165 166 167 168
      new_layout = t->layout();
      break;
    }
  }

  // check src type,layout,dim,lod consistence
  for (size_t i = 1; i < src_lodtensors.size(); ++i) {
169 170
    CheckTensorAttrs(
        src_lodtensors[i], new_type, new_layout, check_dim, new_lod, offset_);
171 172
  }

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  auto rank = src_lodtensors[0]->dims().size();

  // for 0D tensor, can't concat eath tensor. So stack 0D and concat 1+D tensor
  if (rank == 0) {
    int src_lodtensor_size = src_lodtensors.size();
    new_dim = phi::make_ddim(std::vector<int>({src_lodtensor_size}));
  } else {
    bool find_first_dims = false;
    for (auto *t : src_lodtensors) {
      if (t->numel() && t->IsInitialized()) {
        if (!find_first_dims) {
          new_dim = t->dims();
          find_first_dims = true;
        } else {
          new_dim[0] += t->dims()[0];
        }
      }
    }
  }

193 194 195 196 197 198
  // set dst tensor
  dst_lodtensor->Resize(new_dim);
  dst_lodtensor->set_layout(src_lodtensors[0]->layout());
  dst_lodtensor->set_lod(src_lodtensors[0]->lod());
  if (platform::is_gpu_place(src_lodtensors[0]->place())) {
    dst_lodtensor->mutable_data(platform::CUDAPinnedPlace(),
199
                                src_lodtensors[0]->dtype());
200 201
  } else {
    dst_lodtensor->mutable_data(platform::CPUPlace(),
202
                                src_lodtensors[0]->dtype());
203 204 205
  }

  // slice and memcpy
206 207
  // for 0D tensor, can't concat eath tensor, stack them. for 1+D tensor, concat
  // them
208
  int begin = 0;
209
  int end = 0;
210
  for (auto *src : src_lodtensors) {
211 212 213 214 215 216
    if (rank == 0) {
      end = begin + 1;
    } else {
      end = begin + src->dims()[0];
    }

217 218 219 220 221 222 223 224 225 226
    if (end == begin) {
      continue;
    }
    auto dst = dst_lodtensor->Slice(begin, end);
    TransData(src, &dst, *dev_ctxes_[src->place()]);
    begin = end;
  }
}

void FetchAsyncOpHandle::RunImpl() {
227 228
  platform::RecordEvent record_event(
      Name(), platform::TracerEventType::Operator, 1);
229
  WaitInputVarGenerated(true);
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

  // get src vars
  auto &scopes = *local_exec_scopes_;
  std::vector<Variable *> src_vars;
  src_vars.reserve(inputs_.size());
  for (size_t i = 0; i < inputs_.size(); ++i) {
    auto *var_handle = static_cast<VarHandle *>(inputs_[i]);
    auto &scope = scopes.at(var_handle->scope_idx());
    auto *var = scope->FindVar(var_handle->name());
    PADDLE_ENFORCE_NOT_NULL(
        var,
        platform::errors::NotFound(
            "Cannot find variable %s in execution scope.", var_handle->name()));
    src_vars.emplace_back(var);
  }

  if (return_merged_) {
R
Ruibiao Chen 已提交
247
    auto &val = PADDLE_GET(FetchList, *data_);
248 249 250 251 252
    if (src_vars[0]->IsType<LoDTensor>()) {
      // to lodtensor type
      std::vector<const LoDTensor *> src_lodtensors;
      src_lodtensors.reserve(src_vars.size());
      for (size_t i = 0; i < src_vars.size(); ++i) {
253
        src_lodtensors.emplace_back(&src_vars[i]->Get<phi::DenseTensor>());
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      }

      LoDTensor dst_lodtensor;
      FetchMergedLodTensor(src_lodtensors, &dst_lodtensor);
      val.at(offset_) = std::move(dst_lodtensor);
    } else {
      // to lodtensorarray type
      std::vector<const LoDTensorArray *> src_lodtensor_arrays;
      src_lodtensor_arrays.reserve(src_vars.size());
      for (size_t i = 0; i < src_vars.size(); ++i) {
        src_lodtensor_arrays.emplace_back(
            &src_vars[i]->Get<framework::LoDTensorArray>());
      }

      LoDTensorArray dst_lodtensor_array;
      dst_lodtensor_array.resize(src_lodtensor_arrays[0]->size());

      for (size_t i = 0; i < dst_lodtensor_array.size(); ++i) {
        std::vector<const LoDTensor *> src_lodtensors;
        src_lodtensors.reserve(src_lodtensor_arrays.size());
        for (size_t j = 0; j < src_lodtensor_arrays.size(); ++j) {
          src_lodtensors.emplace_back(&(*src_lodtensor_arrays[j])[i]);
        }
        FetchMergedLodTensor(src_lodtensors, &dst_lodtensor_array[i]);
      }
      val.at(offset_) = std::move(dst_lodtensor_array);
    }
  } else {
R
Ruibiao Chen 已提交
282
    auto &val = PADDLE_GET(FetchUnmergedList, *data_);
283 284 285 286 287
    auto &dst_tensors = val.at(offset_);
    dst_tensors.reserve(src_vars.size());

    for (size_t i = 0; i < src_vars.size(); ++i) {
      if (src_vars[i]->IsType<LoDTensor>()) {
288
        auto &t = src_vars[i]->Get<phi::DenseTensor>();
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        LoDTensor item;
        TransData(&t, &item, *dev_ctxes_[t.place()]);
        dst_tensors.emplace_back(std::move(item));
      } else {
        auto &t = src_vars[i]->Get<framework::LoDTensorArray>();
        LoDTensorArray item;
        item.resize(t.size());
        for (size_t j = 0; j < t.size(); ++j) {
          TransData(&t[j], &item[j], *dev_ctxes_[t[j].place()]);
        }
        dst_tensors.emplace_back(std::move(item));
      }
    }
  }
}

bool FetchAsyncOpHandle::IsMultiDeviceTransfer() { return true; }

std::string FetchAsyncOpHandle::Name() const { return "FetchAsync"; }

}  // namespace details
}  // namespace framework
}  // namespace paddle